fix(runtime): 按参考主题硬切换为 loader/main/auto_fun 单一 DOM 生命周期

- 删除 AksrtFrontend registry/rehydrate 双路架构及 build/public.js 拼包入口,
  前台唯一初始路径为 PHP 本地栈(jQuery 1.9.1 → Bootstrap 3.4.1)
  → loader_js(_win/aksrtData 唯一注入)→ tbquire(['main']) → runtime/main.min.js
- window.auto_fun = debounce(z_auto_fun, 100) 为唯一重扫入口;所有模块改为
  执行一次 + off/on('auto_fun.aksrt-*') 命名空间重扫,data/class 标记幂等
- 局部更新协议统一:HTML 注入 → post_ajax.ed → auto_fun();
  远程 modal → loaded.bs.modal → auto_fun();JSON 成功 → zib_ajax.success
- 灯箱恢复 Miniimgbox/imgbox 唯一 owner(imgbox-container、a[data-imgbox]、
  imgbox_data),删除 AksrtLightbox/data-aksrt-lightbox 第二实现及 CSS/overlay,
  _win.imgbox* 重新接上 post-display 设置
- 死代码清理:runtime 下 11 组被自有实现替代的旧模块副本、无消费 vendored 库、
  顶层 grade.min.js、revenue.js、无调用方的 aksrt_get_win_runtime_config(),
  以及 loader 中 16 条死 mapping
- PHP 入队改为本地栈 + loader_js,routed/widget/submit 依赖统一换绑;
  用户卡片发布按钮恢复 nav_user_newposts_btn 设置门控
- 测试对齐:新增 frontend-lifecycle-contract,重写 navigation/lazyload/toast/
  auth-source/comment/page-display/post-visual 等断言为目标架构契约

验证:node --test widget-system+navigation 223 通过 0 失败;
构建脚本重建 main/imgbox min 与 CSS bundles;改动 PHP php -l、JS node --check
全部通过;git diff --check 干净;credits 重入 harness 通过。
This commit is contained in:
2026-09-03 12:44:31 +08:00
parent 1cd81fb61a
commit 5fd7c212ed
124 changed files with 2128 additions and 17328 deletions
+1 -5
View File
@@ -44,14 +44,10 @@
!/tests/widget-system/pay-orders-filter-contract.test.cjs
!/tests/widget-system/front-submit-editor-contract.test.cjs
!/tests/widget-system/comment-smilies-removal-contract.test.cjs
!/tests/widget-system/lightbox-contract.test.cjs
!/tests/widget-system/homepage-dom-contract.test.cjs
!/tests/widget-system/rehydrate-runtime-contract.test.cjs
!/tests/widget-system/global-dom-init-contract.test.cjs
!/tests/widget-system/public-bundle-parity-contract.test.cjs
!/tests/widget-system/comment-children-list-reset-contract.test.cjs
!/tests/widget-system/pay-card-contract.test.cjs
!/tests/widget-system/circular-button-icon-margin-contract.test.cjs
!/tests/widget-system/frontend-lifecycle-contract.test.cjs
!/tests/asset-ledger/
!/tests/asset-ledger/*.php
!/tests/visual/docker-compose.zibll.yml
File diff suppressed because one or more lines are too long
+1 -8
View File
File diff suppressed because one or more lines are too long
+2 -251
View File
@@ -234,257 +234,8 @@ body.aksrt-body-scroll .aksrt-show-on-scroll {
transition: opacity 0.3s, visibility 0.3s;
}
/* ============================================================
* 5. 图片灯箱
* ============================================================ */
[data-aksrt-lightbox="1"] img:not(.no-imgbox):not(.no-lightbox),
.aksrt-lightbox-trigger img:not(.no-imgbox):not(.no-lightbox),
.imgbox-container img:not(.no-imgbox):not(.no-lightbox),
.comment-content .box-img {
/* 可缩放图片的光标 */
.aksrt-cursor-zoom-in {
cursor: zoom-in;
}
.aksrt-lightbox {
--imgbox-origin-left: 50vw;
--imgbox-origin-top: 50vh;
position: fixed;
inset: 0;
z-index: 100000;
display: flex;
align-items: center;
justify-content: center;
background: rgba(0, 0, 0, 0.88);
opacity: 0;
visibility: hidden;
transition: opacity 0.25s ease, visibility 0.25s ease;
}
.aksrt-lightbox.is-open {
opacity: 1;
visibility: visible;
}
.aksrt-lightbox__stage {
position: absolute;
inset: 64px 72px 82px;
display: flex;
align-items: center;
justify-content: center;
overflow: hidden;
}
.aksrt-lightbox__img {
display: block;
max-width: 100%;
max-height: 100%;
width: auto;
height: auto;
object-fit: contain;
transform: scale(1);
transform-origin: center;
transition: transform 0.25s ease, opacity 0.2s ease;
cursor: zoom-in;
user-select: none;
-webkit-user-drag: none;
}
.aksrt-lightbox.from-origin.is-open .aksrt-lightbox__img {
animation: aksrt-lightbox-enter 0.3s ease both;
}
.aksrt-lightbox.is-zoomed .aksrt-lightbox__img {
cursor: zoom-out;
}
.aksrt-lightbox__toolbar {
position: absolute;
z-index: 3;
top: 14px;
right: 14px;
display: flex;
align-items: center;
gap: 8px;
}
.aksrt-lightbox__tool,
.aksrt-lightbox__nav {
border: 0;
background: rgba(255, 255, 255, 0.14);
color: #fff;
box-shadow: none;
cursor: pointer;
transition: background-color 0.2s ease, transform 0.2s ease;
}
.aksrt-lightbox__tool {
display: inline-flex;
align-items: center;
justify-content: center;
width: 38px;
height: 38px;
padding: 0;
border-radius: 999px;
font-size: 16px;
}
.aksrt-lightbox__tool:hover,
.aksrt-lightbox__tool:focus-visible,
.aksrt-lightbox__nav:hover,
.aksrt-lightbox__nav:focus-visible {
background: rgba(255, 255, 255, 0.28);
color: #fff;
}
.aksrt-lightbox__tool:focus-visible,
.aksrt-lightbox__nav:focus-visible,
.aksrt-lightbox__thumb:focus-visible {
outline: 2px solid #fff;
outline-offset: 2px;
}
.aksrt-lightbox__counter {
min-width: 48px;
color: rgba(255, 255, 255, 0.84);
font-size: 14px;
text-align: center;
}
.aksrt-lightbox__nav {
position: absolute;
z-index: 2;
top: 50%;
display: inline-flex;
align-items: center;
justify-content: center;
width: 48px;
height: 48px;
border-radius: 999px;
font-size: 22px;
transform: translateY(-50%);
}
.aksrt-lightbox__nav--prev {
left: 16px;
}
.aksrt-lightbox__nav--next {
right: 16px;
}
.aksrt-lightbox__caption {
position: absolute;
z-index: 2;
right: 20px;
bottom: 18px;
left: 20px;
color: rgba(255, 255, 255, 0.88);
font-size: 14px;
line-height: 1.6;
text-align: center;
pointer-events: none;
}
.aksrt-lightbox__thumbs {
position: absolute;
z-index: 3;
right: 50%;
bottom: 18px;
display: flex;
gap: 8px;
max-width: min(70vw, 760px);
padding: 6px;
overflow-x: auto;
border-radius: 8px;
background: rgba(0, 0, 0, 0.38);
transform: translateX(50%);
scrollbar-width: thin;
}
.aksrt-lightbox__thumb {
flex: 0 0 auto;
width: 56px;
height: 44px;
padding: 0;
overflow: hidden;
border: 2px solid transparent;
border-radius: 5px;
background: transparent;
opacity: 0.6;
cursor: pointer;
}
.aksrt-lightbox__thumb.is-active {
border-color: #fff;
opacity: 1;
}
.aksrt-lightbox__thumb img {
display: block;
width: 100%;
height: 100%;
object-fit: cover;
}
.aksrt-lightbox__thumbs:not([hidden]) ~ .aksrt-lightbox__caption {
bottom: 78px;
}
.aksrt-lightbox [hidden] {
display: none !important;
}
@keyframes aksrt-lightbox-enter {
from {
transform-origin: var(--imgbox-origin-left) var(--imgbox-origin-top);
transform: scale(0.82);
opacity: 0;
}
to {
transform-origin: center;
transform: scale(1);
opacity: 1;
}
}
@media (max-width: 767px) {
.aksrt-lightbox__stage {
inset: 58px 10px 78px;
}
.aksrt-lightbox__toolbar {
top: 10px;
right: 10px;
gap: 5px;
}
.aksrt-lightbox__tool {
width: 34px;
height: 34px;
font-size: 14px;
}
.aksrt-lightbox__counter {
min-width: 36px;
font-size: 12px;
}
.aksrt-lightbox__nav {
width: 40px;
height: 40px;
font-size: 18px;
background: rgba(0, 0, 0, 0.34);
}
.aksrt-lightbox__nav--prev {
left: 8px;
}
.aksrt-lightbox__nav--next {
right: 8px;
}
.aksrt-lightbox__thumbs {
max-width: calc(100vw - 20px);
}
}
+7 -2
View File
@@ -7431,7 +7431,12 @@ badge.top,
color: var(--this-bg-b);
}
.imgbox {
display: none;
}
.comment-content .box-img,
.alone-imgbox-img,
.cursor-zoom-in {
cursor: zoom-in;
}
@@ -8104,7 +8109,7 @@ badge.top,
body:has(.modal.in) .float-right,
.modal-open .float-right,
.aksrt-lightbox-open .float-right,
.imgbox-show .float-right,
.scroll-down .scroll-down-hide.float-right,
.scroll-ing .scrolling-hide.float-right {
transform: translateX(200%);
@@ -8112,7 +8117,7 @@ body:has(.modal.in) .float-right,
body:has(.modal.in) .float-right.position-center,
.modal-open .float-right.position-center,
.aksrt-lightbox-open .float-right.position-center,
.imgbox-show .float-right.position-center,
.scroll-down .scroll-down-hide.float-right.position-center,
.scroll-ing .scrolling-hide.float-right.position-center {
transform: translate(200%, -50%);
+1 -1
View File
File diff suppressed because one or more lines are too long
+254
View File
@@ -215,6 +215,8 @@
--swiper-navigation-color: #000000;
}
.swiper-thumbsbox .swiper-button-next,
.swiper-thumbsbox .swiper-button-prev,
.swiper-scroll .swiper-button-next,
.swiper-scroll .swiper-button-prev {
background-color: rgba(0, 0, 0, 0.5);
@@ -631,6 +633,248 @@ button.swiper-pagination-bullet {
}
/****其它*****/
.imgbox-show {
overflow: hidden;
}
.imgbox-show * {
-webkit-backdrop-filter: unset !important;
backdrop-filter: unset !important;
-webkit-filter: unset !important;
filter: unset !important;
}
.imgbox {
position: fixed;
top: 0;
bottom: 0;
left: 0;
right: 0;
width: 100%;
height: 100%;
}
.imgbox {
z-index: 100000;
transition: 0.4s;
--imgbox-origin-left: center;
--imgbox-origin-top: center;
}
.imgbox-bg {
z-index: 1;
opacity: 0.7;
}
.full-screen .imgbox-bg {
opacity: 1;
}
.imgbox-an {
position: fixed;
z-index: 3;
top: 13px;
right: 15px;
}
.hide-but,
.imgbox-an > a {
color: #fff;
background: rgba(41, 41, 41, 0.7);
}
.imgbox-an > a {
width: 34px;
height: 34px;
}
.hide-but {
padding: 4px 20px;
margin-right: 5px;
border-radius: 0 0 4px 4px;
cursor: pointer;
}
.is-play .fa-play:before {
content: '\f04c';
}
.swiper-imgbox {
width: 100%;
height: 100%;
transition: height 0.3s;
z-index: 10001;
}
.swiper-thumbsbox {
background: rgba(41, 41, 41, 0.6);
padding: 10px;
position: relative;
z-index: 2;
}
.swiper-thumbsbox .swiper-slide {
width: 100px;
height: 100px;
margin: 0 3px;
opacity: 0.8;
transition: border 0.3s;
cursor: pointer;
}
.show-thumb .swiper-imgbox {
height: calc(100% - 120px);
}
.swiper-thumbsbox .swiper-slide.swiper-slide-thumb-active {
opacity: 1;
border: 4px solid var(--focus-color);
}
.imgbox.show {
opacity: 1;
-webkit-animation: fade 0.4s;
animation: fade 0.4s;
visibility: visible;
}
.imgbox.hideing {
opacity: 0;
visibility: visible;
display: block !important;
}
.imgbox .swiper-slide {
transform-origin: var(--imgbox-origin-left) var(--imgbox-origin-top);
}
.imgbox.show .swiper-imgbox .swiper-slide {
-webkit-animation: scale_in 0.6s;
animation: scale_in 0.6s;
-webkit-animation-timing-function: cubic-bezier(0.1, 0.73, 0.41, 1.1);
animation-timing-function: cubic-bezier(0.1, 0.73, 0.41, 1.1);
transform: scale(1);
}
.imgbox.hideing .swiper-imgbox .swiper-slide {
-webkit-animation: scale_out 0.4s;
animation: scale_out 0.4s;
transform: scale(1);
}
.swiper-imgbox .lazyloading,
.swiper-imgbox .lazyload {
transform: scale(0.7);
}
.swiper-imgbox .lazyloaded:not(.lazyloadafter):not(.ls-is-cached) {
-webkit-animation: imgbox_lazy_in 0.4s;
animation: imgbox_lazy_in 0.4s;
}
@-webkit-keyframes imgbox_lazy_in {
0% {
transform: scale(0.7);
}
100% {
transform: scale(1);
}
}
@keyframes imgbox_lazy_in {
0% {
transform: scale(0.7);
}
100% {
transform: scale(1);
}
}
@-webkit-keyframes scale_in {
0% {
transform: scale(0.2);
}
100% {
transform: scale(1);
}
}
@keyframes scale_in {
0% {
transform: scale(0.2);
}
100% {
transform: scale(1);
}
}
@-webkit-keyframes scale_out {
0% {
transform: scale(1);
}
100% {
transform: scale(0.2);
}
}
@keyframes scale_out {
0% {
transform: scale(1);
}
100% {
transform: scale(0.2);
}
}
.counter-con {
transform: none;
top: 10px;
}
.counter {
padding: 4px 12px;
font-size: 16px;
margin: 10px;
background: rgba(41, 41, 41, 0.7);
}
.swiper-imgbox .swiper-slide img {
width: auto;
height: auto;
max-width: 90%;
max-height: 90%;
transition-duration: 0s;
position: relative;
}
.swiper-imgbox .counter-con {
transform: none;
top: 10px;
right: auto;
bottom: auto;
width: auto;
left: 10px;
}
.full-screen .swiper-slide img {
max-width: 100%;
max-height: 100%;
}
.swiper-close {
height: 100%;
transition: 0.3s cubic-bezier(0.18, 0.89, 0.32, 1.28);
}
.lazyloaded + .swiper-lazy-preloader {
display: none;
}
.swiper-pagination-bullets > .swiper-pagination-bullet {
width: 4px;
@@ -661,6 +905,16 @@ button.swiper-pagination-bullet {
}
@media (max-width: 767px) {
.imgbox.show .swiper-imgbox .swiper-slide {
-webkit-animation: scale_in 0.4s;
animation: scale_in 0.4s;
}
.swiper-imgbox .swiper-slide img {
max-width: calc(100% - 10px);
max-height: calc(100% - 10px);
}
.swiper-container-horizontal > .swiper-pagination-bullets,
.swiper-pagination-custom,
.swiper-pagination-fraction {
+1 -1
View File
File diff suppressed because one or more lines are too long
-555
View File
@@ -1,555 +0,0 @@
/**
* AKSRT Runtime Infrastructure
*
* Unified core primitives for the entire frontend:
* aksrt.tbquire(deps, cb) — lazy script/CSS loader
* aksrt.confirm(msg, opts) — i18n confirm dialog
* aksrt.scrollTopTo(target, off) — smart scroll with header offset
* aksrt.loading(el, show) — element-level loading overlay
* aksrt.route(url, title) — push/replace URL + title
*
* Declarative interactions (event delegation on body):
* [data-close] — close target element
* [data-onclick] — trigger click on another element
* [data-confirm] — confirm before action
* [data-action] — universal AJAX action button (like/follow/checkin)
* [ajax-action] — general AJAX button with modal response
*
* @package AKSRT
* @since 5.0.0
*/
(function () {
'use strict';
var aksrt = window.aksrt || {};
window.aksrt = aksrt;
// ══════════════════════════════════════════════════════════════
// §10.11 — tbquire: lazy script/CSS loader
// ══════════════════════════════════════════════════════════════
var _loadedScripts = {};
var _loadingPromises = {};
function loadSingleScript(src) {
if (_loadedScripts[src]) return Promise.resolve();
if (_loadingPromises[src]) return _loadingPromises[src];
_loadingPromises[src] = new Promise(function (resolve, reject) {
var isCSS = /\.css(\?|$)/i.test(src);
var el;
if (isCSS) {
el = document.createElement('link');
el.rel = 'stylesheet';
el.href = src;
} else {
el = document.createElement('script');
el.src = src;
el.async = true;
}
el.onload = function () {
_loadedScripts[src] = true;
delete _loadingPromises[src];
resolve();
};
el.onerror = function () {
delete _loadingPromises[src];
reject(new Error('Failed to load: ' + src));
};
(document.head || document.documentElement).appendChild(el);
});
return _loadingPromises[src];
}
aksrt.tbquire = function (deps, callback) {
if (typeof deps === 'string') deps = [deps];
if (!Array.isArray(deps) || !deps.length) {
if (typeof callback === 'function') callback();
return Promise.resolve();
}
var resolvedDeps = deps.map(function (dep) {
if (/^https?:\/\/|^\//.test(dep)) return dep;
var map = (window.aksrtData && aksrtData.tbquireMap) || {};
return map[dep] || dep;
});
var p = Promise.all(resolvedDeps.map(loadSingleScript));
if (typeof callback === 'function') {
p.then(callback).catch(function (err) {
console.error('[AKSRT tbquire]', err);
});
}
return p;
};
// ══════════════════════════════════════════════════════════════
// §10.10 — confirm: i18n confirm dialog + [data-confirm]
// ══════════════════════════════════════════════════════════════
var _i18n = (window.aksrtData && aksrtData.i18n) || {};
function __(key, fallback) {
return _i18n[key] || fallback || key;
}
aksrt.__ = __;
aksrt.confirm = function (msg, opts) {
opts = opts || {};
return new Promise(function (resolve) {
var overlay = document.createElement('div');
overlay.className = 'aksrt-confirm-overlay';
var dialog = document.createElement('div');
dialog.className = 'aksrt-confirm-dialog';
dialog.setAttribute('role', 'alertdialog');
dialog.setAttribute('aria-modal', 'true');
dialog.innerHTML =
'<div class="aksrt-confirm__body">' + escapeHtml(msg) + '</div>' +
'<div class="aksrt-confirm__actions">' +
'<button type="button" class="aksrt-confirm__cancel btn-ghost">' +
escapeHtml(opts.cancelText || __('cancel', '取消')) +
'</button>' +
'<button type="button" class="aksrt-confirm__ok btn-primary">' +
escapeHtml(opts.okText || __('confirm', '确定')) +
'</button>' +
'</div>';
overlay.appendChild(dialog);
document.body.appendChild(overlay);
requestAnimationFrame(function () { overlay.classList.add('is-open'); });
function close(result) {
overlay.classList.remove('is-open');
setTimeout(function () { overlay.remove(); }, 200);
resolve(result);
}
dialog.querySelector('.aksrt-confirm__cancel').addEventListener('click', function () { close(false); });
dialog.querySelector('.aksrt-confirm__ok').addEventListener('click', function () { close(true); });
overlay.addEventListener('click', function (e) { if (e.target === overlay) close(false); });
dialog.querySelector('.aksrt-confirm__ok').focus();
});
};
// ══════════════════════════════════════════════════════════════
// §10.10 — scrollTopTo: smart scroll with header offset
// ══════════════════════════════════════════════════════════════
aksrt.scrollTopTo = function (target, extraOffset) {
var top = 0;
if (typeof target === 'number') {
top = target;
} else if (target && target.getBoundingClientRect) {
top = target.getBoundingClientRect().top + window.pageYOffset;
}
var navFixed = document.querySelector('body.nav-fixed .header, .navbar.navbar-top');
var headerOffset = navFixed ? (navFixed.offsetHeight + 20) : 0;
top = Math.max(0, top - headerOffset - (extraOffset || 0));
var current = window.pageYOffset;
if (Math.abs(top - current) < 80) return;
window.scrollTo({ top: top, behavior: 'smooth' });
};
// ══════════════════════════════════════════════════════════════
// §10.10 — loading: element-level loading overlay
// ══════════════════════════════════════════════════════════════
aksrt.loading = function (el, show) {
if (!el) return;
if (show === false) {
var mask = el.querySelector('.aksrt-loading-mask');
if (mask) {
mask.classList.add('aksrt-loading-mask--out');
setTimeout(function () { mask.remove(); }, 300);
}
return;
}
if (el.querySelector('.aksrt-loading-mask')) return;
var pos = getComputedStyle(el).position;
if (pos === 'static') el.style.position = 'relative';
var mask = document.createElement('div');
mask.className = 'aksrt-loading-mask';
mask.innerHTML = '<svg class="aksrt-loading-mask__spinner" width="36" height="36" viewBox="0 0 36 36">' +
'<circle cx="18" cy="18" r="15" fill="none" stroke="currentColor" stroke-width="3" stroke-dasharray="80 40" stroke-linecap="round">' +
'<animateTransform attributeName="transform" type="rotate" from="0 18 18" to="360 18 18" dur="0.8s" repeatCount="indefinite"/>' +
'</circle></svg>';
el.appendChild(mask);
};
// ══════════════════════════════════════════════════════════════
// §10.11 — route: tab route + popstate
// ══════════════════════════════════════════════════════════════
aksrt.route = function (url, title) {
if (!window.history || !history.pushState) return;
history.pushState({ aksrt: true }, title || '', url);
if (title) document.title = title;
};
aksrt.routeReplace = function (url, title) {
if (!window.history || !history.replaceState) return;
history.replaceState({ aksrt: true }, title || '', url);
if (title) document.title = title;
};
// Tab route: elements with [data-route] push URL on activation
window.addEventListener('popstate', function (e) {
var routeTabs = document.querySelectorAll('[data-route]');
if (!routeTabs.length) return;
var path = window.location.pathname + window.location.search;
routeTabs.forEach(function (tab) {
var tabRoute = tab.getAttribute('data-route');
var isMatch = path === tabRoute || path.indexOf(tabRoute) === 0;
tab.classList.toggle('is-active', isMatch);
var target = tab.getAttribute('data-route-target');
if (target) {
var panel = document.querySelector(target);
if (panel) panel.classList.toggle('is-active', isMatch);
}
});
});
// ══════════════════════════════════════════════════════════════
// §10.11 — Declarative interactions (event delegation)
// ══════════════════════════════════════════════════════════════
document.addEventListener('click', function (e) {
var target = e.target.closest('[data-close]');
if (target) {
e.preventDefault();
var sel2 = target.getAttribute('data-close');
var el2 = sel2 ? document.querySelector(sel2) : target.parentElement;
if (el2) {
el2.classList.remove('is-open', 'is-active', 'is-visible');
el2.hidden = true;
}
return;
}
target = e.target.closest('[data-onclick]');
if (target) {
e.preventDefault();
var sel3 = target.getAttribute('data-onclick');
var el3 = document.querySelector(sel3);
if (el3) el3.click();
return;
}
});
// [data-confirm] — intercept submission
document.addEventListener('click', function (e) {
var target = e.target.closest('[data-confirm]');
if (!target) return;
var msg = target.getAttribute('data-confirm');
if (!msg) return;
e.preventDefault();
e.stopPropagation();
aksrt.confirm(msg).then(function (ok) {
if (!ok) return;
target.removeAttribute('data-confirm');
target.click();
target.setAttribute('data-confirm', msg);
});
}, true);
// Vendor modules are no longer dynamically loaded by the canonical frontend path.
// ══════════════════════════════════════════════════════════════
// §10.11 — [data-action] / [ajax-action] universal buttons
// ══════════════════════════════════════════════════════════════
// Only these data-action values are network AJAX. UI-only actions
// (toggle-theme, editor toolbar, download, etc.) must not hit admin-ajax.
var DATA_ACTION_AJAX = {
like: true,
favorite: true,
follow: true,
checkin: true
};
document.addEventListener('click', function (e) {
// [data-action] — like/follow/checkin with localStorage de-dup
var btn = e.target.closest('[data-action]');
if (btn) {
var dataAction = btn.getAttribute('data-action') || '';
if (!DATA_ACTION_AJAX[dataAction]) {
// Leave non-AJAX data-action handlers (theme toggle, toolbar, download) alone.
return;
}
e.preventDefault();
handleDataAction(btn);
return;
}
// [ajax-action] — general AJAX button
btn = e.target.closest('[ajax-action]');
if (btn) {
e.preventDefault();
handleAjaxAction(btn);
return;
}
});
function handleDataAction(btn) {
if (btn.classList.contains('is-loading')) return;
var action = btn.getAttribute('data-action');
if (!action || !DATA_ACTION_AJAX[action]) return;
var id = btn.getAttribute('data-id') || '';
var storageKey = 'aksrt_action_' + action + '_' + id;
if (action === 'like' || action === 'favorite') {
try {
if (localStorage.getItem(storageKey) && !btn.classList.contains('is-active')) {
notyf(__('already_done', '已操作'), 'warning');
return;
}
} catch (ex) { /* storage unavailable */ }
}
btn.classList.add('is-loading');
var ajaxUrl = (window.aksrtData && aksrtData.ajaxUrl) || '/wp-admin/admin-ajax.php';
if (!(window.aksrtData && aksrtData.nonce)) {
btn.classList.remove('is-loading');
notyf(__('action_failed', '操作失败'), 'danger');
return;
}
var params = new URLSearchParams();
params.set('action', 'aksrt_' + action);
params.set('nonce', aksrtData.nonce);
params.set('id', id);
var extraData = btn.getAttribute('data-action-data');
if (extraData) {
try {
var ed = JSON.parse(extraData);
Object.keys(ed).forEach(function (k) { params.set(k, ed[k]); });
} catch (ex) { /* ignore */ }
}
fetch(ajaxUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
credentials: 'same-origin',
body: params.toString()
})
.then(function (r) { return r.json(); })
.then(function (json) {
btn.classList.remove('is-loading');
if (json && json.success) {
var isActive = !!json.data && !!json.data.active;
btn.classList.toggle('is-active', isActive);
var countEl = btn.querySelector('[data-count]') || btn.querySelector('.action-count');
if (countEl && json.data && json.data.count !== undefined) {
countEl.textContent = String(json.data.count);
}
try {
if (isActive) localStorage.setItem(storageKey, '1');
else localStorage.removeItem(storageKey);
} catch (ex) { /* */ }
if (json.data && json.data.message) {
notyf(json.data.message, 'success');
}
if (json.data && json.data.goto) {
window.location.href = json.data.goto;
}
} else {
notyf((json.data && json.data.message) || __('action_failed', '操作失败'), 'danger');
}
})
.catch(function (err) {
btn.classList.remove('is-loading');
notyf(err.message || __('network_error', '网络错误'), 'danger');
});
}
function handleAjaxAction(btn) {
if (btn.classList.contains('is-loading')) return;
btn.classList.add('is-loading');
var action = btn.getAttribute('ajax-action');
var ajaxUrl = (window.aksrtData && aksrtData.ajaxUrl) || '/wp-admin/admin-ajax.php';
var params = new URLSearchParams();
params.set('action', action);
if (window.aksrtData && aksrtData.nonce) params.set('nonce', aksrtData.nonce);
var form = btn.closest('form');
if (form) {
new FormData(form).forEach(function (v, k) { params.set(k, v); });
}
fetch(ajaxUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
credentials: 'same-origin',
body: params.toString()
})
.then(function (r) { return r.json(); })
.then(function (json) {
btn.classList.remove('is-loading');
if (json && json.success) {
if (json.data && json.data.show_modal) {
window.AksrtModalRuntime.open({
html: json.data.show_modal,
bottom: true,
mobileBottom: true,
kind: 'generic',
});
} else if (json.data && json.data.message) {
notyf(json.data.message, 'success');
}
if (json.data && json.data.goto) {
window.location.href = json.data.goto;
}
if (json.data && json.data.reload) {
window.location.reload();
}
} else {
notyf((json.data && json.data.message) || __('action_failed', '操作失败'), 'danger');
}
})
.catch(function (err) {
btn.classList.remove('is-loading');
notyf(err.message || __('network_error', '网络错误'), 'danger');
});
}
// ══════════════════════════════════════════════════════════════
// §10.11 — Ripple (broad coverage)
// ══════════════════════════════════════════════════════════════
var RIPPLE_SELECTORS = '.toggle-radius,.but-ripple,.but,.btn,.btn-primary,.btn-ghost,.btn-outline,.item-thumbnail,.menu-item>a,.aksrt-ripple,.yiyan-box,.aksrt-card';
document.addEventListener('click', function (e) {
var target = e.target.closest(RIPPLE_SELECTORS);
if (!target) return;
// Markup opt-out (header publish uses class="nowave") + nav CTA chips
if (target.classList.contains('nowave') || target.closest('.nowave')) return;
if (target.classList.contains('navbar-cta') || target.closest('.navbar-cta')) return;
if (target.closest('.navbar-top .navbar-but, .navbar-top .navbar-vip, .navbar-but-cluster')) return;
if (target.querySelector('.aksrt-wave')) return;
var rect = target.getBoundingClientRect();
var size = Math.max(rect.width, rect.height) * 2;
var x = e.clientX - rect.left - size / 2;
var y = e.clientY - rect.top - size / 2;
var wave = document.createElement('span');
wave.className = 'aksrt-wave';
// Must be absolute — without it the huge span expands the button box ("变长").
wave.style.cssText = 'position:absolute;pointer-events:none;border-radius:50%;background:rgba(255,255,255,0.35);width:'
+ size + 'px;height:' + size + 'px;left:' + x + 'px;top:' + y + 'px;transform:scale(0);animation:aksrtWaveRipple .6s ease-out forwards;';
var cs = getComputedStyle(target);
if (cs.position === 'static') target.style.position = 'relative';
if (cs.overflow === 'visible') target.style.overflow = 'hidden';
target.appendChild(wave);
setTimeout(function () {
if (wave.parentNode) wave.parentNode.removeChild(wave);
}, 600);
});
// ══════════════════════════════════════════════════════════════
// §10.11 — auto_fun: extended rehydration coverage
// ══════════════════════════════════════════════════════════════
function initTooltips(root) {
root.querySelectorAll('[data-tooltip]').forEach(function (el) {
if (el.dataset.tooltipBound) return;
el.dataset.tooltipBound = '1';
el.addEventListener('mouseenter', function () {
var tip = document.createElement('div');
tip.className = 'aksrt-tooltip';
tip.textContent = el.getAttribute('data-tooltip');
document.body.appendChild(tip);
var rect = el.getBoundingClientRect();
tip.style.left = (rect.left + rect.width / 2 - tip.offsetWidth / 2) + 'px';
tip.style.top = (rect.top - tip.offsetHeight - 8 + window.pageYOffset) + 'px';
el._aksrtTooltip = tip;
});
el.addEventListener('mouseleave', function () {
if (el._aksrtTooltip) { el._aksrtTooltip.remove(); el._aksrtTooltip = null; }
});
});
}
function initCountdowns(root) {
root.querySelectorAll('[data-countdown]').forEach(function (el) {
if (el.dataset.countdownBound) return;
el.dataset.countdownBound = '1';
var end = parseInt(el.getAttribute('data-countdown'), 10);
if (!end) return;
var iv = setInterval(function () {
var left = Math.max(0, end - Math.floor(Date.now() / 1000));
if (left <= 0) { clearInterval(iv); el.textContent = '00:00'; return; }
var m = Math.floor(left / 60);
var s = left % 60;
el.textContent = (m < 10 ? '0' : '') + m + ':' + (s < 10 ? '0' : '') + s;
}, 1000);
});
}
AksrtFrontend.register('aksrt-tooltips', initTooltips);
AksrtFrontend.register('aksrt-countdowns', initCountdowns);
aksrt.autoFun = function (root, reason) {
root = root || document;
reason = reason || 'ajax';
if (!window.AksrtFrontend) return;
if (reason === 'init' && typeof AksrtFrontend.boot === 'function') {
AksrtFrontend.boot(root);
} else {
AksrtFrontend.rehydrate(root, reason);
}
};
// ══════════════════════════════════════════════════════════════
// Helpers
// ══════════════════════════════════════════════════════════════
function escapeHtml(str) {
if (!str) return '';
return String(str)
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;');
}
// ── DOMContentLoaded ──
function initRuntime() {
aksrt.autoFun(document, 'init');
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', initRuntime);
} else {
initRuntime();
}
})();
+16 -41
View File
@@ -8,8 +8,6 @@
var modal = null;
var lastModalTrigger = null;
var qrStates = [];
var globalEventsBound = false;
var oauthResultChecked = false;
var oauthErrorMessages = {
access_denied: '已取消第三方授权',
cancelled: '已取消第三方授权',
@@ -509,17 +507,6 @@
}
function initRoot(root) {
root = root || document;
if (root.nodeType === 1 && root.matches('[data-aksrt-auth]')) {
initAuthRoot(root);
return;
}
if (root.querySelectorAll) root.querySelectorAll('[data-aksrt-auth]').forEach(initAuthRoot);
}
function initAuthRoot(root) {
if (root.dataset.aksrtAuthInitialized === '1') return;
root.dataset.aksrtAuthInitialized = '1';
root.querySelectorAll('input').forEach(function (input) {
if (!input.hasAttribute('placeholder')) input.setAttribute('placeholder', ' ');
});
@@ -675,14 +662,12 @@
}
}
function initGlobal() {
modal = document.querySelector('[data-auth-modal]');
if (!oauthResultChecked) {
oauthResultChecked = true;
function init() {
if (document.documentElement.dataset.aksrtAuthInitialized === '1') return;
document.documentElement.dataset.aksrtAuthInitialized = '1';
showOAuthResultToast();
}
if (globalEventsBound) return;
globalEventsBound = true;
document.querySelectorAll('[data-aksrt-auth]').forEach(initRoot);
modal = document.querySelector('[data-auth-modal]');
document.addEventListener('click', function (event) {
var trigger = event.target.closest('[data-aksrt-auth-required], .aksrt-login-trigger, #nav-login-btn, .signin-loader, .signup-loader, .qrcode-signin');
if (!trigger) return;
@@ -690,7 +675,17 @@
var tab = trigger.classList.contains('signup-loader') ? 'signup' : (trigger.classList.contains('qrcode-signin') ? 'oauth' : 'signin');
openModal(tab, trigger.dataset.authRedirect || window.location.href, trigger);
});
if (modal) {
modal.addEventListener('click', function (event) {
if (event.target.closest('[data-auth-close]')) closeModal(true);
});
document.addEventListener('keydown', handleModalKeydown);
if (modal.dataset.auto === '1' && Number(window.localStorage.getItem('aksrtAuthAutoUntil') || 0) < Date.now()) {
window.setTimeout(function () {
openModal(modal.querySelector('[data-aksrt-auth]').dataset.initialTab || 'signin', window.location.href, null);
}, Math.max(1, Number(modal.dataset.autoWait) || 5) * 1000);
}
}
document.addEventListener('visibilitychange', function () {
qrStates.forEach(function (state) {
if (document.visibilityState !== 'visible') stopQr(state.root);
@@ -699,25 +694,5 @@
});
}
function initModal() {
if (!modal || modal.dataset.aksrtAuthModalInitialized === '1') return;
modal.dataset.aksrtAuthModalInitialized = '1';
modal.addEventListener('click', function (event) {
if (event.target.closest('[data-auth-close]')) closeModal(true);
});
if (modal.dataset.auto === '1' && Number(window.localStorage.getItem('aksrtAuthAutoUntil') || 0) < Date.now()) {
window.setTimeout(function () {
var root = modal.querySelector('[data-aksrt-auth]');
if (root) openModal(root.dataset.initialTab || 'signin', window.location.href, null);
}, Math.max(1, Number(modal.dataset.autoWait) || 5) * 1000);
}
}
if (window.AksrtFrontend && typeof window.AksrtFrontend.register === 'function') {
window.AksrtFrontend.register('aksrt-auth', function (root) {
initGlobal();
initRoot(root);
initModal();
});
}
jQuery(document).off('auto_fun.aksrt-auth').on('auto_fun.aksrt-auth', init);
}());
+29 -68
View File
@@ -8,35 +8,19 @@
* @package AKSRT
*/
/* global aksrtAuthorPage, aksrtData, AksrtFrontend, notyf */
/* global aksrtAuthorPage, aksrtData, notyf */
(function () {
'use strict';
var globalEventsBound = false;
function elementsIn(root, selector) {
var elements = [];
root = root || document;
if (root.nodeType === 1 && root.matches(selector)) elements.push(root);
if (root.querySelectorAll) root.querySelectorAll(selector).forEach(function (element) { elements.push(element); });
return elements;
}
function elementById(root, id) {
root = root || document;
if (root.nodeType === 1 && root.id === id) return root;
return root.querySelector ? root.querySelector('#' + id) : null;
}
function notifyLoadError() {
if (typeof notyf === 'function') {
notyf('加载失败,请重试', 'danger');
}
}
function initPublicDashboards(scope) {
elementsIn(scope, '.dashboard--public').forEach(function (root) {
function initPublicDashboards() {
document.querySelectorAll('.dashboard--public').forEach(function (root) {
if (root.dataset.aksrtAuthorBound === '1') return;
root.dataset.aksrtAuthorBound = '1';
@@ -101,9 +85,8 @@
throw new Error('panel-load-failed');
}
panel.innerHTML = payload.data.html;
if (window.AksrtFrontend && typeof window.AksrtFrontend.rehydrate === 'function') {
window.AksrtFrontend.rehydrate(panel, 'ajax');
}
if (window.jQuery) jQuery(document).trigger('post_ajax.ed', [panel]);
if (typeof window.auto_fun === 'function') window.auto_fun();
});
}).finally(function () {
panel._aksrtUhRequest = null;
@@ -154,13 +137,13 @@
});
}
function initCoverUpload(root) {
function initCoverUpload() {
var cfg = window.aksrtAuthorPage || {};
var upload = cfg.coverUpload || null;
if (!upload || !upload.enabled || !upload.restUrl) return;
var btn = elementById(root, upload.buttonId || 'aksrt-upload-bg-btn');
var input = elementById(root, upload.inputId || 'aksrt-bg-file-input');
var btn = document.getElementById(upload.buttonId || 'aksrt-upload-bg-btn');
var input = document.getElementById(upload.inputId || 'aksrt-bg-file-input');
if (!btn || !input || btn.dataset.aksrtCoverBound === '1') return;
btn.dataset.aksrtCoverBound = '1';
@@ -254,13 +237,13 @@
});
}
function initAvatarUpload(root) {
function initAvatarUpload() {
var upload = (window.aksrtUserCenter || {}).avatarUpload;
if (!upload || !upload.enabled || !upload.restUrl) return;
var button = elementById(root, upload.buttonId || 'aksrt-upload-avatar-btn');
var input = elementById(root, upload.inputId || 'aksrt-avatar-file-input');
var image = elementById(root, upload.imageId || 'aksrt-user-avatar-image');
var button = document.getElementById(upload.buttonId || 'aksrt-upload-avatar-btn');
var input = document.getElementById(upload.inputId || 'aksrt-avatar-file-input');
var image = document.getElementById(upload.imageId || 'aksrt-user-avatar-image');
if (!button || !input || button.dataset.aksrtAvatarBound === '1') return;
button.dataset.aksrtAvatarBound = '1';
@@ -313,8 +296,8 @@
});
}
function initCoverMenus(root) {
elementsIn(root, '[data-aksrt-menu]').forEach(function (menu) {
function initCoverMenus() {
document.querySelectorAll('[data-aksrt-menu]').forEach(function (menu) {
if (menu.dataset.aksrtMenuBound === '1') return;
menu.dataset.aksrtMenuBound = '1';
var trigger = menu.querySelector('.aksrt-cover-menu__trigger');
@@ -336,54 +319,32 @@
}
trigger.addEventListener('click', function () { panel.hidden ? open() : close(); });
menu.addEventListener('keydown', function (event) { if (event.key === 'Escape') { close(); trigger.focus(); } });
document.addEventListener('pointerdown', function (event) { if (!menu.contains(event.target)) close(); });
});
}
function initProfileDetailsModal(root) {
var modal = elementById(root, 'aksrt-profile-details-modal');
if (!modal || modal.dataset.aksrtProfileModalBound === '1') return;
modal.dataset.aksrtProfileModalBound = '1';
function initProfileDetailsModal() {
var modal = document.getElementById('aksrt-profile-details-modal');
if (!modal) return;
var dialog = modal.querySelector('.aksrt-profile-details-modal__dialog');
var returnFocus = null;
function close() { modal.hidden = true; if (returnFocus) returnFocus.focus(); }
elementsIn(root, '[data-aksrt-profile-details]').forEach(function (button) {
document.querySelectorAll('[data-aksrt-profile-details]').forEach(function (button) {
button.addEventListener('click', function () { returnFocus = button; modal.hidden = false; if (dialog) dialog.focus(); });
});
modal.querySelectorAll('[data-aksrt-modal-close]').forEach(function (button) { button.addEventListener('click', close); });
document.addEventListener('keydown', function (event) { if (event.key === 'Escape' && !modal.hidden) close(); });
}
function initGlobalEvents() {
if (globalEventsBound) return;
globalEventsBound = true;
document.addEventListener('pointerdown', function (event) {
document.querySelectorAll('[data-aksrt-menu]').forEach(function (menu) {
if (menu.contains(event.target)) return;
var panel = menu.querySelector('.aksrt-cover-menu__panel');
var trigger = menu.querySelector('.aksrt-cover-menu__trigger');
if (panel) panel.hidden = true;
if (trigger) trigger.setAttribute('aria-expanded', 'false');
});
});
document.addEventListener('keydown', function (event) {
if (event.key !== 'Escape') return;
var modal = document.getElementById('aksrt-profile-details-modal');
if (modal && !modal.hidden) {
var close = modal.querySelector('[data-aksrt-modal-close]');
if (close) close.click();
}
});
function init() {
if (document.documentElement.dataset.aksrtAuthorInitialized === '1') return;
document.documentElement.dataset.aksrtAuthorInitialized = '1';
initPublicDashboards();
initCoverMenus();
initProfileDetailsModal();
initCoverUpload();
initAvatarUpload();
}
function init(root) {
initGlobalEvents();
initPublicDashboards(root);
initCoverMenus(root);
initProfileDetailsModal(root);
initCoverUpload(root);
initAvatarUpload(root);
}
if (window.AksrtFrontend && typeof window.AksrtFrontend.register === 'function') {
window.AksrtFrontend.register('aksrt-author', init);
}
jQuery(document).off('auto_fun.aksrt-author').on('auto_fun.aksrt-author', function () { init(document); });
})();
+4 -7
View File
@@ -9,12 +9,9 @@
if (window._win && window._win.ajax_url) return window._win.ajax_url;
return '/wp-admin/admin-ajax.php';
}
function init(root) {
root = root || document;
var form = root.nodeType === 1 && root.matches('.aksrt-ban-appeal-form')
? root : root.querySelector('.aksrt-ban-appeal-form');
if (!form || form.dataset.aksrtBanAppealBound === '1') return;
form.dataset.aksrtBanAppealBound = '1';
function init() {
var form = document.querySelector('.aksrt-ban-appeal-form');
if (!form) return;
form.addEventListener('submit', function (e) {
e.preventDefault();
var btn = form.querySelector('button[type="submit"]');
@@ -35,5 +32,5 @@
.finally(function () { if (btn) btn.disabled = false; });
});
}
window.AksrtFrontend.register('aksrt-ban-appeal-page', init);
jQuery(document).off('auto_fun.aksrt-ban-appeal-page').on('auto_fun.aksrt-ban-appeal-page', init);
})();
File diff suppressed because one or more lines are too long
+14 -6
View File
@@ -121,11 +121,8 @@
TOKEN_FIELDS: TOKEN_FIELDS
});
function scan(root, reason) {
var scope = root && root.querySelectorAll ? root : document;
var mounts = [];
if (scope.nodeType === 1 && scope.matches('[data-aksrt-captcha-config]')) mounts.push(scope);
Array.prototype.push.apply(mounts, scope.querySelectorAll('[data-aksrt-captcha-config]'));
function scan() {
var mounts = document.querySelectorAll('[data-aksrt-captcha-config]');
Array.prototype.forEach.call(mounts, function (mount) {
if (mount.dataset.aksrtCaptchaBound) return;
var config;
@@ -548,5 +545,16 @@
}
}
window.AksrtFrontend.register('aksrt-captcha-front', scan);
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', scan);
else setTimeout(scan, 0);
// AJAX 注入新内容后由 auto_fun 重扫(dataset.aksrtCaptchaBound 标记保证幂等)。
if (window.jQuery) window.jQuery(document).on('auto_fun', scan);
if (window.MutationObserver) {
new MutationObserver(function (mutations) {
var shouldScan = mutations.some(function (mutation) { return mutation.addedNodes && mutation.addedNodes.length; });
if (shouldScan) scan();
}).observe(document.documentElement, { childList: true, subtree: true });
}
})();
+12 -7
View File
@@ -99,8 +99,7 @@
}
function processImage(img) {
if (img.dataset.aksrtColorDone || img.dataset.aksrtColorBound) return;
img.dataset.aksrtColorBound = '1';
if (img.dataset.aksrtColorDone) return;
// Need crossOrigin for canvas access
if (!img.crossOrigin && img.src.indexOf(window.location.origin) !== 0) {
@@ -128,10 +127,8 @@
}
}
function init(root, reason) {
var scope = root && root.querySelectorAll ? root : document;
if (scope.nodeType === 1 && scope.matches('[data-aksrt-color-extract]')) processImage(scope);
scope.querySelectorAll('[data-aksrt-color-extract]').forEach(processImage);
function init() {
document.querySelectorAll('[data-aksrt-color-extract]').forEach(processImage);
}
// Public API
@@ -142,5 +139,13 @@
init: init
};
window.AksrtFrontend.register('aksrt-color-extract', init);
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', init);
} else {
init();
}
// AJAX 注入新内容后由 auto_fun 重扫(dataset.aksrtColorDone 标记保证幂等)。
if (window.jQuery) {
window.jQuery(document).on('auto_fun', init);
}
})();
+2
View File
@@ -333,6 +333,8 @@
url: href,
payload: payload,
});
// legacy 契约:post_ajax.ed 之后调用全局 auto_fun 重扫新内容。
if (typeof window.auto_fun === "function") window.auto_fun();
document.dispatchEvent(
new CustomEvent("aksrt:posts:rendered", {
bubbles: true,
+17 -4
View File
@@ -7,7 +7,8 @@
function initArchiveFilter(root) {
var scope = root || document;
var bar = scope.querySelector(".archive-filter-bar--ajax[data-ajax-archive]");
if (!bar) return;
if (!bar || bar.dataset.aksrtArchiveInit === "1") return;
bar.dataset.aksrtArchiveInit = "1";
var archiveType = bar.dataset.ajaxArchive || "category";
var termId = parseInt(bar.dataset.termId, 10) || 0;
@@ -98,7 +99,9 @@
} else {
rebuildEmptyState();
}
if (window.AksrtFrontend) AksrtFrontend.rehydrate(wrap, "ajax");
// legacy 事件顺序:先 post_ajax.ed,再全局 auto_fun 重扫
wrap.dispatchEvent(new CustomEvent("post_ajax.ed", { bubbles: true }));
if (typeof window.auto_fun === "function") window.auto_fun();
}
if (pushState !== false) {
var url = new URL(window.location.href);
@@ -177,7 +180,17 @@
});
}
window.AksrtFrontend.register("aksrt-archive-filter", function (root) {
function init(root) {
initArchiveFilter(root);
});
}
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", function () { init(); });
} else {
init();
}
// AJAX 注入新内容后由 auto_fun 重扫(bar 级 data 标记保证幂等)。
if (window.jQuery) {
window.jQuery(document).on("auto_fun", function () { init(); });
}
})();
+21 -6
View File
@@ -23,7 +23,8 @@
var btn = document.getElementById("search-clear-btn");
var input = document.getElementById("search-page-input");
if (btn && input) {
if (btn && input && !btn.dataset.aksrtSearchClearBound) {
btn.dataset.aksrtSearchClearBound = "1";
var syncClearButton = function () {
var hasValue = input.value.trim().length > 0;
btn.classList.toggle("is-visible", hasValue);
@@ -63,6 +64,8 @@
if (!buttons.length) return;
buttons.forEach(function (button) {
if (button.dataset.aksrtArticleToolBound) return;
button.dataset.aksrtArticleToolBound = "1";
button.addEventListener("click", function () {
var tool = button.getAttribute("data-article-tool");
if (tool === "print") {
@@ -327,9 +330,21 @@
}
}
window.AksrtFrontend.register("aksrt-search-clear", function () { initSearchClear(); });
window.AksrtFrontend.register("aksrt-article-tools", function () { initArticleTools(); });
window.AksrtFrontend.register("aksrt-post-meta-menus", function (root) { initPostMetaMenus(root); });
window.AksrtFrontend.register("aksrt-password-toggles", function (root) { initPasswordToggles(root); });
window.AksrtFrontend.register("aksrt-interaction-bar", function (root) { initInteractionBar(root); });
function init(root) {
initSearchClear();
initArticleTools();
initPostMetaMenus(root);
initPasswordToggles(root);
initInteractionBar(root);
}
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", function () { init(); });
} else {
init();
}
// AJAX 注入新内容后由 auto_fun 重扫(各 init 均带 data 标记,重复调用幂等)。
if (window.jQuery) {
window.jQuery(document).off("auto_fun.aksrt-article").on("auto_fun.aksrt-article", function () { init(); });
}
})();
+25 -40
View File
@@ -4,10 +4,6 @@
(function () {
'use strict';
function $(sel, root) {
return (root || document).querySelector(sel);
}
function FixedInput(el, action) {
if (!el) return;
if (!el.dataset.fixedBound) {
@@ -39,6 +35,19 @@
}
}
document.addEventListener('click', function (e) {
var trigger = e.target && e.target.closest ? e.target.closest('[fixed-input]') : null;
if (!trigger) return;
e.preventDefault();
var targetSel = trigger.getAttribute('fixed-input') || '#respond';
var panel = document.querySelector(targetSel);
var comments = document.getElementById('comments');
if (comments && comments.scrollIntoView) {
comments.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
FixedInput(panel, 'show');
});
// Autoheight textareas.
function bindAutoheight(ta) {
if (!ta || ta.dataset.autoheightBound) return;
@@ -54,49 +63,25 @@
resize();
}
function scopeFor(root) {
return root && root.querySelectorAll ? root : document;
function scan() {
document.querySelectorAll('textarea[autoheight], textarea.grin').forEach(bindAutoheight);
}
function scan(root) {
var scope = scopeFor(root);
if (scope.nodeType === 1 && scope.matches('textarea[autoheight], textarea.grin')) {
bindAutoheight(scope);
}
scope.querySelectorAll('textarea[autoheight], textarea.grin').forEach(bindAutoheight);
}
var globalsBound = false;
function bindGlobals() {
if (globalsBound) return;
globalsBound = true;
document.addEventListener('click', function (e) {
var trigger = e.target && e.target.closest ? e.target.closest('[fixed-input]') : null;
if (!trigger) return;
e.preventDefault();
var targetSel = trigger.getAttribute('fixed-input') || '#respond';
var panel = document.querySelector(targetSel);
var comments = document.getElementById('comments');
if (comments && comments.scrollIntoView) {
comments.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
FixedInput(panel, 'show');
});
}
window.AksrtFrontend.register('aksrt-comment-fixed-input', function (root, reason) {
bindGlobals();
scan(root);
root = root || document;
var respond = root.nodeType === 1 && root.matches && root.matches('#respond')
? root
: (root.querySelector ? root.querySelector('#respond') : document.getElementById('respond'));
function init() {
scan();
// Expose for submit hide.
var respond = document.getElementById('respond');
if (respond) {
respond.aksrtFixedInput = function (action) {
FixedInput(respond, action);
};
}
});
}
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', init);
else init();
// AJAX 注入新内容后由 auto_fun 重扫(dataset 标记保证幂等)。
if (window.jQuery) window.jQuery(document).on('auto_fun', init);
window.AksrtFixedInput = FixedInput;
})();
+28 -10
View File
@@ -6,7 +6,8 @@
function initCommentSystem() {
var form = document.querySelector("#commentform");
if (!form) return;
if (!form || form.dataset.aksrtCommentInit === "1") return;
form.dataset.aksrtCommentInit = "1";
// 修复:同时匹配 button 和 input 元素
var submitBtn = form.querySelector('[type="submit"]');
@@ -338,7 +339,9 @@
notyf('评论发布成功', 'success');
}
if (window.AksrtFrontend) AksrtFrontend.rehydrate(newComment, 'ajax');
// legacy 事件顺序:先 post_ajax.ed,再全局 auto_fun 重扫
newComment.dispatchEvent(new CustomEvent('post_ajax.ed', { bubbles: true }));
if (typeof window.auto_fun === 'function') window.auto_fun();
updateCommentCount(1);
}
@@ -523,7 +526,9 @@
var currentCount = commentsArea.querySelector(".title-theme small");
if (currentCount && data.count_text) currentCount.textContent = data.count_text;
if (window.AksrtFrontend) AksrtFrontend.rehydrate(commentsArea, "ajax");
// legacy 事件顺序:先 post_ajax.ed,再全局 auto_fun 重扫
newListWrap.dispatchEvent(new CustomEvent("post_ajax.ed", { bubbles: true }));
if (typeof window.auto_fun === "function") window.auto_fun();
}
function fetchCommentFragment(opts) {
@@ -575,7 +580,7 @@
/* ====== 评论排序(最新 / 最早) ====== */
/**
* Locate #id within a rehydrate root.
* Locate #id within the given scope.
* Document has getElementById; Element roots (AJAX panels) only have querySelector.
*/
function findInScope(scope, id) {
@@ -596,9 +601,8 @@
function initCommentOrder(root) {
var scope = root || document;
var commentsArea = findInScope(scope, "comments");
if (!commentsArea) return;
// Event delegation survives filter HTML replacement after AJAX rehydrate.
if (commentsArea.dataset.orderInit === "1") return;
if (!commentsArea || commentsArea.dataset.orderInit === "1") return;
// Event delegation survives filter HTML replacement after AJAX refresh.
commentsArea.dataset.orderInit = "1";
function renderLoadingState() {
@@ -683,6 +687,8 @@
/* ====== 数字分页跳页(legacy pag-jump) ====== */
var commentPageJumpBound = false;
function jumpToCommentPage(page) {
loadCommentPage(page).catch(function (error) {
console.error("[AKSRT Comment] 跳页失败:", error);
@@ -691,6 +697,8 @@
}
function initCommentPageJump() {
if (commentPageJumpBound) return;
commentPageJumpBound = true;
document.addEventListener("click", function (e) {
var jump = e.target.closest ? e.target.closest("#comments .pag-jump") : null;
if (!jump) return;
@@ -708,12 +716,22 @@
});
}
window.AksrtFrontend.register("aksrt-comment-system", function () {
function init() {
stripCommentUrlParams();
initCommentSystem();
initCommentPageJump();
});
window.AksrtFrontend.register("aksrt-comment-order", function (root) { initCommentOrder(root); });
initCommentOrder();
}
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", init);
} else {
init();
}
// AJAX 注入新内容后由 auto_fun 重扫(form/commentsArea 均带 data 标记,重复调用幂等)。
if (window.jQuery) {
window.jQuery(document).on("auto_fun", init);
}
// 供 pagination.js 等模块复用:评论页码加载 / 列表刷新(局部 DOM,无 ? 参数)。
window.AksrtComments = {
+8 -3
View File
@@ -6,14 +6,15 @@
function initFooterTabbar() {
var tabbar = document.getElementById("footer-tabbar");
if (!tabbar) return;
if (!tabbar || tabbar.dataset.aksrtTabbarInit === "1") return;
tabbar.dataset.aksrtTabbarInit = "1";
var addBackdrop = document.getElementById("tabbar-add-backdrop");
var ticking = false;
var scrollThreshold = 100;
var isHidden = false;
// Use body scroll bus classes from aksrt-runtime.js
// Use body scroll bus classes from runtime/main.js
function handleScrollDownHide() {
var body = document.body;
var scrollTop = window.pageYOffset || document.documentElement.scrollTop;
@@ -136,5 +137,9 @@
});
}
window.AksrtFrontend.register("aksrt-footer-tabbar", function () { initFooterTabbar(); });
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", initFooterTabbar);
} else {
initFooterTabbar();
}
})();
+64 -43
View File
@@ -4,18 +4,6 @@
(function () {
"use strict";
var globalsBound = false;
function scopeFor(root) {
return root && root.querySelectorAll ? root : document;
}
function eachMatch(root, selector, callback) {
var scope = scopeFor(root);
if (scope.nodeType === 1 && scope.matches(selector)) callback(scope);
scope.querySelectorAll(selector).forEach(callback);
}
function renderGradientBackground(container) {
if (!container || container.dataset.aksrtGradientState || typeof window.Grade !== "function") return;
@@ -44,15 +32,26 @@
}
function initGradientBackgrounds(root) {
eachMatch(root, ".gradient-bg", renderGradientBackground);
var scope = root || document;
if (scope.nodeType === 1 && scope.matches(".gradient-bg")) {
renderGradientBackground(scope);
}
scope.querySelectorAll(".gradient-bg").forEach(renderGradientBackground);
}
document.addEventListener("lazyloaded", function (event) {
if (!(event.target instanceof Element) || !event.target.matches(".gradient-bg img")) return;
renderGradientBackground(event.target.closest(".gradient-bg"));
}, true);
function initPostThumbMedia(root) {
eachMatch(root, "[data-post-thumb-video]", function (box) {
var scope = root || document;
scope.querySelectorAll("[data-post-thumb-video]").forEach(function (box) {
if (box.dataset.aksrtThumbVideoBound === "1") return;
box.dataset.aksrtThumbVideoBound = "1";
var video = box.querySelector("video");
if (!video) return;
box.dataset.aksrtThumbVideoBound = "1";
function loadVideo() {
if (!video.getAttribute("src") && video.dataset.src) {
@@ -83,17 +82,35 @@
});
}
function initSlideCovers(root) {
eachMatch(root, ".single-cover--slide", function (cover) {
if (cover.dataset.aksrtSlideCoverBound === "1") return;
function init(root) {
initPostThumbMedia(root);
initGradientBackgrounds(root);
}
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", function () { init(); });
} else {
init();
}
// AJAX 注入新内容后由 auto_fun 重扫(各 init 均带 data 标记,重复调用幂等)。
if (window.jQuery) {
window.jQuery(document).on("auto_fun", function () { init(); });
}
})();
(function () {
"use strict";
function initSlideCovers() {
var covers = document.querySelectorAll(".single-cover--slide");
covers.forEach(function (cover) {
var slides = cover.querySelectorAll(".single-cover__slide");
var dots = cover.querySelectorAll(".single-cover__dot");
if (slides.length < 2) return;
cover.dataset.aksrtSlideCoverBound = "1";
var current = 0;
var interval = 5000;
var timer = null;
function goTo(idx) {
slides[current].classList.remove("is-active");
@@ -103,32 +120,33 @@
if (dots[current]) dots[current].classList.add("is-active");
}
function startTimer() {
timer = window.setInterval(function () {
var timer = setInterval(function () {
goTo((current + 1) % slides.length);
}, interval);
}
startTimer();
dots.forEach(function (dot, i) {
dot.addEventListener("click", function () {
window.clearInterval(timer);
clearInterval(timer);
goTo(i);
startTimer();
timer = setInterval(function () {
goTo((current + 1) % slides.length);
}, interval);
});
});
});
}
function bindGlobals() {
if (globalsBound) return;
globalsBound = true;
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", initSlideCovers);
} else {
initSlideCovers();
}
})();
document.addEventListener("lazyloaded", function (event) {
if (!(event.target instanceof Element) || !event.target.matches(".gradient-bg img")) return;
renderGradientBackground(event.target.closest(".gradient-bg"));
}, true);
(function () {
"use strict";
function initHiddenContent() {
document.addEventListener("click", function (e) {
var btn = e.target.closest(".aksrt-hidden-content__submit-btn");
if (!btn) return;
@@ -149,7 +167,7 @@
var formData = new FormData();
formData.append("action", "aksrt_check_visibility");
formData.append("_nonce", (window.aksrtData && window.aksrtData.visibilityNonce) || "");
formData.append("_nonce", (window.aksrtData && aksrtData.visibilityNonce) || "");
formData.append("mode", mode);
formData.append("pid", pid);
if (password) formData.append("password", password);
@@ -157,7 +175,7 @@
btn.disabled = true;
btn.textContent = "...";
fetch((window.aksrtData && window.aksrtData.ajaxUrl) || "/wp-admin/admin-ajax.php", {
fetch((window.aksrtData && aksrtData.ajaxUrl) || "/wp-admin/admin-ajax.php", {
method: "POST",
body: formData,
credentials: "same-origin",
@@ -180,19 +198,22 @@
});
});
// Handle Enter key on password input
document.addEventListener("keydown", function (e) {
if (e.key !== "Enter" || !e.target.classList.contains("aksrt-hidden-content__password-input")) return;
if (e.key === "Enter" && e.target.classList.contains("aksrt-hidden-content__password-input")) {
e.preventDefault();
var wrapper = e.target.closest(".aksrt-hidden-content--locked");
var btn = wrapper ? wrapper.querySelector(".aksrt-hidden-content__submit-btn") : null;
if (wrapper) {
var btn = wrapper.querySelector(".aksrt-hidden-content__submit-btn");
if (btn) btn.click();
}
}
});
}
window.AksrtFrontend.register("aksrt-misc", function (root, reason) {
bindGlobals();
initPostThumbMedia(root);
initGradientBackgrounds(root);
initSlideCovers(root);
});
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", initHiddenContent);
} else {
initHiddenContent();
}
})();
+21 -8
View File
@@ -3,7 +3,7 @@
*
* Owns the modal shell while adding cancellable loaders,
* short in-memory caching, request deduplication, retryable errors, focus
* restoration, and modal-scoped rehydration.
* restoration, and legacy `loaded.bs.modal` content lifecycle (auto_fun rescan).
*
* @package AKSRT
*/
@@ -184,7 +184,7 @@
}));
if (options.html !== undefined) {
rehydrate(session);
notifyContentLoaded(session);
telemetryMark(session, "first-content");
telemetryMark(session, "ready");
if (typeof options.onContent === "function") options.onContent(options.html, session);
@@ -193,9 +193,11 @@
return session;
}
function rehydrate(session) {
if (!session || !session.content) return;
window.AksrtFrontend.rehydrate(session.content, "modal");
// legacy 契约:modal 内容注入后触发 loaded.bs.modal,
// 由全局委托(见文件底部)驱动 auto_fun 重扫,不做模块内扫描。
function notifyContentLoaded(session) {
if (!session || !session.shell || !window.jQuery) return;
window.jQuery(session.shell).trigger("loaded.bs.modal");
}
function abortSessionRequest(session) {
@@ -260,7 +262,7 @@
'</div><div class="but-average modal-buts">' +
'<button type="button" class="but" data-aksrt-modal-retry>重试</button>' +
'<button type="button" class="but" data-aksrt-modal-close>关闭</button></div>';
rehydrate(session);
notifyContentLoaded(session);
if (typeof session.options.onError === "function") session.options.onError(error, session);
}
@@ -281,7 +283,7 @@
}
setState(session, "ready");
telemetryMark(session, "first-content");
rehydrate(session);
notifyContentLoaded(session);
telemetryMark(session, "ready");
if (typeof session.options.onData === "function") session.options.onData(data, session, result);
return;
@@ -298,7 +300,7 @@
session.content.innerHTML = html;
setState(session, "ready");
telemetryMark(session, "first-content");
rehydrate(session);
notifyContentLoaded(session);
telemetryMark(session, "ready");
if (typeof session.options.onContent === "function") session.options.onContent(html, session);
}
@@ -422,4 +424,15 @@
};
document.dispatchEvent(new CustomEvent("aksrt:modal-runtime:ready"));
// legacy 契约(只绑定一次):modal 展示/内容注入后调用全局 auto_fun 重扫。
if (window.jQuery) {
window.jQuery(document).on(
"loaded.bs.modal show.bs.modal",
".modal, .aksrt-modal-runtime",
function () {
if (typeof window.auto_fun === "function") window.auto_fun();
}
);
}
})(window, document);
+16 -4
View File
@@ -173,9 +173,9 @@
target.appendChild(newItems[0]);
}
}
if (window.AksrtFrontend) {
AksrtFrontend.rehydrate(target, "ajax");
}
// legacy 事件顺序:先 post_ajax.ed,再全局 auto_fun 重扫
target.dispatchEvent(new CustomEvent("post_ajax.ed", { bubbles: true }));
if (typeof window.auto_fun === "function") window.auto_fun();
nextPage++;
container.dataset.nextPage = String(nextPage);
if (fromAuto) {
@@ -284,5 +284,17 @@
});
}
window.AksrtFrontend.register("aksrt-ajax-pagination", function (root) { initAjaxPagination(root); });
function init(root) {
initAjaxPagination(root);
}
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", function () { init(); });
} else {
init();
}
// AJAX 注入新内容后由 auto_fun 重扫(container 级 data 标记保证幂等)。
if (window.jQuery) {
window.jQuery(document).on("auto_fun", function () { init(); });
}
})();
+10 -1
View File
@@ -182,7 +182,12 @@
if (ddBtn) ddBtn.setAttribute("aria-pressed", isDark ? "true" : "false");
}
var themeInitialized = false;
function initTheme() {
if (themeInitialized) return;
themeInitialized = true;
var stored = getStoredTheme();
var configuredMode = (window.aksrtData && aksrtData.themeMode) || "light";
if (stored === "dark" || stored === "light") {
@@ -265,5 +270,9 @@
};
}
window.AksrtFrontend.register("aksrt-theme", function () { initTheme(); });
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", initTheme);
} else {
initTheme();
}
})();
+44 -70
View File
@@ -15,21 +15,6 @@
return;
}
var activePoll = null;
var balancesRefreshed = false;
function elementsIn(root, selector) {
var elements = [];
root = root || document;
if (root.nodeType === 1 && root.matches(selector)) elements.push(root);
if (root.querySelectorAll) root.querySelectorAll(selector).forEach(function (element) { elements.push(element); });
return elements;
}
function firstIn(root, selector) {
root = root || document;
if (root.nodeType === 1 && root.matches(selector)) return root;
return root.querySelector ? root.querySelector(selector) : null;
}
function operationKey(owner) {
if (!owner.dataset.aksrtOperationKey) {
@@ -104,12 +89,8 @@
}
// Task-list "去签到" → scroll + click the real asset-card sign-in button.
function initSigninGoto(root) {
root = root || document;
var items = [];
if (root.nodeType === 1 && root.matches('[data-aksrt-signin-goto]')) items.push(root);
if (root.querySelectorAll) root.querySelectorAll('[data-aksrt-signin-goto]').forEach(function (el) { items.push(el); });
items.forEach(function (el) {
function initSigninGoto() {
document.querySelectorAll('[data-aksrt-signin-goto]').forEach(function (el) {
if (el.dataset.aksrtSigninGotoInitialized === '1') return;
el.dataset.aksrtSigninGotoInitialized = '1';
el.addEventListener('click', function (e) {
@@ -132,8 +113,8 @@
}
// ===== Forward-only affiliate revenue center =====
function initAffiliateRevenue(scope) {
var root = firstIn(scope, '[data-aksrt-revenue-page]');
function initAffiliateRevenue() {
var root = document.querySelector('[data-aksrt-revenue-page]');
if (!root || root.dataset.affiliateBound) return;
root.dataset.affiliateBound = '1';
var input = root.querySelector('[data-affiliate-link]');
@@ -168,10 +149,9 @@
// ===== VIP 积分兑换 =====
function initVipPointsExchange(scope) {
var root = firstIn(scope, '[data-aksrt-vip-points]');
if (!root || root.dataset.aksrtVipPointsBound === '1') return;
root.dataset.aksrtVipPointsBound = '1';
function initVipPointsExchange() {
var root = document.querySelector('[data-aksrt-vip-points]');
if (!root) return;
var tip = root.querySelector('[data-aksrt-vip-points-tip]');
var busy = false;
var coordinator = window.AksrtVipPurchaseCoordinator;
@@ -211,10 +191,9 @@
}
// ===== VIP 开通 =====
function initVipShop(scope) {
var root = firstIn(scope, '[data-aksrt-vip-shop]');
if (!root || root.dataset.aksrtVipShopBound === '1') return;
root.dataset.aksrtVipShopBound = '1';
function initVipShop() {
var root = document.querySelector('[data-aksrt-vip-shop]');
if (!root) return;
var tip = root.querySelector('[data-aksrt-vip-tip]');
var busy = false;
var coordinator = window.AksrtVipPurchaseCoordinator;
@@ -286,13 +265,11 @@
}
// ===== 卡密兑换(余额 / 会员) =====
function initCardPass(scope) {
var roots = elementsIn(scope, '[data-aksrt-card-pass]');
function initCardPass() {
var roots = document.querySelectorAll('[data-aksrt-card-pass]');
if (!roots || !roots.length) return;
Array.prototype.forEach.call(roots, function (root) {
if (root.dataset.aksrtCardPassBound === '1') return;
root.dataset.aksrtCardPassBound = '1';
var tip = root.querySelector('[data-aksrt-card-tip]');
var busy = false;
resetOperationKeyOnChange(root);
@@ -403,8 +380,8 @@
return handle;
}
function initBalanceCharge(scope) {
var modal = firstIn(scope, '[data-aksrt-charge-modal]');
function initBalanceCharge() {
var modal = document.querySelector('[data-aksrt-charge-modal]');
if (!modal || modal.dataset.aksrtChargeInitialized === '1') return;
modal.dataset.aksrtChargeInitialized = '1';
var form = modal.querySelector('[data-aksrt-charge-form]');
@@ -481,8 +458,8 @@
});
}
function initTransfer(scope) {
var modal = firstIn(scope, '[data-aksrt-transfer-modal]');
function initTransfer() {
var modal = document.querySelector('[data-aksrt-transfer-modal]');
if (!modal || modal.dataset.aksrtTransferInitialized === '1') return;
modal.dataset.aksrtTransferInitialized = '1';
var form = modal.querySelector('[data-aksrt-transfer-form]');
@@ -613,8 +590,8 @@
});
}
function initPointsExchange(scope) {
var modal = firstIn(scope, '[data-aksrt-points-exchange-modal]');
function initPointsExchange() {
var modal = document.querySelector('[data-aksrt-points-exchange-modal]');
if (!modal || modal.dataset.aksrtPointsExchangeInitialized === '1') return;
modal.dataset.aksrtPointsExchangeInitialized = '1';
var form = modal.querySelector('[data-aksrt-points-exchange-form]');
@@ -673,8 +650,8 @@
});
}
function initWithdraw(scope) {
var modal = firstIn(scope, '[data-aksrt-withdraw-modal]');
function initWithdraw() {
var modal = document.querySelector('[data-aksrt-withdraw-modal]');
if (!modal || modal.dataset.aksrtWithdrawInitialized === '1') return;
modal.dataset.aksrtWithdrawInitialized = '1';
var form = modal.querySelector('[data-aksrt-withdraw-form]');
@@ -748,7 +725,8 @@
.then(function (payload) {
if (!payload || !payload.success || !payload.data || typeof payload.data.html !== 'string') return;
panel.innerHTML = payload.data.html;
if (window.AksrtFrontend && typeof window.AksrtFrontend.rehydrate === 'function') window.AksrtFrontend.rehydrate(panel, 'ajax');
if (window.jQuery) jQuery(document).trigger('post_ajax.ed', [panel]);
if (typeof window.auto_fun === 'function') window.auto_fun();
});
}
}).catch(function () {
@@ -758,28 +736,27 @@
});
}
function initAssetTabs(root) {
var nav = elementsIn(root, '[data-aksrt-asset-tab]');
function initAssetTabs() {
var nav = document.querySelectorAll('[data-aksrt-asset-tab]');
if (!nav.length) return;
var scope = root || document;
nav.forEach(function (link) {
if (link.dataset.aksrtAssetTabBound === 'true') return;
link.dataset.aksrtAssetTabBound = 'true';
link.addEventListener('click', function (e) {
e.preventDefault();
var key = link.getAttribute('data-aksrt-asset-tab');
elementsIn(scope, '[data-aksrt-asset-tab]').forEach(function (a) {
document.querySelectorAll('.uc-asset-tabs__nav [data-aksrt-asset-tab]').forEach(function (a) {
var li = a.closest('li');
if (!li) return;
var aKey = a.getAttribute('data-aksrt-asset-tab');
var on = aKey === key || (key === 'points_date' && aKey === 'points_free');
li.classList.toggle('active', on);
});
var tabs = firstIn(scope, '.uc-asset-tabs');
var tabs = document.querySelector('.uc-asset-tabs');
if (tabs && typeof tabs.scrollIntoView === 'function') {
tabs.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
elementsIn(scope, '[data-aksrt-asset-pane]').forEach(function (pane) {
document.querySelectorAll('[data-aksrt-asset-pane]').forEach(function (pane) {
var on = pane.getAttribute('data-aksrt-asset-pane') === key;
pane.classList.toggle('is-active', on);
pane.hidden = !on;
@@ -789,8 +766,8 @@
}
function initWithdrawHistory(scope) {
var modal = firstIn(scope, '[data-aksrt-withdraw-history-modal]');
function initWithdrawHistory() {
var modal = document.querySelector('[data-aksrt-withdraw-history-modal]');
if (!modal || modal.dataset.aksrtWithdrawHistoryInitialized === '1') return;
modal.dataset.aksrtWithdrawHistoryInitialized = '1';
function open() { modal.hidden = false; document.body.classList.add('uc-modal-open'); }
@@ -809,25 +786,22 @@
refresh: refreshAssetBalances
};
function bootAssets(root, reason) {
if (!balancesRefreshed && reason === 'init') {
balancesRefreshed = true;
function bootAssets() {
refreshAssetBalances();
}
initSigninGoto(root);
initAffiliateRevenue(root);
initVipShop(root);
initVipPointsExchange(root);
initCardPass(root);
initBalanceCharge(root);
initTransfer(root);
initPointsExchange(root);
initWithdraw(root);
initWithdrawHistory(root);
initAssetTabs(root);
initSigninGoto();
initAffiliateRevenue();
initVipShop();
initVipPointsExchange();
initCardPass();
initBalanceCharge();
initTransfer();
initPointsExchange();
initWithdraw();
initWithdrawHistory();
initAssetTabs();
}
if (window.AksrtFrontend && typeof window.AksrtFrontend.register === 'function') {
window.AksrtFrontend.register('credits', bootAssets);
}
jQuery(document).off('auto_fun.aksrt-credits').on('auto_fun.aksrt-credits', function () {
bootAssets();
});
})();
+3 -7
View File
@@ -18,10 +18,8 @@
searchInput: null,
items: [],
init: function (root) {
root = root || document;
this.sidebar = root.nodeType === 1 && root.matches('.aksrt-doc-sidebar')
? root : root.querySelector('.aksrt-doc-sidebar');
init: function () {
this.sidebar = document.querySelector('.aksrt-doc-sidebar');
if (!this.sidebar || this.sidebar.dataset.aksrtDocsNavBound === '1') return;
this.sidebar.dataset.aksrtDocsNavBound = '1';
@@ -132,7 +130,5 @@
},
};
window.AksrtFrontend.register('aksrt-docs-navigation', function (root) {
DocsNav.init(root);
});
jQuery(document).off('auto_fun.aksrt-docs-navigation').on('auto_fun.aksrt-docs-navigation', function () { DocsNav.init(); });
})();
+6 -13
View File
@@ -13,8 +13,9 @@
'use strict';
var DownloadStatus = {
init: function (root) {
this.root = root || document;
init: function () {
if (document.documentElement.dataset.aksrtDownloadStatusBound === '1') return;
document.documentElement.dataset.aksrtDownloadStatusBound = '1';
this.initFilterHighlight();
this.initCardHover();
},
@@ -23,13 +24,10 @@
* Animate filter button active state
*/
initFilterHighlight: function () {
var filters = this.root.nodeType === 1 && this.root.matches('.aksrt-download-hero__filter')
? [this.root] : this.root.querySelectorAll('.aksrt-download-hero__filter');
var filters = document.querySelectorAll('.aksrt-download-hero__filter');
if (filters.length === 0) return;
filters.forEach(function (btn) {
if (btn.dataset.aksrtDownloadHoverBound === '1') return;
btn.dataset.aksrtDownloadHoverBound = '1';
btn.addEventListener('mouseenter', function () {
btn.style.transform = 'translateY(-1px)';
});
@@ -43,13 +41,10 @@
* Card hover depth effect
*/
initCardHover: function () {
var cards = this.root.nodeType === 1 && this.root.matches('.aksrt-download-card')
? [this.root] : this.root.querySelectorAll('.aksrt-download-card');
var cards = document.querySelectorAll('.aksrt-download-card');
if (cards.length === 0) return;
cards.forEach(function (card) {
if (card.dataset.aksrtDownloadHoverBound === '1') return;
card.dataset.aksrtDownloadHoverBound = '1';
card.addEventListener('mouseenter', function () {
card.style.transform = 'translateY(-2px)';
});
@@ -60,7 +55,5 @@
},
};
window.AksrtFrontend.register('aksrt-download-status', function (root) {
DownloadStatus.init(root);
});
jQuery(document).off('auto_fun.aksrt-download-status').on('auto_fun.aksrt-download-status', function () { DownloadStatus.init(); });
})();
+100 -61
View File
@@ -10,64 +10,68 @@
'use strict';
var reducedMotion = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
var countUpObserver = null;
var countdownElements = [];
var countdownTimer = null;
var fpsDetectionStarted = false;
function scopeFor(root) {
return root && root.querySelectorAll ? root : document;
}
/* ============================================================
* 1. 数字递增 (count-up) — IntersectionObserver 触发
* 用法:<span data-aksrt-countup data-target="1234" data-duration="2000">0</span>
* ============================================================ */
function initCountUp() {
if (reducedMotion) return;
if (!('IntersectionObserver' in window)) return;
function eachMatch(root, selector, callback) {
var scope = scopeFor(root);
if (scope.nodeType === 1 && scope.matches(selector)) callback(scope);
scope.querySelectorAll(selector).forEach(callback);
}
var els = document.querySelectorAll('[data-aksrt-countup]:not([data-aksrt-countup-init])');
if (!els.length) return;
function animateCountUp(el) {
if (el.dataset.aksrtCountupBound === '1') return;
el.dataset.aksrtCountupBound = '1';
countUpObserver.observe(el);
}
function initCountUp(root) {
if (reducedMotion || !('IntersectionObserver' in window)) return;
if (!countUpObserver) {
countUpObserver = new IntersectionObserver(function (entries) {
var observer = new IntersectionObserver(function (entries) {
entries.forEach(function (entry) {
if (!entry.isIntersecting) return;
var el = entry.target;
countUpObserver.unobserve(el);
observer.unobserve(el);
var target = parseFloat(el.dataset.target || '0');
var duration = parseInt(el.dataset.duration || '2000', 10);
var decimals = (el.dataset.decimals || '0|').split('|');
var prefix = decimals[1] || '';
var dec = parseInt(decimals[0], 10) || 0;
var start = 0;
var startTime = null;
function step(timestamp) {
if (!startTime) startTime = timestamp;
var progress = Math.min((timestamp - startTime) / duration, 1);
var current = target * (1 - Math.pow(1 - progress, 3));
// ease-out cubic
var eased = 1 - Math.pow(1 - progress, 3);
var current = start + (target - start) * eased;
el.textContent = prefix + current.toFixed(dec).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
if (progress < 1) requestAnimationFrame(step);
else el.textContent = prefix + target.toFixed(dec).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
if (progress < 1) {
requestAnimationFrame(step);
} else {
el.textContent = prefix + target.toFixed(dec).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}
}
requestAnimationFrame(step);
});
}, { threshold: 0.3 });
els.forEach(function (el) {
el.dataset.aksrtCountupInit = '1';
observer.observe(el);
});
}
eachMatch(root, '[data-aksrt-countup]', animateCountUp);
}
/* ============================================================
* 2. 倒计时组件
* 用法:<span data-aksrt-countdown data-end="2026-12-31T23:59:59">--:--:--</span>
* ============================================================ */
function initCountdown() {
var els = document.querySelectorAll('[data-aksrt-countdown]:not([data-aksrt-countdown-init])');
if (!els.length) return;
function pad(n) { return n < 10 ? '0' + n : '' + n; }
function updateCountdowns() {
function update(el) {
var now = Date.now();
countdownElements = countdownElements.filter(function (el) { return document.documentElement.contains(el); });
countdownElements.forEach(function (el) {
var end = new Date(el.dataset.end).getTime();
var diff = end - now;
if (diff <= 0) {
@@ -76,35 +80,42 @@
}
var d = Math.floor(diff / 86400000);
var h = Math.floor((diff % 86400000) / 3600000);
var m = Math.floor((diff % 3600000) / 60000);
var m = Math.floor((diff % 86400000) / 60000);
var s = Math.floor((diff % 60000) / 1000);
var format = el.dataset.format || 'dhms';
if (format === 'dhms') el.textContent = (d > 0 ? d + '天 ' : '') + pad(h) + ':' + pad(m) + ':' + pad(s);
else if (format === 'hms') el.textContent = pad(h + d * 24) + ':' + pad(m) + ':' + pad(s);
else el.textContent = (d > 0 ? d + '天 ' : '') + pad(h) + '时' + pad(m) + '分' + pad(s) + '秒';
if (format === 'dhms') {
el.textContent = (d > 0 ? d + '天 ' : '') + pad(h) + ':' + pad(m) + ':' + pad(s);
} else if (format === 'hms') {
el.textContent = pad(h + d * 24) + ':' + pad(m) + ':' + pad(s);
} else {
el.textContent = (d > 0 ? d + '天 ' : '') + pad(h) + '时' + pad(m) + '分' + pad(s) + '秒';
}
}
els.forEach(function (el) {
el.dataset.aksrtCountdownInit = '1';
update(el);
setInterval(function () { update(el); }, 1000);
});
}
function initCountdown(root) {
eachMatch(root, '[data-aksrt-countdown]', function (el) {
if (el.dataset.aksrtCountdownBound === '1') return;
el.dataset.aksrtCountdownBound = '1';
countdownElements.push(el);
});
updateCountdowns();
if (!countdownTimer && countdownElements.length) countdownTimer = window.setInterval(updateCountdowns, 1000);
}
function initTilt(root) {
/* ============================================================
* 4. 3D 悬停倾斜 (vanilla tilt)
* 用法:<div data-aksrt-tilt data-tilt-max="15">...</div>
* ============================================================ */
function initTilt() {
if (reducedMotion) return;
eachMatch(root, '[data-aksrt-tilt]', function (el) {
document.querySelectorAll('[data-aksrt-tilt]').forEach(function (el) {
if (el.dataset.tiltBound) return;
el.dataset.tiltBound = '1';
var maxDeg = parseFloat(el.dataset.tiltMax || '10');
var perspective = parseFloat(el.dataset.tiltPerspective || '800');
var scale = parseFloat(el.dataset.tiltScale || '1.03');
var glare = el.dataset.tiltGlare === '1';
var glareEl = null;
if (glare) {
glareEl = document.createElement('div');
glareEl.style.cssText = 'position:absolute;inset:0;border-radius:inherit;pointer-events:none;background:linear-gradient(135deg,rgba(255,255,255,0) 0%,rgba(255,255,255,0.25) 100%);opacity:0;transition:opacity 0.2s;';
@@ -112,13 +123,17 @@
el.style.overflow = 'hidden';
el.appendChild(glareEl);
}
el.addEventListener('mousemove', function (e) {
var rect = el.getBoundingClientRect();
var x = (e.clientX - rect.left) / rect.width;
var y = (e.clientY - rect.top) / rect.height;
el.style.transform = 'perspective(' + perspective + 'px) rotateX(' + ((0.5 - y) * maxDeg) + 'deg) rotateY(' + ((x - 0.5) * maxDeg) + 'deg) scale3d(' + scale + ',' + scale + ',' + scale + ')';
var rotateX = (0.5 - y) * maxDeg;
var rotateY = (x - 0.5) * maxDeg;
el.style.transform = 'perspective(' + perspective + 'px) rotateX(' + rotateX + 'deg) rotateY(' + rotateY + 'deg) scale3d(' + scale + ',' + scale + ',' + scale + ')';
if (glareEl) glareEl.style.opacity = '1';
});
el.addEventListener('mouseleave', function () {
el.style.transform = 'perspective(' + perspective + 'px) rotateX(0deg) rotateY(0deg) scale3d(1,1,1)';
if (glareEl) glareEl.style.opacity = '0';
@@ -126,30 +141,54 @@
});
}
function initFpsDetection(root, reason) {
if (fpsDetectionStarted || !('requestAnimationFrame' in window)) return;
fpsDetectionStarted = true;
/* ============================================================
* 5. FPS 检测 + 低端设备降级 — 只检测一次
* ============================================================ */
var fpsDetected = false;
function initFpsDetection() {
if (fpsDetected || !('requestAnimationFrame' in window)) return;
fpsDetected = true;
var frames = 0;
var startTime = performance.now();
function countFrames() {
frames++;
var elapsed = performance.now() - startTime;
if (elapsed >= 1000) {
if (Math.round(frames * 1000 / elapsed) < 24 && document.body) document.body.classList.add('fps-accelerat');
return;
var fps = Math.round(frames * 1000 / elapsed);
if (fps < 24) {
document.body.classList.add('fps-accelerat');
}
requestAnimationFrame(countFrames);
return; // 只检测一次
}
requestAnimationFrame(countFrames);
}
function init(root, reason) {
initCountUp(root);
initCountdown(root);
if (typeof initMarquee === 'function') initMarquee(root, reason);
initTilt(root);
initFpsDetection(root, reason);
requestAnimationFrame(countFrames);
}
/* ============================================================
* 初始化入口 — 先执行一次,随后监听 auto_fun 重扫(各 init 幂等)
* ============================================================ */
function init() {
initCountUp();
initCountdown();
if (typeof initMarquee === 'function') {
initMarquee();
}
initTilt();
initFpsDetection();
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', init);
} else {
init();
}
if (window.jQuery) {
window.jQuery(document).on('auto_fun', init);
}
window.AksrtFrontend.register('aksrt-effects', init);
})();
+30 -532
View File
@@ -1,7 +1,8 @@
/**
* AKSRT Enhancements — 全局 UI 增强
*
* 包含:图片灯箱、滚动方向感知
* 图片灯箱由 assets/js/runtime/imgbox.js(Miniimgbox,zibll 风格)唯一负责,
* 此文件仅保留滚动方向感知的 legacy class 同步。
*
* @package AKSRT
*/
@@ -9,531 +10,15 @@
(function () {
'use strict';
var lightboxEl = null;
var lightboxImg = null;
var lightboxCaption = null;
var lightboxCounter = null;
var lightboxThumbsWrap = null;
var currentGallery = [];
var currentIndex = 0;
var currentZoom = 1;
var autoplayTimer = null;
var isAutoplay = false;
var lastTrigger = null;
var previousBodyOverflow = '';
var globalsBound = false;
var scrollDirectionBound = false;
var EXCLUDE_SEL = '.no-imgbox,.no-lightbox,.avatar,.img-icon,.avatar-badge,.aksrt-avatar,[data-no-lightbox],[data-aksrt-lightbox="0"]';
var TRIGGER_SEL = '[data-aksrt-lightbox="1"] img,.aksrt-lightbox-trigger img,.imgbox-container img,.comment-content .box-img';
var ANCHOR_TRIGGER_SEL = 'a[data-aksrt-lightbox-trigger]';
var GROUP_SEL = '[data-aksrt-lightbox-group],.content-gallery[data-aksrt-lightbox="1"],.aksrt-carousel-block[data-aksrt-lightbox="1"],.imgbox-container,.comment-content,.post_front_content[data-aksrt-lightbox="1"],.wp-posts-content[data-aksrt-lightbox="1"],.entry-thumb[data-aksrt-lightbox="1"],.entry-content[data-aksrt-lightbox="1"],.aksrt-lightbox-trigger,[data-aksrt-lightbox="1"]';
var IMAGE_URL_RE = /\.(?:avif|bmp|gif|ico|jpe?g|png|svg|tiff?|webp)(?:[?#].*)?$/i;
var MAX_ZOOM_DESKTOP = 2;
var MAX_ZOOM_MOBILE = 3;
function lightboxFlag(key, fallback) {
var config = window._win || {};
if (config[key] === undefined || config[key] === null || config[key] === '') return fallback;
return config[key] === true || config[key] === 1 || config[key] === '1';
}
function lightboxEnabled() {
return lightboxFlag('imgbox', false);
}
function normalizeFullUrl(url) {
if (!url || url.indexOf('data:') === 0) return url || '';
return url
.replace(/-\d+x\d+(\.[a-z0-9]+)(?=([?#]|$))/i, '$1')
.replace(/([?&])x-oss-process=[^#&]*&?/i, '$1')
.replace(/[?&]$/, '');
}
function resolveFullUrl(img) {
var explicitFull = img.getAttribute('data-full-url') || '';
if (explicitFull) return normalizeFullUrl(explicitFull);
var anchor = img.closest('a[href]');
var href = anchor ? anchor.getAttribute('href') || '' : '';
if (IMAGE_URL_RE.test(href)) return normalizeFullUrl(href);
return normalizeFullUrl(
img.getAttribute('data-src')
|| img.getAttribute('data-lazy-src')
|| img.currentSrc
|| img.getAttribute('src')
|| ''
);
}
function resolveThumbUrl(img) {
return img.currentSrc
|| img.getAttribute('src')
|| img.getAttribute('data-src')
|| img.getAttribute('data-lazy-src')
|| img.getAttribute('data-full-url')
|| '';
}
function resolveCaption(img) {
var anchor = img.closest('a');
var explicit = anchor ? anchor.getAttribute('data-caption') || '' : '';
if (explicit.trim()) return explicit.trim();
var figure = img.closest('figure');
var figcaption = figure ? figure.querySelector('figcaption') : null;
if (figcaption && figcaption.textContent.trim()) return figcaption.textContent.trim();
return (img.getAttribute('alt') || '').trim();
}
function isNoLightbox(img) {
if (!img || img.closest(EXCLUDE_SEL)) return true;
var parentA = img.closest('a[href]');
if (parentA) {
var href = parentA.getAttribute('href') || '';
if (href && !IMAGE_URL_RE.test(href) && !parentA.hasAttribute('data-aksrt-lightbox-trigger')) {
return true;
}
}
return resolveFullUrl(img) === '';
}
function createLightbox() {
if (!lightboxEnabled()) return null;
if (lightboxEl) return lightboxEl;
lightboxEl = document.createElement('div');
lightboxEl.className = 'aksrt-lightbox';
lightboxEl.setAttribute('role', 'dialog');
lightboxEl.setAttribute('aria-modal', 'true');
lightboxEl.setAttribute('aria-hidden', 'true');
lightboxEl.setAttribute('aria-label', '图片预览');
lightboxEl.setAttribute('tabindex', '-1');
lightboxEl.innerHTML =
'<div class="aksrt-lightbox__toolbar">' +
'<span class="aksrt-lightbox__counter" aria-live="polite"></span>' +
'<button type="button" class="aksrt-lightbox__tool toggle-zoom" title="缩放" aria-label="缩放"><i class="fa fas fa-search-plus" aria-hidden="true"></i></button>' +
'<button type="button" class="aksrt-lightbox__tool toggle-thumbs" title="缩略图" aria-label="显示或隐藏缩略图"><i class="fa fas fa-th" aria-hidden="true"></i></button>' +
'<button type="button" class="aksrt-lightbox__tool toggle-play" title="幻灯片" aria-label="播放幻灯片"><i class="fa fas fa-play" aria-hidden="true"></i></button>' +
'<button type="button" class="aksrt-lightbox__tool toggle-full" title="全屏" aria-label="切换全屏"><i class="fa fas fa-expand" aria-hidden="true"></i></button>' +
'<a class="aksrt-lightbox__tool aksrt-lightbox__download" title="下载" aria-label="下载图片" download><i class="fa fas fa-download" aria-hidden="true"></i></a>' +
'<button type="button" class="aksrt-lightbox__tool aksrt-lightbox__close" title="关闭" aria-label="关闭"><i class="fa fas fa-times" aria-hidden="true"></i></button>' +
'</div>' +
'<button type="button" class="aksrt-lightbox__nav aksrt-lightbox__nav--prev" aria-label="上一张"><i class="fa fas fa-chevron-left" aria-hidden="true"></i></button>' +
'<div class="aksrt-lightbox__stage"><img class="aksrt-lightbox__img" src="" alt=""></div>' +
'<button type="button" class="aksrt-lightbox__nav aksrt-lightbox__nav--next" aria-label="下一张"><i class="fa fas fa-chevron-right" aria-hidden="true"></i></button>' +
'<div class="aksrt-lightbox__caption" aria-live="polite"></div>' +
'<div class="aksrt-lightbox__thumbs" hidden></div>';
document.body.appendChild(lightboxEl);
lightboxImg = lightboxEl.querySelector('.aksrt-lightbox__img');
lightboxCaption = lightboxEl.querySelector('.aksrt-lightbox__caption');
lightboxCounter = lightboxEl.querySelector('.aksrt-lightbox__counter');
lightboxThumbsWrap = lightboxEl.querySelector('.aksrt-lightbox__thumbs');
lightboxEl.querySelector('.aksrt-lightbox__close').addEventListener('click', function (event) {
event.stopPropagation();
closeLightbox();
});
lightboxEl.addEventListener('click', function (event) {
if (event.target === lightboxEl || event.target.classList.contains('aksrt-lightbox__stage')) closeLightbox();
});
lightboxEl.querySelector('.aksrt-lightbox__nav--prev').addEventListener('click', function (event) {
event.stopPropagation();
navigateLightbox(-1);
});
lightboxEl.querySelector('.aksrt-lightbox__nav--next').addEventListener('click', function (event) {
event.stopPropagation();
navigateLightbox(1);
});
document.addEventListener('keydown', function (event) {
if (!lightboxEl || !lightboxEl.classList.contains('is-open')) return;
if (event.key === 'Escape') closeLightbox();
if (event.key === 'ArrowLeft') navigateLightbox(-1);
if (event.key === 'ArrowRight') navigateLightbox(1);
if (event.key === 'Tab') trapFocus(event);
});
lightboxEl.addEventListener('wheel', function (event) {
if (!lightboxEl.classList.contains('is-open') || currentZoom > 1 || currentGallery.length < 2) return;
event.preventDefault();
navigateLightbox(event.deltaY > 0 ? 1 : -1);
}, { passive: false });
lightboxImg.addEventListener('click', function (event) {
event.stopPropagation();
if (lightboxFlag('imgbox_zoom', true)) toggleZoom();
});
lightboxImg.addEventListener('dblclick', function (event) {
if (!lightboxFlag('imgbox_zoom', true)) return;
event.stopPropagation();
var maxZoom = window.innerWidth < 768 ? MAX_ZOOM_MOBILE : MAX_ZOOM_DESKTOP;
setZoom(currentZoom < maxZoom ? maxZoom : 1);
});
bindTouchGestures();
lightboxEl.querySelector('.toggle-zoom').addEventListener('click', function (event) {
event.stopPropagation();
toggleZoom();
});
lightboxEl.querySelector('.toggle-thumbs').addEventListener('click', function (event) {
event.stopPropagation();
lightboxThumbsWrap.hidden = !lightboxThumbsWrap.hidden;
});
lightboxEl.querySelector('.toggle-play').addEventListener('click', function (event) {
event.stopPropagation();
toggleAutoplay();
});
lightboxEl.querySelector('.toggle-full').addEventListener('click', function (event) {
event.stopPropagation();
toggleFullscreen();
});
document.addEventListener('fullscreenchange', syncFullscreenState);
document.addEventListener('webkitfullscreenchange', syncFullscreenState);
return lightboxEl;
}
function bindTouchGestures() {
var pinchStart = 0;
var touchStartY = 0;
var touchStartX = 0;
var pullDistance = 0;
lightboxEl.addEventListener('touchstart', function (event) {
if (event.touches.length === 2 && lightboxFlag('imgbox_zoom', true)) {
pinchStart = Math.hypot(
event.touches[1].clientX - event.touches[0].clientX,
event.touches[1].clientY - event.touches[0].clientY
);
return;
}
if (event.touches.length === 1 && currentZoom <= 1.05) {
touchStartY = event.touches[0].clientY;
touchStartX = event.touches[0].clientX;
pullDistance = 0;
}
}, { passive: true });
lightboxEl.addEventListener('touchmove', function (event) {
if (event.touches.length === 2 && pinchStart > 0 && lightboxFlag('imgbox_zoom', true)) {
var distance = Math.hypot(
event.touches[1].clientX - event.touches[0].clientX,
event.touches[1].clientY - event.touches[0].clientY
);
var maxZoom = window.innerWidth < 768 ? MAX_ZOOM_MOBILE : MAX_ZOOM_DESKTOP;
setZoom(Math.min(maxZoom, Math.max(1, currentZoom * (distance / pinchStart))));
pinchStart = distance;
return;
}
if (event.touches.length !== 1 || currentZoom > 1.05) return;
var dy = event.touches[0].clientY - touchStartY;
var dx = event.touches[0].clientX - touchStartX;
if (Math.abs(dy) > Math.abs(dx) && dy > 30) {
pullDistance = dy;
lightboxImg.style.transform = 'translate3d(0, ' + dy + 'px, 0) scale(' + currentZoom + ')';
lightboxImg.style.opacity = String(Math.max(0.2, Math.min(1, (150 - dy) / 80)));
}
}, { passive: true });
lightboxEl.addEventListener('touchend', function () {
pinchStart = 0;
if (pullDistance > 100) {
closeLightbox();
} else if (pullDistance > 0) {
setZoom(1);
}
lightboxImg.style.opacity = '';
pullDistance = 0;
}, { passive: true });
}
function trapFocus(event) {
var focusable = Array.prototype.filter.call(
lightboxEl.querySelectorAll('a[href],button:not([hidden]):not([disabled]),[tabindex]:not([tabindex="-1"])'),
function (element) { return element.offsetParent !== null; }
);
if (!focusable.length) {
event.preventDefault();
lightboxEl.focus();
return;
}
var first = focusable[0];
var last = focusable[focusable.length - 1];
if (event.shiftKey && document.activeElement === first) {
event.preventDefault();
last.focus();
} else if (!event.shiftKey && document.activeElement === last) {
event.preventDefault();
first.focus();
}
}
function setZoom(zoom) {
if (!lightboxImg || !lightboxEl) return;
currentZoom = zoom;
lightboxImg.style.transform = 'scale(' + zoom + ')';
lightboxEl.classList.toggle('is-zoomed', zoom > 1);
}
function toggleZoom() {
if (!lightboxFlag('imgbox_zoom', true)) return;
var maxZoom = window.innerWidth < 768 ? MAX_ZOOM_MOBILE : MAX_ZOOM_DESKTOP;
setZoom(currentZoom > 1 ? 1 : maxZoom);
}
function toggleAutoplay() {
if (!lightboxEl) return;
var icon = lightboxEl.querySelector('.toggle-play i');
if (isAutoplay) {
clearInterval(autoplayTimer);
autoplayTimer = null;
isAutoplay = false;
icon.className = 'fa fas fa-play';
return;
}
if (currentGallery.length < 2) return;
isAutoplay = true;
icon.className = 'fa fas fa-pause';
autoplayTimer = setInterval(function () { navigateLightbox(1); }, 3000);
}
function toggleFullscreen() {
if (!lightboxEl || !lightboxFlag('imgbox_full', true)) return;
var fullscreenElement = document.fullscreenElement || document.webkitFullscreenElement;
if (fullscreenElement) {
var exit = document.exitFullscreen || document.webkitExitFullscreen;
if (exit) exit.call(document);
return;
}
var request = lightboxEl.requestFullscreen || lightboxEl.webkitRequestFullscreen;
if (request) request.call(lightboxEl);
}
function syncFullscreenState() {
if (!lightboxEl) return;
var active = Boolean(document.fullscreenElement || document.webkitFullscreenElement);
var icon = lightboxEl.querySelector('.toggle-full i');
lightboxEl.classList.toggle('full-screen', active);
icon.className = active ? 'fa fas fa-compress' : 'fa fas fa-expand';
}
function buildThumbnails() {
if (!lightboxThumbsWrap) return;
lightboxThumbsWrap.innerHTML = '';
currentGallery.forEach(function (item, index) {
var button = document.createElement('button');
var thumb = document.createElement('img');
button.type = 'button';
button.className = 'aksrt-lightbox__thumb' + (index === currentIndex ? ' is-active' : '');
button.setAttribute('aria-label', '查看第 ' + (index + 1) + ' 张图片');
thumb.src = item.thumbSrc || item.src;
thumb.alt = '';
button.appendChild(thumb);
button.addEventListener('click', function (event) {
event.stopPropagation();
showLightboxImage(index);
});
lightboxThumbsWrap.appendChild(button);
});
}
function syncThumbActive() {
if (!lightboxThumbsWrap) return;
var thumbs = lightboxThumbsWrap.querySelectorAll('.aksrt-lightbox__thumb');
thumbs.forEach(function (thumb, index) {
thumb.classList.toggle('is-active', index === currentIndex);
});
var active = thumbs[currentIndex];
if (active) active.scrollIntoView({ inline: 'center', block: 'nearest' });
}
function syncControls() {
if (!lightboxEl) return;
var multiple = currentGallery.length > 1;
var fullscreenAvailable = Boolean(
lightboxEl.requestFullscreen
|| lightboxEl.webkitRequestFullscreen
|| document.fullscreenEnabled
|| document.webkitFullscreenEnabled
);
var thumbsEnabled = multiple && lightboxFlag('imgbox_thumbs', true);
lightboxEl.querySelector('.toggle-zoom').hidden = !lightboxFlag('imgbox_zoom', true);
lightboxEl.querySelector('.toggle-thumbs').hidden = !thumbsEnabled;
lightboxEl.querySelector('.toggle-play').hidden = !multiple || !lightboxFlag('imgbox_play', false);
lightboxEl.querySelector('.toggle-full').hidden = !lightboxFlag('imgbox_full', true) || !fullscreenAvailable;
lightboxEl.querySelector('.aksrt-lightbox__download').hidden = !lightboxFlag('imgbox_down', false);
lightboxEl.querySelector('.aksrt-lightbox__nav--prev').hidden = !multiple;
lightboxEl.querySelector('.aksrt-lightbox__nav--next').hidden = !multiple;
lightboxThumbsWrap.hidden = !thumbsEnabled;
}
function openLightbox(src, caption, gallery, index, originEl) {
if (!lightboxEnabled() || !createLightbox()) return false;
currentGallery = gallery && gallery.length ? gallery : [{ src: src, fullSrc: src, thumbSrc: src, caption: caption || '' }];
currentIndex = Number.isInteger(index) ? index : 0;
currentZoom = 1;
lastTrigger = originEl || document.activeElement;
if (originEl && typeof originEl.getBoundingClientRect === 'function') {
var rect = originEl.getBoundingClientRect();
lightboxEl.style.setProperty('--imgbox-origin-top', (rect.top + rect.height / 2) + 'px');
lightboxEl.style.setProperty('--imgbox-origin-left', (rect.left + rect.width / 2) + 'px');
lightboxEl.classList.add('from-origin');
} else {
lightboxEl.classList.remove('from-origin');
}
buildThumbnails();
syncControls();
showLightboxImage(currentIndex);
lightboxEl.classList.add('is-open');
lightboxEl.setAttribute('aria-hidden', 'false');
previousBodyOverflow = document.body.style.overflow;
document.body.style.overflow = 'hidden';
document.body.classList.add('aksrt-lightbox-open');
lightboxEl.querySelector('.aksrt-lightbox__close').focus();
lightboxEl.dispatchEvent(new CustomEvent('aksrt:lightbox-open', { bubbles: true }));
return true;
}
function showLightboxImage(index) {
if (!currentGallery.length || !lightboxImg) return;
if (index < 0) index = currentGallery.length - 1;
if (index >= currentGallery.length) index = 0;
currentIndex = index;
setZoom(1);
var item = currentGallery[currentIndex];
lightboxImg.src = item.fullSrc || item.src;
lightboxImg.alt = item.caption || '';
lightboxCaption.textContent = item.caption || '';
lightboxCaption.hidden = !item.caption;
if (currentGallery.length > 1) {
lightboxCounter.textContent = (currentIndex + 1) + ' / ' + currentGallery.length;
lightboxCounter.hidden = false;
} else {
lightboxCounter.textContent = '';
lightboxCounter.hidden = true;
}
var download = lightboxEl.querySelector('.aksrt-lightbox__download');
var fullSrc = item.fullSrc || item.src;
download.href = fullSrc;
download.download = fullSrc.substring(fullSrc.lastIndexOf('/') + 1).split(/[?#]/)[0] || 'image';
syncThumbActive();
}
function navigateLightbox(direction) {
if (currentGallery.length < 2) return;
showLightboxImage(currentIndex + direction);
}
function closeLightbox() {
if (!lightboxEl || !lightboxEl.classList.contains('is-open')) return;
if (isAutoplay) toggleAutoplay();
lightboxEl.classList.remove('is-open', 'is-zoomed', 'from-origin');
lightboxEl.setAttribute('aria-hidden', 'true');
document.body.style.overflow = previousBodyOverflow;
document.body.classList.remove('aksrt-lightbox-open');
lightboxThumbsWrap.hidden = true;
lightboxImg.src = '';
lightboxImg.alt = '';
var fullscreenElement = document.fullscreenElement || document.webkitFullscreenElement;
var exit = document.exitFullscreen || document.webkitExitFullscreen;
if (fullscreenElement && exit) exit.call(document);
if (lastTrigger && typeof lastTrigger.focus === 'function' && document.contains(lastTrigger)) {
lastTrigger.focus({ preventScroll: true });
}
lastTrigger = null;
}
function buildGallery(img) {
var container = img.closest(GROUP_SEL);
if (!container || container.closest('[data-no-lightbox],[data-aksrt-lightbox="0"]')) return null;
var gallery = [];
var foundIndex = -1;
container.querySelectorAll('img').forEach(function (candidate) {
if (!candidate.matches(TRIGGER_SEL) || isNoLightbox(candidate)) return;
var fullSrc = resolveFullUrl(candidate);
var thumbSrc = resolveThumbUrl(candidate) || fullSrc;
if (!fullSrc) return;
if (candidate === img) foundIndex = gallery.length;
gallery.push({
src: thumbSrc,
thumbSrc: thumbSrc,
fullSrc: fullSrc,
caption: resolveCaption(candidate),
});
});
if (foundIndex < 0 || !gallery.length) return null;
return { items: gallery, index: foundIndex };
}
function openImage(img) {
if (isNoLightbox(img)) return false;
var gallery = buildGallery(img);
if (!gallery) return false;
var item = gallery.items[gallery.index];
return openLightbox(item.fullSrc, item.caption, gallery.items, gallery.index, img);
}
function initLightbox(root, reason) {
if (globalsBound) return;
globalsBound = true;
document.addEventListener('click', function (event) {
if (!lightboxEnabled() || !(event.target instanceof Element)) return;
var anchor = event.target.closest(ANCHOR_TRIGGER_SEL);
if (anchor && !anchor.closest(EXCLUDE_SEL)) {
var anchorImage = anchor.querySelector('img');
if (anchorImage && openImage(anchorImage)) {
event.preventDefault();
return;
}
var href = anchor.getAttribute('href') || '';
if (IMAGE_URL_RE.test(href) && openLightbox(href, anchor.getAttribute('data-caption') || '', null, 0, anchor)) {
event.preventDefault();
}
return;
}
var img = event.target.closest(TRIGGER_SEL);
if (img && openImage(img)) event.preventDefault();
});
}
window.AksrtLightbox = {
open: openLightbox,
close: closeLightbox,
};
// Scroll direction is handled by aksrt-runtime.js. Keep the prefixed
// classes in sync for the remaining CSS consumers.
function initScrollDirection(root, reason) {
if (scrollDirectionBound || !document.body) return;
scrollDirectionBound = true;
var initialized = false;
/* ============================================================
* 滚动方向感知
* Scroll direction is owned by runtime main.js body scroll bus
* (body.scroll-down / body.scroll-up / body.body-scroll).
* This stub syncs the legacy aksrt-* prefixed classes for backward compat.
* ============================================================ */
function initScrollDirection() {
var body = document.body;
function sync() {
@@ -548,13 +33,26 @@
}, 300);
}
window.addEventListener('scroll', function () {
function onScroll() {
requestAnimationFrame(sync);
}, { passive: true });
}
window.AksrtFrontend.register('aksrt-enhancements', function (root, reason) {
initLightbox(root, reason);
initScrollDirection(root, reason);
});
window.addEventListener('scroll', onScroll, { passive: true });
}
/* ============================================================
* 初始化入口 — 只执行一次(window scroll 绑定不可重复)
* ============================================================ */
function init() {
if (initialized) return;
initialized = true;
initScrollDirection();
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', init);
} else {
init();
}
})();
+171 -120
View File
@@ -9,27 +9,11 @@
(function () {
'use strict';
var animateObserver = null;
var rippleBound = false;
var stickyScrollBound = false;
var parallaxScrollBound = false;
var modalBound = false;
var stickyElements = [];
var parallaxElements = [];
var parallaxTicking = false;
function scopeFor(root) {
return root && root.querySelectorAll ? root : document;
}
function eachMatch(root, selector, callback) {
var scope = scopeFor(root);
if (scope.nodeType === 1 && scope.matches(selector)) callback(scope);
scope.querySelectorAll(selector).forEach(callback);
}
function initTilt(root) {
eachMatch(root, '[data-aksrt-tilt]', function (el) {
/* ============================================================
* 1. 3D 悬停倾斜效果 (vanilla-tilt 轻量版)
* ============================================================ */
function initTilt() {
document.querySelectorAll('[data-aksrt-tilt]').forEach(function (el) {
if (el.dataset.tiltInit) return;
el.dataset.tiltInit = '1';
@@ -74,184 +58,251 @@
});
}
function prepareAnimation(el) {
if (el.dataset.aksrtAnimateBound === '1') return;
el.dataset.aksrtAnimateBound = '1';
var animation = el.dataset.aksrtAnimate || 'fadeInUp';
el.style.opacity = '0';
switch (animation) {
case 'fadeIn': el.style.transform = 'none'; break;
case 'fadeInUp': el.style.transform = 'translateY(30px)'; break;
case 'fadeInDown': el.style.transform = 'translateY(-30px)'; break;
case 'fadeInLeft': el.style.transform = 'translateX(-30px)'; break;
case 'fadeInRight': el.style.transform = 'translateX(30px)'; break;
case 'zoomIn': el.style.transform = 'scale(0.9)'; break;
default: el.style.transform = 'translateY(30px)';
}
animateObserver.observe(el);
}
function initScrollAnimations(root) {
/* ============================================================
* 2. 滚动触发动画 (IntersectionObserver)
* ============================================================ */
function initScrollAnimations() {
if (!('IntersectionObserver' in window)) {
eachMatch(root, '[data-aksrt-animate]', function (el) {
// 不支持时直接显示所有元素
document.querySelectorAll('[data-aksrt-animate]').forEach(function (el) {
el.style.opacity = '1';
el.style.transform = 'none';
});
return;
}
if (!animateObserver) {
animateObserver = new IntersectionObserver(function (entries) {
var observer = new IntersectionObserver(function (entries) {
entries.forEach(function (entry) {
if (!entry.isIntersecting) return;
var el = entry.target;
var animation = el.dataset.aksrtAnimate || 'fadeInUp';
var delay = parseInt(el.dataset.aksrtAnimateDelay || '0', 10);
var duration = parseInt(el.dataset.aksrtAnimateDuration || '600', 10);
animateObserver.unobserve(el);
window.setTimeout(function () {
setTimeout(function () {
el.style.transition = 'opacity ' + duration + 'ms ease, transform ' + duration + 'ms ease';
el.style.opacity = '1';
el.style.transform = 'translateY(0) translateX(0) scale(1)';
el.classList.add('aksrt-animated');
}, delay);
observer.unobserve(el);
});
}, { threshold: 0.1, rootMargin: '0px 0px -50px 0px' });
}, {
threshold: 0.1,
rootMargin: '0px 0px -50px 0px',
});
document.querySelectorAll('[data-aksrt-animate]').forEach(function (el) {
if (el.dataset.aksrtAnimateInit) return;
el.dataset.aksrtAnimateInit = '1';
var animation = el.dataset.aksrtAnimate || 'fadeInUp';
// 设置初始状态
el.style.opacity = '0';
switch (animation) {
case 'fadeIn':
el.style.transform = 'none';
break;
case 'fadeInUp':
el.style.transform = 'translateY(30px)';
break;
case 'fadeInDown':
el.style.transform = 'translateY(-30px)';
break;
case 'fadeInLeft':
el.style.transform = 'translateX(-30px)';
break;
case 'fadeInRight':
el.style.transform = 'translateX(30px)';
break;
case 'zoomIn':
el.style.transform = 'scale(0.9)';
break;
default:
el.style.transform = 'translateY(30px)';
}
eachMatch(root, '[data-aksrt-animate]', prepareAnimation);
observer.observe(el);
});
}
function updateSticky() {
stickyElements = stickyElements.filter(function (el) { return document.documentElement.contains(el); });
stickyElements.forEach(function (el) {
/* ============================================================
* 5. 粘性元素 (Sticky)
* ============================================================ */
function initSticky() {
document.querySelectorAll('[data-aksrt-sticky]').forEach(function (el) {
if (el.dataset.aksrtStickyInit) return;
el.dataset.aksrtStickyInit = '1';
var top = parseInt(el.dataset.aksrtStickyTop || '80', 10);
var parent = el.parentElement;
if (!parent) return;
var parentRect = parent.getBoundingClientRect();
var offset = parseInt(el.dataset.aksrtStickyOffset || '0', 10);
function update() {
var rect = el.getBoundingClientRect();
var parentRect = el.parentElement.getBoundingClientRect();
if (parentRect.top < top && parentRect.bottom > el.offsetHeight + top) {
el.style.position = 'sticky';
el.style.top = top + 'px';
}
}
window.addEventListener('scroll', update, { passive: true });
});
}
function initSticky(root) {
eachMatch(root, '[data-aksrt-sticky]', function (el) {
if (el.dataset.aksrtStickyBound === '1') return;
el.dataset.aksrtStickyBound = '1';
stickyElements.push(el);
});
if (!stickyScrollBound) {
stickyScrollBound = true;
window.addEventListener('scroll', updateSticky, { passive: true });
}
updateSticky();
}
/* ============================================================
* 6. 视差滚动
* ============================================================ */
var parallaxScrollBound = false;
function updateParallax() {
parallaxElements = parallaxElements.filter(function (el) { return document.documentElement.contains(el); });
parallaxElements.forEach(function (el) {
function initParallax() {
if (!document.querySelector('[data-aksrt-parallax]')) return;
if (parallaxScrollBound) return;
parallaxScrollBound = true;
var ticking = false;
function update() {
document.querySelectorAll('[data-aksrt-parallax]').forEach(function (el) {
var speed = parseFloat(el.dataset.aksrtParallax || '0.3');
var rect = el.getBoundingClientRect();
var center = rect.top + rect.height / 2;
var offset = (center - window.innerHeight / 2) * speed;
var windowCenter = window.innerHeight / 2;
var offset = (center - windowCenter) * speed;
el.style.transform = 'translateY(' + offset + 'px)';
});
parallaxTicking = false;
ticking = false;
}
function initParallax(root) {
eachMatch(root, '[data-aksrt-parallax]', function (el) {
if (el.dataset.aksrtParallaxBound === '1') return;
el.dataset.aksrtParallaxBound = '1';
parallaxElements.push(el);
});
if (!parallaxScrollBound) {
parallaxScrollBound = true;
window.addEventListener('scroll', function () {
if (parallaxTicking) return;
parallaxTicking = true;
requestAnimationFrame(updateParallax);
if (!ticking) {
requestAnimationFrame(update);
ticking = true;
}
}, { passive: true });
}
updateParallax();
}
function initRipple(root, reason) {
/* ============================================================
* 7. 涟漪点击效果 — document 委托只绑定一次
* ============================================================ */
var rippleBound = false;
function initRipple() {
if (rippleBound) return;
rippleBound = true;
document.addEventListener('click', function (e) {
var el = e.target.closest('.aksrt-ripple');
if (!el) return;
var rect = el.getBoundingClientRect();
var x = e.clientX - rect.left;
var y = e.clientY - rect.top;
var size = Math.max(rect.width, rect.height) * 2;
var wave = document.createElement('span');
wave.className = 'aksrt-ripple__wave';
wave.style.width = wave.style.height = size + 'px';
wave.style.left = (e.clientX - rect.left - size / 2) + 'px';
wave.style.top = (e.clientY - rect.top - size / 2) + 'px';
wave.style.left = (x - size / 2) + 'px';
wave.style.top = (y - size / 2) + 'px';
el.appendChild(wave);
wave.addEventListener('animationend', function () { wave.remove(); });
wave.addEventListener('animationend', function () {
wave.remove();
});
});
}
function initFloatLabels(root) {
eachMatch(root, '.aksrt-float-label__input', function (input) {
if (input.value) input.setAttribute('data-has-value', '1');
if (input.dataset.aksrtFloatLabelBound === '1') return;
input.dataset.aksrtFloatLabelBound = '1';
/* ============================================================
* 8. 表单浮动标签自动初始化
* ============================================================ */
function initFloatLabels() {
document.querySelectorAll('.aksrt-float-label__input').forEach(function (input) {
if (input.dataset.aksrtFloatInit) return;
input.dataset.aksrtFloatInit = '1';
// 检查初始值
if (input.value) {
input.setAttribute('data-has-value', '1');
}
input.addEventListener('input', function () {
if (this.value) this.setAttribute('data-has-value', '1');
else this.removeAttribute('data-has-value');
if (this.value) {
this.setAttribute('data-has-value', '1');
} else {
this.removeAttribute('data-has-value');
}
});
});
}
function initSigninCalendar(root) {
eachMatch(root, '[data-aksrt-signin-calendar]', function (calendar) {
if (calendar.dataset.aksrtSigninCalendarBound === '1') return;
calendar.dataset.aksrtSigninCalendarBound = '1';
/* ============================================================
* 8. 签到日历可视化
* ============================================================ */
function initSigninCalendar() {
var calendar = document.querySelector('[data-aksrt-signin-calendar]');
if (!calendar) return;
var data = [];
try { data = JSON.parse(calendar.dataset.aksrtSigninCalendar || '[]'); } catch (e) {}
try {
data = JSON.parse(calendar.dataset.aksrtSigninCalendar || '[]');
} catch (e) {}
// 生成最近 30 天的格子
var today = new Date();
var html = '<div class="aksrt-signin-calendar__grid">';
for (var i = 29; i >= 0; i--) {
var d = new Date(today);
d.setDate(d.getDate() - i);
var dateStr = d.toISOString().split('T')[0];
var isSigned = data.indexOf(dateStr) !== -1;
html += '<div class="aksrt-signin-calendar__day' + (isSigned ? ' is-signed' : '') + (i === 0 ? ' is-today' : '') +
'" title="' + dateStr + (isSigned ? ' ✓' : '') + '"><span>' + d.getDate() + '</span></div>';
}
calendar.innerHTML = html + '</div>';
});
var isToday = i === 0;
html += '<div class="aksrt-signin-calendar__day' +
(isSigned ? ' is-signed' : '') +
(isToday ? ' is-today' : '') +
'" title="' + dateStr + (isSigned ? ' ✓' : '') + '">' +
'<span>' + d.getDate() + '</span>' +
'</div>';
}
function bindModalLifecycle() {
if (modalBound) return;
modalBound = true;
document.addEventListener('aksrt:modal:open', function (event) {
var root = event.target && event.target.querySelectorAll ? event.target : document;
window.setTimeout(function () { initSigninCalendar(root); }, 30);
});
html += '</div>';
calendar.innerHTML = html;
}
function init(root, reason) {
initTilt(root);
initScrollAnimations(root);
initRipple(root, reason);
initSticky(root);
initParallax(root);
initFloatLabels(root);
initSigninCalendar(root);
bindModalLifecycle();
/* ============================================================
* 初始化入口 — 先执行一次,随后监听 auto_fun 重扫(各 init 幂等)
* ============================================================ */
function init() {
initTilt();
initScrollAnimations();
initRipple();
initSticky();
initParallax();
initFloatLabels();
initSigninCalendar();
}
window.AksrtFrontend.register('aksrt-enhancements-advanced', init);
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', init);
} else {
init();
}
if (window.jQuery) {
window.jQuery(document).on('auto_fun', init);
}
// 暴露到全局供动态内容使用
window.AksrtEnhancements = {
initTilt: initTilt,
initScrollAnimations: initScrollAnimations,
initRipple: initRipple,
};
})();
+1 -8
View File
@@ -44,11 +44,7 @@
}
}
var globalsBound = false;
function initFollowButtons(root, reason) {
if (globalsBound) return;
globalsBound = true;
// 全局 document 委托只绑定一次(模块顶层执行)。
document.addEventListener('click', function (event) {
var button = event.target.closest('[data-aksrt-follow]');
if (!button) return;
@@ -94,7 +90,4 @@
setLoading(matchingButtons, false);
});
});
}
window.AksrtFrontend.register('aksrt-follow', initFollowButtons);
})();
+4 -11
View File
@@ -80,14 +80,11 @@
isSubmitting: false,
featured: { type: '', data: {} },
init: function (root) {
this.root = root || document;
this.form = this.root.nodeType === 1 && this.root.matches('#aksrt-submit-form')
? this.root : this.root.querySelector('#aksrt-submit-form');
if (!this.form || this.form.dataset.aksrtFrontSubmitBound === '1') {
init: function () {
this.form = document.getElementById('aksrt-submit-form');
if (!this.form) {
return;
}
this.form.dataset.aksrtFrontSubmitBound = '1';
this.bindDirty();
this.bindAutoHeight();
this.bindSubmitButtons();
@@ -314,8 +311,6 @@
},
bindDraftDelete: function () {
if (document.__aksrtFrontSubmitDraftDeleteBound) return;
document.__aksrtFrontSubmitDraftDeleteBound = true;
document.addEventListener('click', function (e) {
var btn = e.target.closest('.aksrt-submit-drafts__delete');
if (!btn) {
@@ -650,7 +645,5 @@
},
};
window.AksrtFrontend.register('aksrt-front-submit', function (root) {
App.init(root);
});
jQuery(document).off('auto_fun.aksrt-front-submit').on('auto_fun.aksrt-front-submit', function () { App.init(); });
})();
-1
View File
@@ -1 +0,0 @@
(function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var t;t="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,t.Grade=e()}})(function(){return function e(t,n,r){function i(o,s){if(!n[o]){if(!t[o]){var u="function"==typeof require&&require;if(!s&&u)return u(o,!0);if(a)return a(o,!0);var c=new Error("Cannot find module '"+o+"'");throw c.code="MODULE_NOT_FOUND",c}var g=n[o]={exports:{}};t[o][0].call(g.exports,function(e){var n=t[o][1][e];return i(n||e)},g,g.exports,e,t,n,r)}return n[o].exports}for(var a="function"==typeof require&&require,o=0;o<r.length;o++)i(r[o]);return i}({1:[function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var i=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),a=["webkit"],o=function(){function e(t,n,i){r(this,e),this.callback=i||null,this.container=t;var a=this.container.querySelector(n||"img");if(this.gradientData=[],a&&this.container){this.canvas=document.createElement("canvas"),this.ctx=this.canvas.getContext("2d"),this.imageData=[];var o=this;o.image=new Image,o.image.crossOrigin="Anonymous",o.image.src=a.getAttribute("data-src")||a.getAttribute("src"),o.image.onload=function(){o.readImage()}}}return i(e,[{key:"readImage",value:function(){this.imageDimensions={width:100,height:100},this.render()}},{key:"getImageData",value:function(){var e=this.ctx.getImageData(0,0,this.imageDimensions.width,this.imageDimensions.height).data;this.imageData=Array.from(e)}},{key:"getChunkedImageData",value:function(){var e=4,t=this.imageData.reduce(function(t,n,r){var i=Math.floor(r/e);return t[i]||(t[i]=[]),t[i].push(n),t},[]),n=t.filter(function(e){var t=e[0],n=e[1],r=e[2],i=Math.max(Math.abs(t-n),Math.abs(t-r),Math.abs(n-r));return i>20});return(!n||n.length<2)&&(n=t.filter(function(e){return e.slice(0,2).every(function(e){return e<245})&&e.slice(0,2).every(function(e){return e>10})})),n}},{key:"getRGBAGradientValues",value:function(e){return e.map(function(e,t){return"rgb("+e.rgba.slice(0,3).join(",")+") "+(0==t?"0%":"75%")}).join(",")}},{key:"getCSSGradientProperty",value:function(e){var t=this.getRGBAGradientValues(e);return a.map(function(e){return"background-image: -"+e+"-linear-gradient(\n 135deg,\n "+t+"\n )"}).concat(["background-image: linear-gradient(\n 135deg,\n "+t+"\n )"]).join(";")}},{key:"getMiddleRGB",value:function(e,t){var n=0,r=(n+1)/2,i=1-r,a=[parseInt(e[0]*r+t[0]*i),parseInt(e[1]*r+t[1]*i),parseInt(e[2]*r+t[2]*i)];return a}},{key:"getSortedValues",value:function(e){var t=Object.keys(e).map(function(t){var n=t,r=t.split("|"),i=(299*r[0]+587*r[1]+114*r[2])/1e3;return{rgba:n.split("|"),occurs:e[t],brightness:i}}).sort(function(e,t){return e.occurs-t.occurs}).reverse().slice(0,10);return t.sort(function(e,t){return e.brightness-t.brightness}).reverse()}},{key:"getTextProperty",value:function(e){var t=this.getMiddleRGB(e[0].rgba.slice(0,3),e[1].rgba.slice(0,3)),n=Math.round((299*parseInt(t[0])+587*parseInt(t[1])+114*parseInt(t[2]))/1e3);return n>125?"color: #000":"color: #fff"}},{key:"getTopValues",value:function(e){var t=this.getSortedValues(e);return[t[0],t[t.length-1]]}},{key:"getUniqValues",value:function(e){return e.reduce(function(e,t){var n=t.join("|");return e[n]?(e[n]=++e[n],e):(e[n]=1,e)},{})}},{key:"renderGradient",value:function(){var e=window.localStorage,t="grade-"+this.image.getAttribute("src"),n=null;if(e&&e.getItem(t)&&(n=JSON.parse(e.getItem(t))),!n||!n[0]){var r=this.getChunkedImageData();n=this.getTopValues(this.getUniqValues(r)),e&&e.setItem(t,JSON.stringify(n))}if(this.callback)return this.gradientData=n,void this.callback([{element:this.container,gradientData:n}]);var i=this.getCSSGradientProperty(n),a=this.getTextProperty(n),o=(this.container.getAttribute("style")||"")+"; "+i+"; "+a;this.container.setAttribute("style",o)}},{key:"render",value:function(){this.canvas.width=this.imageDimensions.width,this.canvas.height=this.imageDimensions.height,this.ctx.drawImage(this.image,0,0,this.imageDimensions.width,this.imageDimensions.height),this.getImageData(),this.renderGradient()}}]),e}();t.exports=function(e,t,n){var r=function(e,t,n){var r=new o(e,t,n),i=r.gradientData;return i.length?{element:e,gradientData:i}:null},i=(NodeList.prototype.isPrototypeOf(e)?Array.from(e).map(function(e){return r(e,t,n)}):[r(e,t,n)]).filter(Boolean);if(i.length)return n(i)}},{}]},{},[1])(1)});
+22 -25
View File
@@ -376,10 +376,8 @@
// 4. Hydrate + rendered event
notifyPostsRendered(panel, options.viewMode);
// 5. Rehydrate dynamic components on new content
if (window.AksrtFrontend && typeof window.AksrtFrontend.rehydrate === 'function') {
window.AksrtFrontend.rehydrate(panel, 'ajax');
}
// 5. legacy 契约:post_ajax.ed 之后调用全局 auto_fun 重扫新内容
if (typeof window.auto_fun === 'function') window.auto_fun();
return;
}
@@ -424,7 +422,6 @@
var tablists = (scope || document).querySelectorAll('[data-aksrt-home-tabs]');
tablists.forEach(function (list, listIndex) {
if (list.dataset.aksrtHomeTabsBound === '1') return;
var stream = list.closest('.aksrt-homepage__stream');
if (!stream) return;
@@ -432,7 +429,6 @@
var panels = Array.from(stream.querySelectorAll('[data-home-tab-panel]'));
if (buttons.length < 2 || !panels.length) return;
list.dataset.aksrtHomeTabsBound = '1';
function getPanel(button) {
var target = button.getAttribute('data-home-tab-target');
@@ -541,14 +537,12 @@
* Sortbar Dropdown Toggle
* ============================================================ */
function initSortbarDropdown(scope) {
(scope || document).querySelectorAll('[data-sort-dropdown-trigger]').forEach(function (trigger) {
if (trigger.dataset.aksrtSortDropdownBound === '1') return;
function initSortbarDropdown() {
document.querySelectorAll('[data-sort-dropdown-trigger]').forEach(function (trigger) {
var wrapper = trigger.closest('.aksrt-homepage__sortbar-dropdown');
if (!wrapper) return;
var menu = wrapper.querySelector('.aksrt-homepage__sortbar-dropdown-menu');
if (!menu) return;
trigger.dataset.aksrtSortDropdownBound = '1';
function close() {
menu.setAttribute('hidden', '');
@@ -603,11 +597,10 @@
* Sortbar AJAX
* ============================================================ */
function initSortbar(scope) {
(scope || document).querySelectorAll('.aksrt-homepage__stream').forEach(function (stream) {
function initSortbar() {
document.querySelectorAll('.aksrt-homepage__stream').forEach(function (stream) {
var sortbar = stream.querySelector('.aksrt-homepage__sortbar');
if (!sortbar || !isSortAjaxEnabled(sortbar) || sortbar.dataset.aksrtSortbarBound === '1') return;
sortbar.dataset.aksrtSortbarBound = '1';
if (!sortbar || !isSortAjaxEnabled(sortbar)) return;
sortbar.addEventListener('click', function (event) {
var link = event.target.closest('.aksrt-homepage__sortbar-link, .aksrt-homepage__sortbar-dropdown-item');
@@ -654,11 +647,10 @@
return isNaN(offset) ? 60 : offset;
}
function initStickyTabs(scope) {
function initStickyTabs() {
if (!isStickyTabsEnabled()) return;
(scope || document).querySelectorAll('.aksrt-homepage__tabs.home-tab-nav-box').forEach(function (tabs) {
if (tabs.dataset.aksrtStickyTabsBound === '1') return;
document.querySelectorAll('.aksrt-homepage__tabs.home-tab-nav-box').forEach(function (tabs) {
var parent = tabs.parentNode;
var sentinel = tabs.previousElementSibling;
var canUseSticky = supportsStickyPosition();
@@ -666,7 +658,6 @@
var observer = null;
if (!parent || tabs.getAttribute('data-sticky-tabs') === 'false') return;
tabs.dataset.aksrtStickyTabsBound = '1';
if (!sentinel || !sentinel.classList.contains('aksrt-homepage__tabs-sentinel')) {
sentinel = document.createElement('div');
@@ -725,13 +716,19 @@
* Init
* ============================================================ */
function init(root) {
var scope = root || document;
initHomeTabs(scope);
initSortbarDropdown(scope);
initSortbar(scope);
initStickyTabs(scope);
function init() {
if (document.body.dataset.aksrtHomeFixedInit === '1') return;
document.body.dataset.aksrtHomeFixedInit = '1';
initHomeTabs();
initSortbarDropdown();
initSortbar();
initStickyTabs();
}
window.AksrtFrontend.register('aksrt-homepage', init);
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', init);
} else {
init();
}
})();
+11 -24
View File
@@ -37,17 +37,9 @@
// ── Auto-resize Textarea ──
function queryAll(root, selector) {
var nodes = Array.prototype.slice.call(root.querySelectorAll(selector));
if (root.nodeType === 1 && root.matches(selector)) nodes.unshift(root);
return nodes;
}
function initAutoResize(root) {
var textareas = queryAll(root, 'textarea[data-aksrt-autoresize]');
function initAutoResize() {
var textareas = document.querySelectorAll('textarea[data-aksrt-autoresize]');
textareas.forEach(function (ta) {
if (ta.dataset.aksrtAutoresizeBound === '1') return;
ta.dataset.aksrtAutoresizeBound = '1';
function resize() {
ta.style.height = 'auto';
ta.style.height = ta.scrollHeight + 'px';
@@ -60,11 +52,9 @@
// ── Character Counter ──
function initCounters(root) {
var fields = queryAll(root, '[data-aksrt-counter]');
function initCounters() {
var fields = document.querySelectorAll('[data-aksrt-counter]');
fields.forEach(function (field) {
if (field.dataset.aksrtCounterBound === '1') return;
field.dataset.aksrtCounterBound = '1';
var max = parseInt(field.getAttribute('data-aksrt-maxlength') || field.getAttribute('maxlength') || '0', 10);
var counter = document.createElement('span');
counter.className = 'aksrt-counter';
@@ -89,11 +79,9 @@
// ── Validation Feedback ──
function initValidation(root) {
var fields = queryAll(root, '[data-aksrt-validate]');
function initValidation() {
var fields = document.querySelectorAll('[data-aksrt-validate]');
fields.forEach(function (field) {
if (field.dataset.aksrtValidateBound === '1') return;
field.dataset.aksrtValidateBound = '1';
var minLen = parseInt(field.getAttribute('data-aksrt-minlength') || field.getAttribute('minlength') || '0', 10);
var maxLen = parseInt(field.getAttribute('data-aksrt-maxlength') || field.getAttribute('maxlength') || '0', 10);
var required = field.hasAttribute('required');
@@ -127,13 +115,12 @@
// ── Main Init ──
function init(root) {
root = root || document;
function init() {
injectStyle();
initAutoResize(root);
initCounters(root);
initValidation(root);
initAutoResize();
initCounters();
initValidation();
}
window.AksrtFrontend.register('aksrt-input-expand', init);
jQuery(document).off('auto_fun.aksrt-input-expand').on('auto_fun.aksrt-input-expand', function () { init(document); });
})();
-34
View File
@@ -1,34 +0,0 @@
/**
* Build lazy-image attributes for dynamically rendered AKSRT markup.
* legacy owns the lazySizes runtime; this file only provides the shared bridge.
*/
(function (window) {
'use strict';
function escapeAttribute(value) {
return String(value == null ? '' : value)
.replace(/&/g, '&amp;')
.replace(/"/g, '&quot;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;');
}
window.aksrtGetLazyImageAttr = function (key, src, className, size) {
var config = window.aksrtData || {};
var scopes = config.lazyScopes || {};
var classes = String(className || '').trim();
var realSrc = escapeAttribute(src);
if (!src || scopes[key] === false) {
return ' class="' + escapeAttribute(classes) + '" src="' + realSrc + '"';
}
var thumbs = config.lazyThumbs || {};
var placeholder = key === 'lazy_avatar'
? (config.lazyAvatar || thumbs.sm || '')
: (thumbs[size || 'default'] || thumbs.default || '');
return ' class="lazyload ' + escapeAttribute(classes) + '" src="' +
escapeAttribute(placeholder) + '" data-src="' + realSrc + '"';
};
})(window);
-870
View File
@@ -1,870 +0,0 @@
//lazySizes
(function (window, factory) {
var lazySizes = factory(window, window.document, Date);
window.lazySizes = lazySizes;
if (typeof module == 'object' && module.exports) {
module.exports = lazySizes;
}
})(typeof window != 'undefined' ? window : {}, function l(window, document, Date) {
// Pass in the windoe Date function also for SSR because the Date class can be lost
'use strict';
/*jshint eqnull:true */
var lazysizes, lazySizesCfg;
(function () {
var prop;
var lazySizesDefaults = {
lazyClass: 'lazyload',
loadedClass: 'lazyloaded',
loadingClass: 'lazyloading',
preloadClass: 'lazypreload',
loadafterClass: 'lazyloadafter',
errorClass: 'lazyerror',
//strictClass: 'lazystrict',
autosizesClass: 'lazyautosizes',
srcAttr: 'data-src',
srcsetAttr: 'data-srcset',
sizesAttr: 'data-sizes',
//preloadAfterLoad: false,
minSize: 40,
customMedia: {},
init: true,
expFactor: 1.5,
hFac: 0.8,
loadMode: 2,
loadHidden: true,
ricTimeout: 0,
throttleDelay: 125,
};
lazySizesCfg = window.lazySizesConfig || window.lazysizesConfig || {};
for (prop in lazySizesDefaults) {
if (!(prop in lazySizesCfg)) {
lazySizesCfg[prop] = lazySizesDefaults[prop];
}
}
})();
if (!document || !document.getElementsByClassName) {
return {
init: function () {},
cfg: lazySizesCfg,
noSupport: true,
};
}
var docElem = document.documentElement;
var supportPicture = window.HTMLPictureElement;
var _addEventListener = 'addEventListener';
var _getAttribute = 'getAttribute';
/**
* Update to bind to window because 'this' becomes null during SSR
* builds.
*/
var addEventListener = window[_addEventListener].bind(window);
var setTimeout = window.setTimeout;
var requestAnimationFrame = window.requestAnimationFrame || setTimeout;
var requestIdleCallback = window.requestIdleCallback;
var regPicture = /^picture$/i;
var loadEvents = ['load', 'error', 'lazyincluded', '_lazyloaded'];
var regClassCache = {};
var forEach = Array.prototype.forEach;
var hasClass = function (ele, cls) {
if (!regClassCache[cls]) {
regClassCache[cls] = new RegExp('(\\s|^)' + cls + '(\\s|$)');
}
return regClassCache[cls].test(ele[_getAttribute]('class') || '') && regClassCache[cls];
};
var addClass = function (ele, cls) {
if (!hasClass(ele, cls)) {
ele.setAttribute('class', (ele[_getAttribute]('class') || '').trim() + ' ' + cls);
}
};
var removeClass = function (ele, cls) {
var reg;
if ((reg = hasClass(ele, cls))) {
ele.setAttribute('class', (ele[_getAttribute]('class') || '').replace(reg, ' '));
}
};
var addRemoveLoadEvents = function (dom, fn, add) {
var action = add ? _addEventListener : 'removeEventListener';
if (add) {
addRemoveLoadEvents(dom, fn);
}
loadEvents.forEach(function (evt) {
dom[action](evt, fn);
});
};
var triggerEvent = function (elem, name, detail, noBubbles, noCancelable) {
var event = document.createEvent('Event');
if (!detail) {
detail = {};
}
detail.instance = lazysizes;
event.initEvent(name, !noBubbles, !noCancelable);
event.detail = detail;
elem.dispatchEvent(event);
return event;
};
var updatePolyfill = function (el, full) {
var polyfill;
if (!supportPicture && (polyfill = window.picturefill || lazySizesCfg.pf)) {
if (full && full.src && !el[_getAttribute]('srcset')) {
el.setAttribute('srcset', full.src);
}
polyfill({ reevaluate: true, elements: [el] });
} else if (full && full.src) {
el.src = full.src;
}
};
var getCSS = function (elem, style) {
return (getComputedStyle(elem, null) || {})[style];
};
var getWidth = function (elem, parent, width) {
width = width || elem.offsetWidth;
while (width < lazySizesCfg.minSize && parent && !elem._lazysizesWidth) {
width = parent.offsetWidth;
parent = parent.parentNode;
}
return width;
};
var rAF = (function () {
var running, waiting;
var firstFns = [];
var secondFns = [];
var fns = firstFns;
var run = function () {
var runFns = fns;
fns = firstFns.length ? secondFns : firstFns;
running = true;
waiting = false;
while (runFns.length) {
runFns.shift()();
}
running = false;
};
var rafBatch = function (fn, queue) {
if (running && !queue) {
fn.apply(this, arguments);
} else {
fns.push(fn);
if (!waiting) {
waiting = true;
(document.hidden ? setTimeout : requestAnimationFrame)(run);
}
}
};
rafBatch._lsFlush = run;
return rafBatch;
})();
var rAFIt = function (fn, simple) {
return simple
? function () {
rAF(fn);
}
: function () {
var that = this;
var args = arguments;
rAF(function () {
fn.apply(that, args);
});
};
};
var throttle = function (fn) {
var running;
var lastTime = 0;
var gDelay = lazySizesCfg.throttleDelay;
var rICTimeout = lazySizesCfg.ricTimeout;
var run = function () {
running = false;
lastTime = Date.now();
fn();
};
var idleCallback =
requestIdleCallback && rICTimeout > 49
? function () {
requestIdleCallback(run, { timeout: rICTimeout });
if (rICTimeout !== lazySizesCfg.ricTimeout) {
rICTimeout = lazySizesCfg.ricTimeout;
}
}
: rAFIt(function () {
setTimeout(run);
}, true);
return function (isPriority) {
var delay;
if ((isPriority = isPriority === true)) {
rICTimeout = 33;
}
if (running) {
return;
}
running = true;
delay = gDelay - (Date.now() - lastTime);
if (delay < 0) {
delay = 0;
}
if (isPriority || delay < 9) {
idleCallback();
} else {
setTimeout(idleCallback, delay);
}
};
};
//based on http://modernjavascript.blogspot.de/2013/08/building-better-debounce.html
var debounce = function (func) {
var timeout, timestamp;
var wait = 99;
var run = function () {
timeout = null;
func();
};
var later = function () {
var last = Date.now() - timestamp;
if (last < wait) {
setTimeout(later, wait - last);
} else {
(requestIdleCallback || run)(run);
}
};
return function () {
timestamp = Date.now();
if (!timeout) {
timeout = setTimeout(later, wait);
}
};
};
var loader = (function () {
var preloadElems, isCompleted, resetPreloadingTimer, loadMode, started;
var eLvW, elvH, eLtop, eLleft, eLright, eLbottom, isBodyHidden;
var regImg = /^img$/i;
var regIframe = /^iframe$/i;
var supportScroll = 'onscroll' in window && !/(gle|ing)bot/.test(navigator.userAgent);
var shrinkExpand = 0;
var currentExpand = 0;
var isLoading = 0;
var lowRuns = -1;
var resetPreloading = function (e) {
isLoading--;
if (!e || isLoading < 0 || !e.target) {
isLoading = 0;
}
};
var isVisible = function (elem) {
if (isBodyHidden == null) {
isBodyHidden = getCSS(document.body, 'visibility') == 'hidden';
}
return isBodyHidden || !(getCSS(elem.parentNode, 'visibility') == 'hidden' && getCSS(elem, 'visibility') == 'hidden');
};
var isNestedVisible = function (elem, elemExpand) {
var outerRect;
var parent = elem;
var visible = isVisible(elem);
eLtop -= elemExpand;
eLbottom += elemExpand;
eLleft -= elemExpand;
eLright += elemExpand;
while (visible && (parent = parent.offsetParent) && parent != document.body && parent != docElem) {
visible = (getCSS(parent, 'opacity') || 1) > 0;
if (visible && getCSS(parent, 'overflow') != 'visible') {
outerRect = parent.getBoundingClientRect();
visible = eLright > outerRect.left && eLleft < outerRect.right && eLbottom > outerRect.top - 1 && eLtop < outerRect.bottom + 1;
}
}
return visible;
};
var checkElements = function () {
var eLlen, i, rect, autoLoadElem, loadedSomething, elemExpand, elemNegativeExpand, elemExpandVal, beforeExpandVal, defaultExpand, preloadExpand, hFac;
var lazyloadElems = lazysizes.elements;
if ((loadMode = lazySizesCfg.loadMode) && isLoading < 8 && (eLlen = lazyloadElems.length)) {
i = 0;
lowRuns++;
for (; i < eLlen; i++) {
if (!lazyloadElems[i] || lazyloadElems[i]._lazyRace) {
continue;
}
if (!supportScroll || (lazysizes.prematureUnveil && lazysizes.prematureUnveil(lazyloadElems[i]))) {
unveilElement(lazyloadElems[i]);
continue;
}
if (!(elemExpandVal = lazyloadElems[i][_getAttribute]('data-expand')) || !(elemExpand = elemExpandVal * 1)) {
elemExpand = currentExpand;
}
if (!defaultExpand) {
defaultExpand = !lazySizesCfg.expand || lazySizesCfg.expand < 1 ? (docElem.clientHeight > 500 && docElem.clientWidth > 500 ? 500 : 370) : lazySizesCfg.expand;
lazysizes._defEx = defaultExpand;
preloadExpand = defaultExpand * lazySizesCfg.expFactor;
hFac = lazySizesCfg.hFac;
isBodyHidden = null;
if (currentExpand < preloadExpand && isLoading < 1 && lowRuns > 2 && loadMode > 2 && !document.hidden) {
currentExpand = preloadExpand;
lowRuns = 0;
} else if (loadMode > 1 && lowRuns > 1 && isLoading < 6) {
currentExpand = defaultExpand;
} else {
currentExpand = shrinkExpand;
}
}
if (beforeExpandVal !== elemExpand) {
eLvW = innerWidth + elemExpand * hFac;
elvH = innerHeight + elemExpand;
elemNegativeExpand = elemExpand * -1;
beforeExpandVal = elemExpand;
}
rect = lazyloadElems[i].getBoundingClientRect();
if ((eLbottom = rect.bottom) >= elemNegativeExpand && (eLtop = rect.top) <= elvH && (eLright = rect.right) >= elemNegativeExpand * hFac && (eLleft = rect.left) <= eLvW && (eLbottom || eLright || eLleft || eLtop) && (lazySizesCfg.loadHidden || isVisible(lazyloadElems[i])) && ((isCompleted && isLoading < 3 && !elemExpandVal && (loadMode < 3 || lowRuns < 4)) || isNestedVisible(lazyloadElems[i], elemExpand))) {
unveilElement(lazyloadElems[i]);
loadedSomething = true;
if (isLoading > 9) {
break;
}
} else if (!loadedSomething && isCompleted && !autoLoadElem && isLoading < 4 && lowRuns < 4 && loadMode > 2 && (preloadElems[0] || lazySizesCfg.preloadAfterLoad) && (preloadElems[0] || (!elemExpandVal && (eLbottom || eLright || eLleft || eLtop || lazyloadElems[i][_getAttribute](lazySizesCfg.sizesAttr) != 'auto')))) {
autoLoadElem = preloadElems[0] || lazyloadElems[i];
}
}
if (autoLoadElem && !loadedSomething) {
unveilElement(autoLoadElem);
}
}
};
var throttledCheckElements = throttle(checkElements);
var switchLoadingClass = function (e) {
var elem = e.target;
if (elem._lazyCache) {
delete elem._lazyCache;
return;
}
resetPreloading(e);
addClass(elem, lazySizesCfg.loadedClass);
removeClass(elem, lazySizesCfg.loadingClass);
addRemoveLoadEvents(elem, rafSwitchLoadingClass);
triggerEvent(elem, 'lazyloaded');
//添加loadafterClass,防止后期二次触发动画
setTimeout(function () {
addClass(elem, lazySizesCfg.loadafterClass);
}, 700);
};
var rafedSwitchLoadingClass = rAFIt(switchLoadingClass);
var rafSwitchLoadingClass = function (e) {
rafedSwitchLoadingClass({ target: e.target });
};
var changeIframeSrc = function (elem, src) {
try {
elem.contentWindow.location.replace(src);
} catch (e) {
elem.src = src;
}
};
var handleSources = function (source) {
var customMedia;
var sourceSrcset = source[_getAttribute](lazySizesCfg.srcsetAttr);
if ((customMedia = lazySizesCfg.customMedia[source[_getAttribute]('data-media') || source[_getAttribute]('media')])) {
source.setAttribute('media', customMedia);
}
if (sourceSrcset) {
source.setAttribute('srcset', sourceSrcset);
}
};
var lazyUnveil = rAFIt(function (elem, detail, isAuto, sizes, isImg) {
var src, srcset, parent, isPicture, event, firesLoad;
if (!(event = triggerEvent(elem, 'lazybeforeunveil', detail)).defaultPrevented) {
if (sizes) {
if (isAuto) {
addClass(elem, lazySizesCfg.autosizesClass);
} else {
elem.setAttribute('sizes', sizes);
}
}
srcset = elem[_getAttribute](lazySizesCfg.srcsetAttr);
src = elem[_getAttribute](lazySizesCfg.srcAttr);
if (isImg) {
parent = elem.parentNode;
isPicture = parent && regPicture.test(parent.nodeName || '');
}
firesLoad = detail.firesLoad || ('src' in elem && (srcset || src || isPicture));
event = { target: elem };
addClass(elem, lazySizesCfg.loadingClass);
if (firesLoad) {
clearTimeout(resetPreloadingTimer);
resetPreloadingTimer = setTimeout(resetPreloading, 2500);
addRemoveLoadEvents(elem, rafSwitchLoadingClass, true);
}
if (isPicture) {
forEach.call(parent.getElementsByTagName('source'), handleSources);
}
if (srcset) {
elem.setAttribute('srcset', srcset);
} else if (src && !isPicture) {
if (regIframe.test(elem.nodeName)) {
changeIframeSrc(elem, src);
} else {
elem.src = src;
}
}
if (isImg && (srcset || isPicture)) {
updatePolyfill(elem, { src: src });
}
}
if (elem._lazyRace) {
delete elem._lazyRace;
}
removeClass(elem, lazySizesCfg.lazyClass);
rAF(function () {
// Part of this can be removed as soon as this fix is older: https://bugs.chromium.org/p/chromium/issues/detail?id=7731 (2015)
var isLoaded = elem.complete && elem.naturalWidth > 1;
if (!firesLoad || isLoaded) {
if (isLoaded) {
addClass(elem, 'ls-is-cached');
}
switchLoadingClass(event);
elem._lazyCache = true;
setTimeout(function () {
if ('_lazyCache' in elem) {
delete elem._lazyCache;
}
}, 9);
}
if (elem.loading == 'lazy') {
isLoading--;
}
}, true);
});
var unveilElement = function (elem) {
if (elem._lazyRace) {
return;
}
var detail;
var isImg = regImg.test(elem.nodeName);
//allow using sizes="auto", but don't use. it's invalid. Use data-sizes="auto" or a valid value for sizes instead (i.e.: sizes="80vw")
var sizes = isImg && (elem[_getAttribute](lazySizesCfg.sizesAttr) || elem[_getAttribute]('sizes'));
var isAuto = sizes == 'auto';
if ((isAuto || !isCompleted) && isImg && (elem[_getAttribute]('src') || elem.srcset) && !elem.complete && !hasClass(elem, lazySizesCfg.errorClass) && hasClass(elem, lazySizesCfg.lazyClass)) {
return;
}
detail = triggerEvent(elem, 'lazyunveilread').detail;
if (isAuto) {
autoSizer.updateElem(elem, true, elem.offsetWidth);
}
elem._lazyRace = true;
isLoading++;
lazyUnveil(elem, detail, isAuto, sizes, isImg);
};
var afterScroll = debounce(function () {
lazySizesCfg.loadMode = 3;
throttledCheckElements();
});
var altLoadmodeScrollListner = function () {
if (lazySizesCfg.loadMode == 3) {
lazySizesCfg.loadMode = 2;
}
afterScroll();
};
var onload = function () {
if (isCompleted) {
return;
}
if (Date.now() - started < 999) {
setTimeout(onload, 999);
return;
}
isCompleted = true;
lazySizesCfg.loadMode = 3;
throttledCheckElements();
addEventListener('scroll', altLoadmodeScrollListner, true);
};
return {
_: function () {
started = Date.now();
lazysizes.elements = document.getElementsByClassName(lazySizesCfg.lazyClass);
preloadElems = document.getElementsByClassName(lazySizesCfg.lazyClass + ' ' + lazySizesCfg.preloadClass);
addEventListener('scroll', throttledCheckElements, true);
addEventListener('resize', throttledCheckElements, true);
addEventListener('pageshow', function (e) {
if (e.persisted) {
var loadingElements = document.querySelectorAll('.' + lazySizesCfg.loadingClass);
if (loadingElements.length && loadingElements.forEach) {
requestAnimationFrame(function () {
loadingElements.forEach(function (img) {
if (img.complete) {
unveilElement(img);
}
});
});
}
}
});
if (window.MutationObserver) {
new MutationObserver(throttledCheckElements).observe(docElem, { childList: true, subtree: true, attributes: true });
} else {
docElem[_addEventListener]('DOMNodeInserted', throttledCheckElements, true);
docElem[_addEventListener]('DOMAttrModified', throttledCheckElements, true);
setInterval(throttledCheckElements, 999);
}
addEventListener('hashchange', throttledCheckElements, true);
//, 'fullscreenchange'
['focus', 'mouseover', 'click', 'load', 'transitionend', 'animationend'].forEach(function (name) {
document[_addEventListener](name, throttledCheckElements, true);
});
if (/d$|^c/.test(document.readyState)) {
onload();
} else {
addEventListener('load', onload);
document[_addEventListener]('DOMContentLoaded', throttledCheckElements);
setTimeout(onload, 20000);
}
if (lazysizes.elements.length) {
checkElements();
rAF._lsFlush();
} else {
throttledCheckElements();
}
},
checkElems: throttledCheckElements,
unveil: unveilElement,
_aLSL: altLoadmodeScrollListner,
};
})();
var autoSizer = (function () {
var autosizesElems;
var sizeElement = rAFIt(function (elem, parent, event, width) {
var sources, i, len;
elem._lazysizesWidth = width;
width += 'px';
elem.setAttribute('sizes', width);
if (regPicture.test(parent.nodeName || '')) {
sources = parent.getElementsByTagName('source');
for (i = 0, len = sources.length; i < len; i++) {
sources[i].setAttribute('sizes', width);
}
}
if (!event.detail.dataAttr) {
updatePolyfill(elem, event.detail);
}
});
var getSizeElement = function (elem, dataAttr, width) {
var event;
var parent = elem.parentNode;
if (parent) {
width = getWidth(elem, parent, width);
event = triggerEvent(elem, 'lazybeforesizes', { width: width, dataAttr: !!dataAttr });
if (!event.defaultPrevented) {
width = event.detail.width;
if (width && width !== elem._lazysizesWidth) {
sizeElement(elem, parent, event, width);
}
}
}
};
var updateElementsSizes = function () {
var i;
var len = autosizesElems.length;
if (len) {
i = 0;
for (; i < len; i++) {
getSizeElement(autosizesElems[i]);
}
}
};
var debouncedUpdateElementsSizes = debounce(updateElementsSizes);
return {
_: function () {
autosizesElems = document.getElementsByClassName(lazySizesCfg.autosizesClass);
addEventListener('resize', debouncedUpdateElementsSizes);
},
checkElems: debouncedUpdateElementsSizes,
updateElem: getSizeElement,
};
})();
var init = function () {
if (!init.i && document.getElementsByClassName) {
init.i = true;
autoSizer._();
loader._();
}
};
setTimeout(function () {
if (lazySizesCfg.init) {
init();
}
});
lazysizes = {
cfg: lazySizesCfg,
autoSizer: autoSizer,
loader: loader,
init: init,
uP: updatePolyfill,
aC: addClass,
rC: removeClass,
hC: hasClass,
fire: triggerEvent,
gW: getWidth,
rAF: rAF,
};
return lazysizes;
});
/**
* AKSRT integration for legacy's lazySizes runtime.
* Normalizes dynamic markup without creating a second media loader.
*/
(function (window, document) {
'use strict';
function normalize(root) {
var scope = root && root.querySelectorAll ? root : document;
scope.querySelectorAll('img,iframe,video,[data-bg],[lazyload-action]').forEach(function (element) {
var hasLazySource = element.hasAttribute('data-src') || element.hasAttribute('data-srcset');
if (element.tagName === 'VIDEO' && element.querySelector('source[data-src],source[data-srcset]')) {
hasLazySource = true;
}
if ((hasLazySource || element.hasAttribute('data-bg') || element.hasAttribute('lazyload-action')) &&
!element.classList.contains('lazyloaded') && !element.classList.contains('lazyloading')) {
element.classList.add('lazyload');
}
});
}
function escapeAttribute(value) {
return String(value == null ? '' : value)
.replace(/&/g, '&amp;')
.replace(/"/g, '&quot;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;');
}
window.aksrtGetLazyImageAttr = function (key, src, className, size) {
var config = window.aksrtData || {};
var scopes = config.lazyScopes || {};
var classes = String(className || '').trim();
var realSrc = escapeAttribute(src);
if (!src || scopes[key] === false) {
return ' class="' + escapeAttribute(classes) + '" src="' + realSrc + '"';
}
var thumbs = config.lazyThumbs || {};
var placeholder = key === 'lazy_avatar'
? (config.lazyAvatar || thumbs.sm || '')
: (thumbs[size || 'default'] || thumbs.default || '');
return ' class="lazyload ' + escapeAttribute(classes) + '" src="' + escapeAttribute(placeholder) + '" data-src="' + realSrc + '"';
};
document.addEventListener('lazybeforeunveil', function (event) {
var element = event.target;
var action = element.getAttribute('lazyload-action');
window.setTimeout(function () {
if (action === 'ias') {
if (element.hasAttribute('remote-box')) {
element.click();
} else {
var trigger = element.matches('.ajax-next,.ias-btn')
? element
: element.querySelector('.ajax-next,.ias-btn');
if (trigger) {
trigger.setAttribute('no-scroll', 'true');
trigger.dataset.lazyAuto = '1';
trigger.click();
}
}
} else if (action === 'animated') {
var animation = element.getAttribute('data-animated');
if (animation) {
element.classList.add('animated', animation);
element.style.visibility = '';
}
}
}, 200);
var background = element.getAttribute('data-bg');
if (background) {
element.style.backgroundImage = 'url("' + background.replace(/"/g, '\\"') + '")';
}
if (element.tagName === 'VIDEO') {
var changed = false;
var poster = element.getAttribute('data-poster');
if (poster) {
element.setAttribute('poster', poster);
}
element.querySelectorAll('source[data-src],source[data-srcset]').forEach(function (source) {
var src = source.getAttribute('data-src');
var srcset = source.getAttribute('data-srcset');
if (src) {
source.setAttribute('src', src);
changed = true;
}
if (srcset) {
source.setAttribute('srcset', srcset);
changed = true;
}
});
if (changed) {
event.detail.firesLoad = true;
element.load();
}
}
});
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', function () { normalize(document); });
} else {
normalize(document);
}
new MutationObserver(function (records) {
records.forEach(function (record) {
record.addedNodes.forEach(function (node) {
if (node.nodeType !== 1) return;
normalize(node);
});
});
}).observe(document.documentElement, { childList: true, subtree: true });
window.aksrtNormalizeLazyMedia = normalize;
})(window, document);
+2 -8
View File
@@ -6,11 +6,8 @@
(function () {
'use strict';
function init(scope) {
scope = scope || document;
var root = scope.nodeType === 1 && scope.matches('[data-message-center]') ? scope : scope.querySelector('[data-message-center]');
if (!root || root.dataset.aksrtMessagesBound === '1') return;
root.dataset.aksrtMessagesBound = '1';
var root = document.querySelector('[data-message-center]');
if (!root) return;
var nonce = typeof aksrtData !== 'undefined' ? aksrtData.nonce : '';
var ajaxUrl = typeof aksrtData !== 'undefined' ? aksrtData.ajaxUrl : '/wp-admin/admin-ajax.php';
@@ -228,7 +225,4 @@
if (result.success && result.data) updateHeaderBadge(result.data.unread);
}).catch(function () {});
}, pollInterval);
}
window.AksrtFrontend.register('aksrt-messages', init);
})();
+3 -6
View File
@@ -307,11 +307,8 @@
};
// 自动初始化
function autoInit(root) {
var containers = [];
if (root && root.nodeType === 1 && root.matches('[data-aksrt-mini-upload]')) containers.push(root);
Array.prototype.push.apply(containers, (root || document).querySelectorAll('[data-aksrt-mini-upload]'));
containers.forEach(function (el) {
function autoInit() {
document.querySelectorAll('[data-aksrt-mini-upload]').forEach(function (el) {
if (el.dataset.miniUploadInit) return;
el.dataset.miniUploadInit = '1';
@@ -324,7 +321,7 @@
});
}
window.AksrtFrontend.register('aksrt-mini-upload', autoInit);
jQuery(document).off('auto_fun.aksrt-mini-upload').on('auto_fun.aksrt-mini-upload', autoInit);
// 暴露到全局
window.AksrtMiniUpload = MiniUpload;
+9 -9
View File
@@ -15,9 +15,9 @@
}
function notyf(message, type, time, id) {
var $body = $(document.body);
var $body = jQuery(document.body);
if (!$('.notyn').length) {
if (!jQuery('.notyn').length) {
$body.append('<div class="notyn"></div>');
}
@@ -30,19 +30,19 @@
time = time < 100 ? time * 1000 : time;
var idAttribute = id ? ' id="' + id + '"' : '';
var $notification = $('<div class="noty1"' + idAttribute + '><div class="notyf ' + type + '">' + message + '</div></div>');
var $notification = jQuery('<div class="noty1"' + idAttribute + '><div class="notyf ' + type + '">' + message + '</div></div>');
var shouldClose = !id;
if (id && $('#' + id).length) {
$('#' + id)
if (id && jQuery('#' + id).length) {
jQuery('#' + id)
.find('.notyf')
.removeClass()
.addClass('notyf ' + type)
.html(message);
$notification = $('#' + id);
$notification = jQuery('#' + id);
shouldClose = true;
} else {
$('.notyn').append($notification);
jQuery('.notyn').append($notification);
}
if (shouldClose) {
@@ -52,8 +52,8 @@
}
}
$(document.body).on('click', '.noty1', function () {
closeNotyf($(this));
jQuery(document.body).on('click', '.noty1', function () {
closeNotyf(jQuery(this));
});
window.notyf = notyf;
+1 -3
View File
@@ -470,7 +470,5 @@
}
window.AKSRTOrderCenter = { init: init, destroy: destroy };
if (window.AksrtFrontend && typeof window.AksrtFrontend.register === "function") {
window.AksrtFrontend.register("aksrt-order-center", init);
}
jQuery(document).off("auto_fun.aksrt-order-center").on("auto_fun.aksrt-order-center", function () { init(document); });
}());
+5 -7
View File
@@ -21,7 +21,6 @@
*/
function PageEdit(options) {
this.options = Object.assign({
form: null,
formSelector: 'form[data-aksrt-edit]',
titleSelector: 'input[name="title"], input[name="topic_title"]',
contentSelector: 'textarea[name="content"], textarea[name="topic_content"]',
@@ -30,7 +29,7 @@
draftKey: '',
}, options || {});
this.form = this.options.form || document.querySelector(this.options.formSelector);
this.form = document.querySelector(this.options.formSelector);
if (!this.form) return;
this.autoSaveTimer = null;
@@ -190,15 +189,14 @@
};
// 自动初始化
function autoInit(root) {
var form = root && root.nodeType === 1 && root.matches('form[data-aksrt-edit]')
? root : (root || document).querySelector('form[data-aksrt-edit]');
function autoInit() {
var form = document.querySelector('form[data-aksrt-edit]');
if (form) {
new PageEdit({ form: form });
new PageEdit();
}
}
window.AksrtFrontend.register('aksrt-page-edit', autoInit);
jQuery(document).off('auto_fun.aksrt-page-edit').on('auto_fun.aksrt-page-edit', autoInit);
window.AksrtPageEdit = PageEdit;
})();
+16 -24
View File
@@ -28,10 +28,7 @@
searchQuery: '',
ajaxInFlight: null,
init: function (root) {
this.root = root || document;
if (this.root.__aksrtPageNavInitialized) return;
this.root.__aksrtPageNavInitialized = true;
init: function () {
this.initTocHighlight();
this.initSmoothScroll();
this.initDocSearch();
@@ -43,8 +40,7 @@
* TOC 高亮(文档阅读页)
* ============================================================ */
initTocHighlight: function () {
var toc = this.root.querySelector('.aksrt-doc-toc');
if (this.root.nodeType === 1 && this.root.matches('.aksrt-doc-toc')) toc = this.root;
var toc = document.querySelector('.aksrt-doc-toc');
if (!toc) return;
this.tocItems = Array.from(toc.querySelectorAll('.aksrt-doc-toc__item a'));
@@ -96,9 +92,7 @@
* 平滑滚动
* ============================================================ */
initSmoothScroll: function () {
if (this.root.__aksrtPageNavSmoothBound) return;
this.root.__aksrtPageNavSmoothBound = true;
this.root.addEventListener('click', function (e) {
document.addEventListener('click', function (e) {
var link = e.target.closest('a[href^="#"]');
if (!link) return;
@@ -119,11 +113,11 @@
* 文档搜索(AJAX 接管)
* ============================================================ */
initDocSearch: function () {
var searchInput = this.root.querySelector('.aksrt-doc-search__input');
var searchInput = document.querySelector('.aksrt-doc-search__input');
if (!searchInput) return;
var resultsContainer = this.root.querySelector('.aksrt-doc-search__results');
var takeover = this.root.querySelector('.aksrt-doc-takeover');
var resultsContainer = document.querySelector('.aksrt-doc-search__results');
var takeover = document.querySelector('.aksrt-doc-takeover');
var self = this;
var debounceTimer = null;
@@ -212,7 +206,7 @@
resultsContainer.innerHTML = '';
}
// 显示所有卡片
var cards = this.root.querySelectorAll('.aksrt-doc-index-card');
var cards = document.querySelectorAll('.aksrt-doc-index-card');
cards.forEach(function (card) { card.style.display = ''; });
},
@@ -237,7 +231,7 @@
* 分类切换 — AJAX 加载 + 分页
* ============================================================ */
initCategoryChips: function () {
var toolbar = this.root.querySelector('.aksrt-doc-toolbar');
var toolbar = document.querySelector('.aksrt-doc-toolbar');
if (!toolbar) return;
var chips = toolbar.querySelectorAll('.aksrt-doc-toolbar__chip[data-cat-id]');
@@ -266,7 +260,7 @@
}
var self = this;
var grid = this.root.querySelector('.aksrt-doc-grid');
var grid = document.querySelector('.aksrt-doc-grid');
if (!grid) return;
// 显示加载状态
@@ -311,7 +305,7 @@
},
updateMetaCount: function (total) {
var meta = this.root.querySelector('.aksrt-doc-toolbar__meta');
var meta = document.querySelector('.aksrt-doc-toolbar__meta');
if (meta) {
meta.textContent = total + ' 篇文档';
}
@@ -322,7 +316,7 @@
* ============================================================ */
initPagination: function () {
var self = this;
var paginationContainer = this.root.querySelector('.aksrt-doc-pagination');
var paginationContainer = document.querySelector('.aksrt-doc-pagination');
if (!paginationContainer) return;
paginationContainer.addEventListener('click', function (e) {
@@ -337,7 +331,7 @@
self.loadCategoryDocs(self.activeCategory, page);
// 滚动到顶部
var grid = self.root.querySelector('.aksrt-doc-grid');
var grid = document.querySelector('.aksrt-doc-grid');
if (grid) {
grid.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
@@ -348,7 +342,7 @@
this.totalPages = totalPages;
this.currentPage = currentPage;
var container = this.root.querySelector('.aksrt-doc-pagination');
var container = document.querySelector('.aksrt-doc-pagination');
if (!container) return;
if (totalPages <= 1) {
@@ -400,7 +394,7 @@
},
filterDocItems: function (query) {
var cards = this.root.querySelectorAll('.aksrt-doc-index-card');
var cards = document.querySelectorAll('.aksrt-doc-index-card');
if (cards.length > 0) {
cards.forEach(function (card) {
var title = card.querySelector('.aksrt-doc-index-card__title');
@@ -414,7 +408,7 @@
});
}
var sidebarItems = this.root.querySelectorAll('.aksrt-doc-sidebar__item');
var sidebarItems = document.querySelectorAll('.aksrt-doc-sidebar__item');
if (sidebarItems.length > 0) {
sidebarItems.forEach(function (item) {
var link = item.querySelector('.aksrt-doc-sidebar__link');
@@ -452,7 +446,5 @@
}
};
window.AksrtFrontend.register('aksrt-page-navs', function (root) {
PAGE_NAVS.init(root);
});
jQuery(document).off('auto_fun.aksrt-page-navs').on('auto_fun.aksrt-page-navs', function () { PAGE_NAVS.init(); });
})();
+9 -22
View File
@@ -10,15 +10,9 @@
(function () {
'use strict';
function queryAll(root, selector) {
var nodes = Array.prototype.slice.call((root || document).querySelectorAll(selector));
if (root && root.nodeType === 1 && root.matches(selector)) nodes.unshift(root);
return nodes;
}
function initContentExpand(root) {
function initContentExpand() {
// legacy-style: inject .read-more inside .limit-height and expand on click.
queryAll(root, '.wp-posts-content.limit-height, .limit-height[data-nav]').forEach(function (content) {
document.querySelectorAll('.wp-posts-content.limit-height, .limit-height[data-nav]').forEach(function (content) {
if (content.dataset.aksrtExpandBound === '1') return;
content.dataset.aksrtExpandBound = '1';
@@ -64,13 +58,8 @@
wrap.remove();
});
});
}
var expandDelegateBound = false;
function bindExpandDelegate() {
if (expandDelegateBound) return;
expandDelegateBound = true;
// Compatibility: old external expand buttons.
document.addEventListener('click', function (event) {
var open = event.target.closest && event.target.closest('.read-more-open');
if (!open) return;
@@ -84,8 +73,8 @@
});
}
function initFlashQueryCleanup(root) {
queryAll(root, '[data-aksrt-flash-query]').forEach(function (node) {
function initFlashQueryCleanup() {
document.querySelectorAll('[data-aksrt-flash-query]').forEach(function (node) {
var queryKey = node.getAttribute('data-aksrt-flash-query');
if (!queryKey || !window.history || typeof window.history.replaceState !== 'function') return;
@@ -97,12 +86,10 @@
});
}
function init(root) {
root = root || document;
bindExpandDelegate();
initContentExpand(root);
initFlashQueryCleanup(root);
function init() {
initContentExpand();
initFlashQueryCleanup();
}
window.AksrtFrontend.register('aksrt-page-template', init);
jQuery(document).off('auto_fun.aksrt-page-template').on('auto_fun.aksrt-page-template', function () { init(document); });
})();
+1 -1
View File
@@ -567,5 +567,5 @@
document.addEventListener("click", onDocClick, true);
}
window.AksrtFrontend.register("aksrt-pay-vip", bindOnce);
jQuery(document).off("auto_fun.aksrt-pay-vip").on("auto_fun.aksrt-pay-vip", bindOnce);
})();
+3 -7
View File
@@ -271,11 +271,7 @@
return Promise.resolve({ mode: 'window' });
}
var genericShareBound = false;
function bindGenericShareButtons() {
if (genericShareBound) return;
genericShareBound = true;
document.addEventListener('click', function (event) {
var node = event.target.closest('[data-share-platform]');
if (!node || node.closest('#share-dropdown')) return;
@@ -299,11 +295,11 @@
}
function init() {
if (document.documentElement.dataset.aksrtPostShareInitialized === '1') return;
document.documentElement.dataset.aksrtPostShareInitialized = '1';
initShareDropdown();
bindGenericShareButtons();
}
window.AksrtFrontend.register('aksrt-post-share', function () {
init();
});
jQuery(document).off('auto_fun.aksrt-post-share').on('auto_fun.aksrt-post-share', function () { init(document); });
})();
+12 -16
View File
@@ -37,11 +37,7 @@
PosterShare.prototype.init = function () {
var self = this;
var scope = this.options.root || document;
var triggers = [];
if (scope.nodeType === 1 && scope.matches(this.options.triggerSelector)) triggers.push(scope);
Array.prototype.push.apply(triggers, scope.querySelectorAll(this.options.triggerSelector));
triggers.forEach(function (btn) {
document.querySelectorAll(this.options.triggerSelector).forEach(function (btn) {
btn.addEventListener('click', function (e) {
e.preventDefault();
@@ -364,21 +360,21 @@
};
// 自动初始化
function autoInit(root) {
var triggers = [];
if (root && root.nodeType === 1 && root.matches('[data-aksrt-poster]')) triggers.push(root);
Array.prototype.push.apply(triggers, (root || document).querySelectorAll('[data-aksrt-poster]'));
if (!triggers.length) return;
var pending = triggers.filter(function (el) { return el.dataset.posterInit !== '1'; });
if (!pending.length) return;
var instance = new PosterShare({ root: root || document, triggerSelector: '[data-aksrt-poster]' });
pending.forEach(function (el) {
function autoInit() {
document.querySelectorAll('[data-aksrt-poster]').forEach(function (el) {
if (el.dataset.posterInit) return;
el.dataset.posterInit = '1';
el._aksrtPosterShare = instance;
var config = {};
try {
config = JSON.parse(el.dataset.aksrtPoster || '{}');
} catch (e) {}
new PosterShare({ triggerSelector: '[data-aksrt-poster]' });
});
}
window.AksrtFrontend.register('aksrt-poster-share', autoInit);
jQuery(document).off('auto_fun.aksrt-poster-share').on('auto_fun.aksrt-poster-share', autoInit);
/**
* Generate a poster directly from a unified share payload, without binding
+19 -26
View File
@@ -8,14 +8,11 @@
'use strict';
function qs(sel, root) {
if (root && root.nodeType === 1 && root.matches(sel)) return root;
return (root || document).querySelector(sel);
}
function qsa(sel, root) {
var nodes = Array.prototype.slice.call((root || document).querySelectorAll(sel));
if (root && root.nodeType === 1 && root.matches(sel)) nodes.unshift(root);
return nodes;
return Array.prototype.slice.call((root || document).querySelectorAll(sel));
}
function ajaxUrl() {
@@ -24,13 +21,10 @@
return '/wp-admin/admin-ajax.php';
}
function initModal(root) {
var modal = qs('#post-navs-sz', root);
function initModal() {
var modal = qs('#post-navs-sz');
if (!modal) return;
if (modal.dataset.aksrtPostsNavModalBound === '1') return;
modal.dataset.aksrtPostsNavModalBound = '1';
function openModal(e) {
if (e) e.preventDefault();
modal.classList.add('is-open', 'show');
@@ -43,11 +37,11 @@
modal.setAttribute('aria-hidden', 'true');
}
qsa('[data-toggle="modal"][data-target="#post-navs-sz"], a[href="#post-navs-sz"]', root).forEach(function (el) {
qsa('[data-toggle="modal"][data-target="#post-navs-sz"], a[href="#post-navs-sz"]').forEach(function (el) {
el.addEventListener('click', openModal);
});
// Title [设置] uses data-target.
qsa('[data-target="#post-navs-sz"]', root).forEach(function (el) {
qsa('[data-target="#post-navs-sz"]').forEach(function (el) {
el.addEventListener('click', openModal);
});
qsa('[data-dismiss="modal"]', modal).forEach(function (btn) {
@@ -61,9 +55,9 @@
});
}
function initDragSort(root) {
var left = qs('#cat-sortable', root);
var right = qs('#cat-sortable-ok', root);
function initDragSort() {
var left = qs('#cat-sortable');
var right = qs('#cat-sortable-ok');
if (!left || !right) return;
var dragEl = null;
@@ -129,8 +123,8 @@
}
}
function initSave(root) {
var form = qs('#aksrt-posts-navs-settings', root);
function initSave() {
var form = qs('#aksrt-posts-navs-settings');
if (!form) return;
form.addEventListener('submit', function (e) {
@@ -185,9 +179,9 @@
* Build simple TOC into .posts-nav-box if section-navs hasn't already.
* Uses category h2 headings inside .posts-navs.
*/
function initFallbackToc(scope) {
var box = qs('.posts-nav-box', scope);
var root = qs('.posts-navs[data-nav]', scope);
function initFallbackToc() {
var box = qs('.posts-nav-box');
var root = qs('.posts-navs[data-nav]');
if (!box || !root) return;
if (box.querySelector('.posts-nav-lists, .aksrt-section-nav, .toc-list')) return;
@@ -236,14 +230,13 @@
highlight();
}
function init(root) {
root = root || document;
initModal(root);
initDragSort(root);
initSave(root);
function init() {
initModal();
initDragSort();
initSave();
// Defer so section-navs.js can own TOC first.
window.setTimeout(function () { initFallbackToc(root); }, 50);
window.setTimeout(initFallbackToc, 50);
}
window.AksrtFrontend.register('aksrt-posts-navs-page', init);
jQuery(document).off('auto_fun.aksrt-posts-navs-page').on('auto_fun.aksrt-posts-navs-page', function () { init(document); });
})();
+1 -3
View File
@@ -218,7 +218,5 @@
loadEnlighterJS(initEnlighter);
}
window.AksrtFrontend.register('aksrt-precode', function () {
init();
});
jQuery(document).off('auto_fun.aksrt-precode').on('auto_fun.aksrt-precode', function () { init(document); });
})();
-109
View File
@@ -1,109 +0,0 @@
/**
* AKSRT Rehydrate System
*
* Centralized component initialization and re-initialization system.
* Components register their init functions, and rehydrate() is called
* to initialize or re-initialize them on a given root element.
*
* Usage:
* AksrtFrontend.register('name', initFn); // Register a component
* AksrtFrontend.boot(document); // One-time initial page load
* AksrtFrontend.rehydrate(root, 'ajax'); // Initialize dynamic content
*
* @package AKSRT
* @since 5.0.0
*/
(function () {
'use strict';
var _registry = [];
var _booted = false;
var _bootRoot = null;
function invoke(entry, root, reason) {
try {
entry.initFn(root, reason);
} catch (err) {
console.error('[AKSRT Rehydrate] Error initializing "' + entry.name + '":', err);
}
}
function dispatch(root, reason, eventName) {
try {
root.dispatchEvent(new CustomEvent(eventName, {
bubbles: true,
detail: { reason: reason }
}));
} catch (e) { /* IE fallback */ }
}
window.AksrtFrontend = {
/**
* Register a component's init function.
*
* @param {string} name Unique component name
* @param {Function} initFn Function(root, reason) - root defaults to document
*/
register: function (name, initFn) {
if (typeof name !== 'string' || typeof initFn !== 'function') return;
// Prevent duplicate registrations
for (var i = 0; i < _registry.length; i++) {
if (_registry[i].name === name) {
_registry[i].initFn = initFn;
if (_booted) invoke(_registry[i], _bootRoot || document, 'init');
return;
}
}
var entry = { name: name, initFn: initFn };
_registry.push(entry);
if (_booted) invoke(entry, _bootRoot || document, 'init');
},
/**
* Run the one-time initial page boot.
*
* @param {Element|Document} root The document root to initialize
*/
boot: function (root) {
if (_booted) return;
_booted = true;
_bootRoot = root || document;
this.rehydrate(_bootRoot, 'init');
dispatch(_bootRoot, 'init', 'aksrt:ready');
},
/**
* Initialize or re-initialize all registered components on a root element.
*
* @param {Element|Document} root The root DOM element to search within
* @param {string} reason Why rehydrate is called:
* 'init' = initial page load
* 'ajax' = after AJAX content injection
* 'modal' = after modal content loads
* Custom string for other triggers
*/
rehydrate: function (root, reason) {
root = root || document;
reason = reason || 'init';
for (var i = 0; i < _registry.length; i++) {
invoke(_registry[i], root, reason);
}
dispatch(root, reason, 'aksrt:rehydrated');
},
/**
* Get the list of registered component names (for debugging).
*/
getRegistered: function () {
return _registry.map(function (r) { return r.name; });
},
isBooted: function () {
return _booted;
}
};
})();
+1 -3
View File
@@ -159,7 +159,5 @@
});
}
if (window.AksrtFrontend && typeof window.AksrtFrontend.register === 'function') {
window.AksrtFrontend.register('aksrt-report', initReportButtons);
}
jQuery(document).off('auto_fun.aksrt-report').on('auto_fun.aksrt-report', initReportButtons);
})();
-116
View File
@@ -1,116 +0,0 @@
/**
* AKSRT Revenue Center Frontend
*
* @package AKSRT
*/
(function () {
'use strict';
var page = document.querySelector('[data-aksrt-revenue-page]');
var data = window.aksrtData || {};
if (!page || !data) return;
var rest = data.restUrl || data.apiUrl || ((data.siteUrl || '').replace(/\/$/, '') + '/wp-json/aksrt/v1');
if (!rest) return;
if (window.location.protocol === 'https:' && rest.substring(0, 5) === 'http:') {
rest = 'https:' + rest.substring(5);
}
rest = rest.replace(/\/?$/, '');
var form = page.querySelector('[data-aksrt-withdraw-form]');
var message = page.querySelector('[data-aksrt-withdraw-msg]');
var balance = page.querySelector('[data-aksrt-revenue-balance]');
var list = page.querySelector('[data-aksrt-withdraw-list]');
if (!form) return;
function setMessage(text, error) {
if (!message) return;
message.hidden = false;
message.textContent = text;
message.classList.toggle('is-error', !!error);
}
function request(payload) {
return fetch(rest + '/earnings/withdrawals', {
method: 'POST',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json',
'X-WP-Nonce': data.restNonce || data.nonce || ''
},
body: JSON.stringify(payload)
}).then(function (response) {
return response.json().catch(function () {
return { message: '服务器返回了非 JSON 响应' };
}).then(function (json) {
return { ok: response.ok, json: json };
});
});
}
form.addEventListener('submit', function (event) {
event.preventDefault();
var values = new FormData(form);
var amount = Number(values.get('amount') || 0);
var method = String(values.get('method') || 'alipay');
var account = String(values.get('account') || values.get('account_info') || '').trim();
var minimum = Number(page.getAttribute('data-min-amount') || 50);
if (amount < minimum) {
setMessage('最低提现金额为 ' + minimum, true);
return;
}
if (!account) {
setMessage('请填写收款账户信息', true);
return;
}
var button = form.querySelector('button[type="submit"]');
if (button) {
button.disabled = true;
button.textContent = '提交中…';
}
request({ amount: amount, method: method, account: account }).then(function (result) {
if (button) {
button.disabled = false;
button.textContent = '提交提现申请';
}
if (!result.ok || !result.json || !result.json.success) {
setMessage((result.json && result.json.message) || '提现失败,请稍后重试。', true);
return;
}
var response = result.json.data || {};
setMessage(response.message || '提现申请已提交。', false);
if (balance && typeof response.wallet_balance !== 'undefined') {
balance.textContent = '¥' + Number(response.wallet_balance).toFixed(2);
}
if (list) {
var item = document.createElement('div');
item.className = 'aksrt-revenue-page__item';
var main = document.createElement('div');
var amountEl = document.createElement('strong');
amountEl.textContent = '¥' + Number(response.amount || amount).toFixed(2);
var methodEl = document.createElement('span');
methodEl.textContent = method;
main.appendChild(amountEl);
main.appendChild(methodEl);
var state = document.createElement('div');
var pending = document.createElement('span');
pending.textContent = 'pending';
var time = document.createElement('time');
time.textContent = 'just now';
state.appendChild(pending);
state.appendChild(time);
item.appendChild(main);
item.appendChild(state);
list.insertBefore(item, list.firstChild);
}
form.reset();
}).catch(function () {
if (button) {
button.disabled = false;
button.textContent = '提交提现申请';
}
setMessage('网络错误,请稍后重试。', true);
});
});
})();
+2 -7
View File
@@ -8,10 +8,7 @@
var cfg = window.aksrtData || {};
function initReward(root) {
if (root && root.nodeType === 1 && !root.matches('[data-aksrt-reward-root], body, html')) return;
if (document.documentElement.dataset.aksrtRewardInitialized === '1') return;
document.documentElement.dataset.aksrtRewardInitialized = '1';
function initReward() {
var activeTrigger = null;
function operationKey(modal) {
@@ -126,7 +123,5 @@
});
}
if (window.AksrtFrontend && typeof window.AksrtFrontend.register === 'function') {
window.AksrtFrontend.register('aksrt-reward', initReward);
}
jQuery(document).off('auto_fun.aksrt-reward').on('auto_fun.aksrt-reward', initReward);
})();
+28 -39
View File
@@ -42,10 +42,8 @@
/* ==================== Dashboard 导航 ==================== */
function initDashboardNavigation() {
if (document.documentElement.dataset.aksrtUserCenterNavigationInitialized === 'true') return;
var tabContainer = document.querySelector('.uc-mobile-tabs');
if (!tabContainer) return;
document.documentElement.dataset.aksrtUserCenterNavigationInitialized = 'true';
var tabs = tabContainer.querySelectorAll('[data-tab]');
var sidebarBtns = document.querySelectorAll('.uc-sidebar [data-tab]');
@@ -123,9 +121,8 @@
window.AKSRTOrderCenter.destroy(target);
}
target.innerHTML = payload.data.html;
if (window.AksrtFrontend && typeof window.AksrtFrontend.rehydrate === 'function') {
window.AksrtFrontend.rehydrate(target, 'ajax');
}
if (window.jQuery) jQuery(document).trigger('post_ajax.ed', [target]);
if (typeof window.auto_fun === 'function') window.auto_fun();
target.dataset.panelLoaded = 'true';
});
}).finally(function() {
@@ -159,9 +156,8 @@
}
target.innerHTML = payload.data.html;
target.dataset.panelLoaded = 'true';
if (window.AksrtFrontend && typeof window.AksrtFrontend.rehydrate === 'function') {
window.AksrtFrontend.rehydrate(target, 'ajax');
}
if (window.jQuery) jQuery(document).trigger('post_ajax.ed', [target]);
if (typeof window.auto_fun === 'function') window.auto_fun();
});
}).finally(function() {
target.classList.remove('is-loading');
@@ -324,18 +320,18 @@
});
}
function initAuthForm(root) {
root = root || document;
var identityRoot = root.matches && root.matches('[data-identity-root]') ? root : root.querySelector('[data-identity-root]');
if (identityRoot && window.AKSRTUserCenterAuth && typeof window.AKSRTUserCenterAuth.init === 'function') {
window.AKSRTUserCenterAuth.init(identityRoot);
function initAuthForm() {
var root = document.querySelector('[data-identity-root]');
if (root && window.AKSRTUserCenterAuth && typeof window.AKSRTUserCenterAuth.init === 'function') {
window.AKSRTUserCenterAuth.init(root);
}
}
/* ==================== 列表内取消收藏 ==================== */
function initUnfavorite(root) {
root = root || document;
var list = root.matches && root.matches('.profile-list[data-list="favorites"]') ? root : root.querySelector('.profile-list[data-list="favorites"]');
function initUnfavorite() {
var list = document.querySelector('.profile-list[data-list="favorites"]');
if (!list) return;
list.addEventListener('click', function(e) {
@@ -393,7 +389,7 @@
});
}
function initPostDeletion(root) {
function initPostDeletion() {
if (document.documentElement.dataset.aksrtPostDeletionBound === 'true') return;
document.documentElement.dataset.aksrtPostDeletionBound = 'true';
document.addEventListener('click', function(e) {
@@ -421,14 +417,12 @@
}
/* ==================== 通知中心 ==================== */
function initNotifications(root) {
root = root || document;
var list = root.matches && root.matches('#aksrt-notification-list') ? root : root.querySelector('#aksrt-notification-list');
var markAllBtn = list && list.ownerDocument.getElementById('aksrt-mark-all-notifications-read');
var markSelectedBtn = list && list.ownerDocument.getElementById('aksrt-mark-selected-notifications-read');
var deleteSelectedBtn = list && list.ownerDocument.getElementById('aksrt-delete-selected-notifications');
if (!list || list.dataset.aksrtNotificationsInitialized === 'true') return;
list.dataset.aksrtNotificationsInitialized = 'true';
function initNotifications() {
var list = document.getElementById('aksrt-notification-list');
var markAllBtn = document.getElementById('aksrt-mark-all-notifications-read');
var markSelectedBtn = document.getElementById('aksrt-mark-selected-notifications-read');
var deleteSelectedBtn = document.getElementById('aksrt-delete-selected-notifications');
if (!list) return;
function markRead(notificationId, markAll) {
var body = new URLSearchParams();
@@ -1034,24 +1028,19 @@
}
function initNavigationOnce() {
jQuery(document).off('auto_fun.aksrt-user-center').on('auto_fun.aksrt-user-center', function () {
initDashboardNavigation();
initProfileForm();
initAuthForm();
initUnfavorite();
initPostDeletion();
}
if (window.AksrtFrontend && typeof window.AksrtFrontend.register === 'function') {
window.AksrtFrontend.register('aksrt-user-center', function(root) {
initNavigationOnce();
initProfileForm(root);
initAuthForm(root);
initUnfavorite(root);
initNotifications(root);
initNotificationPreferences(root);
initSettings(root);
initBindPhone(root);
initNotifications();
initNotificationPreferences();
initSettings();
initBindPhone();
initSettingsCallbackToast();
});
}
// 绑定手机
function initBindPhone(root) {
-1
View File
@@ -1 +0,0 @@
//社交账号解绑
View File
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
+567
View File
@@ -0,0 +1,567 @@
(function ($, window) {
'use strict';
var Miniimgbox = function (img_selector, container_selector) {
return _Miniimgbox(img_selector, container_selector, Miniimgbox.options);
};
Miniimgbox.options = {
group: true,
thumbs: true,
down: true,
play: true,
zoom: true,
full: true,
exclude: '.no-imgbox,.avatar,.img-icon,.avatar-badge', //排除
};
Miniimgbox.swiper = '';
Miniimgbox.thumbs_swiper = '';
window.Miniimgbox = Miniimgbox;
function _Miniimgbox(img_selector, container_selector, options) {
var imgbox_calss = 'mini-imgbox imgbox';
var imgbox_id = 'mini-imgbox';
var data_key = 'imgbox_data';
var imgbox_selector = '#' + imgbox_id;
var _imgbox = $(imgbox_selector);
var Miniimgbox = window.Miniimgbox;
var imgbox_swiper = Miniimgbox.swiper;
var imgbox_thumbs_swiper = Miniimgbox.thumbs_swiper;
var _body = $('body');
var _fixed = $('.nav-fixed header');
if (!options.group) {
options.thumbs = false;
}
init();
function init() {
add_dom();
if (options.exclude) {
img_selector += ':not(' + options.exclude + ')';
}
var all_img_selector = container_selector ? container_selector + ' ' + img_selector : img_selector;
container_selector = options.group ? container_selector : false;
setTimeout(function () {
update_all_slide_data(img_selector, container_selector); //更新dom数据
}, 1000);
//只绑定一次
if (!_body.data('imgbox-ison-' + all_img_selector)) {
_body.on('click', all_img_selector, function () {
var _this = $(this);
imgbox_open(_this, container_selector);
});
_body.data('imgbox-ison-' + all_img_selector, true);
}
}
function imgbox_open(_this, container_s) {
var slide_lists = get_slide_lists(_this, container_s);
//没有则退出
if (!slide_lists.slide) {
return;
}
if (slide_lists.node_length > 1) {
$('.imgbox-an .toggle-palay').show();
} else {
$('.imgbox-an .toggle-palay').hide();
}
$(imgbox_selector + ' .swiper-imgbox .swiper-wrapper').html(slide_lists.slide);
if (options.thumbs) {
$(imgbox_selector + ' .swiper-thumbsbox .swiper-wrapper').html(slide_lists.thumbs);
}
var index = ~~_this.attr('imgbox-index') || 0;
setTimeout(function () {
if (options.thumbs) {
imgbox_thumbs_swiper.update();
}
imgbox_swiper.update();
imgbox_swiper.slideTo(index, 2);
imgbox_swiper.autoplay.stop();
thumb_open();
}, 16);
show(_this);
}
function get_slide_lists(_this, container_s) {
var data = _this.data(data_key);
if (data) {
return data;
}
var _container = container_s ? $(_this.parents(container_s)[0]) : {};
if (_container.length) {
var _data = _container.data(data_key);
if (_data && _data.node_length == get_node_length(_container)) {
return _data;
}
}
return update_slide_data(_this, _container);
}
//获取节点数量
function get_node_length(_container) {
return _container.find(img_selector).length;
}
function update_all_slide_data(img_selector, container_s) {
if (container_s) {
$(container_s).each(function () {
var each_this = $(this);
if (!each_this.data(data_key)) {
update_slide_data(each_this.find(img_selector).eq(0), each_this);
}
});
} else {
$(img_selector).each(function () {
var each_this = $(this);
if (!each_this.data(data_key)) {
update_slide_data(each_this, {});
}
});
}
}
//将数据保存到节点
function update_slide_data(_this, _container) {
var data = {
slide: '',
thumbs: '',
length: 0,
};
if (_container.length) {
var index = 0;
_container.find(img_selector).each(function (i) {
if (i == 0) {
index = 0;
}
var each_this = $(this);
if (!is_no(each_this)) {
each_this.attr('imgbox-index', index);
data.slide += get_slide(each_this);
data.length = index + 1;
//缩略图
if (options.thumbs) data.thumbs += get_thumbs(each_this);
index++;
}
});
data.node_length = get_node_length(_container);
_container.data(data_key, data);
} else {
if (!is_no(_this) && !_this.find('img').length) {
data.slide = get_slide(_this);
data.length = index;
if (!_this.attr('imgbox-no-cache')) {
_this.data(data_key, data);
}
}
}
return data;
}
//加载dom
function add_dom() {
if (_imgbox.length) return;
var swiper = '<div class="swiper-imgbox"><div class="swiper-wrapper"></div><div class="swiper-button-prev"></div><div class="swiper-button-next"></div><div class="abs-left counter-con"></div></div>';
var thumbs_swiper = '<div class="swiper-thumbsbox"><div class="swiper-wrapper">' + '' + '</div><div class="swiper-button-prev"></div><div class="swiper-button-next"></div><div class="abs-center right-top"><i class="hide-but fa fas fa-angle-down em12"></i></div></div>';
var button = options.down ? '<a href="javascript:;" download class="img-down toggle-radius mr6" title="' + aksrt__('imgbox_download') + '"><i class="fa fas fa-download"></i></a>' : '';
if (options.group) {
button += options.play ? '<a href="javascript:;" class="toggle-palay toggle-radius mr6" title="' + aksrt__('imgbox_play') + '"><i class="fa fas fa-play"></i></a>' : '';
if (options.thumbs) {
button += '<a href="javascript:;" class="toggle-thumbs toggle-radius mr6" title="' + aksrt__('imgbox_view_more') + '"><i class="fa fas fa-th-large"></i></a>';
swiper += thumbs_swiper;
}
}
button += options.zoom ? '<a href="javascript:;" class="toggle-zoom toggle-radius mr6" title="' + aksrt__('imgbox_toggle_zoom') + '"><i class="fa fas fa-search"></i></a>' : '';
button += options.full ? '<a href="javascript:;" class="hide-sm toggle-full toggle-radius mr6" title="' + aksrt__('imgbox_toggle_full') + '"><i class="fa fas fa-expand"></i></a>' : '';
button += '<a href="javascript:;" title="' + aksrt__('close') + '" class="icon-close toggle-radius"><svg viewBox="0 0 1024 1024" class="icon em12"><path d="M573.44 512.128l237.888 237.696a43.328 43.328 0 0 1 0 59.712 43.392 43.392 0 0 1-59.712 0L513.728 571.84 265.856 819.712a44.672 44.672 0 0 1-61.568 0 44.672 44.672 0 0 1 0-61.568L452.16 510.272 214.208 272.448a43.328 43.328 0 0 1 0-59.648 43.392 43.392 0 0 1 59.712 0l237.952 237.76 246.272-246.272a44.672 44.672 0 0 1 61.568 0 44.672 44.672 0 0 1 0 61.568L573.44 512.128z"></path></svg></a>';
_body.append('<div class="' + imgbox_calss + '" id="' + imgbox_id + '"><div class="modal-backdrop imgbox-bg"></div><div class="imgbox-an">' + button + '</div>' + swiper + '</div>');
_imgbox = $(imgbox_selector);
new_swiper();
imgbox_on();
}
function new_swiper() {
var selector = imgbox_selector + ' .swiper-imgbox';
var speed = ~~(($(window).width() + 1600) / 600);
var option = {};
// option['init'] = false;
option['mousewheel'] = {
speed: 10,
};
option['speed'] = speed * 100;
option['zoom'] = {
maxRatio: $(window).width() < 769 ? 3 : 2,
};
option['autoplay'] = {
disableOnInteraction: false,
};
option['grabCursor'] = true;
option['navigation'] = {
nextEl: selector + ' .swiper-button-next',
prevEl: selector + ' .swiper-button-prev',
};
option['keyboard'] = {
enabled: !0,
onlyInViewport: !1,
};
option['pagination'] = {
el: selector + ' .counter-con',
type: 'custom',
renderCustom: function (swiper, current, total) {
if (total > 1) {
return '<badge class="b-black counter">' + current + '/' + total + '</badge>';
}
return '';
},
};
if (options.thumbs && options.group) {
new_thumbs_swiper();
option['thumbs'] = {
swiper: imgbox_thumbs_swiper,
autoScrollOffset: ~~(speed / 1.6),
};
}
Miniimgbox.swiper = imgbox_swiper = new Swiper(selector, option);
}
function new_thumbs_swiper() {
var selector = imgbox_selector + ' .swiper-thumbsbox';
var option = {};
// option['init'] = true;
option['watchSlidesVisibility'] = true; //防止不可点击
option['navigation'] = {
nextEl: selector + ' .swiper-button-next',
prevEl: selector + ' .swiper-button-prev',
};
option.slidesPerView = 'auto';
option.freeMode = true;
option.freeModeSticky = true;
Miniimgbox.thumbs_swiper = imgbox_thumbs_swiper = new Swiper(selector, option);
}
//绑定执行
function imgbox_on() {
//仅绑定一次
if (_imgbox.data('is_on')) return;
//下滑关闭
touch_close();
//关闭灯箱
_imgbox.on('click', '.img-close,.imgbox-bg,.imgbox-an .icon-close', close);
//切换thumb
_imgbox.on('click', '.imgbox-an .toggle-thumbs,.hide-but', function () {
_imgbox.toggleClass('show-thumb');
});
//下载图片
_imgbox.on('click', '.imgbox-an .img-down', function () {
var _this = $(this);
var img = _imgbox.find('.swiper-imgbox .swiper-slide-active img');
var src = img.attr('data-src') || img.attr('src');
var down_name = src.substring(src.lastIndexOf('/') + 1) || src;
_this.attr('href', src).attr('download', down_name);
});
//播放图片
_imgbox.on('click', '.imgbox-an .toggle-palay', function () {
var _this = $(this);
_this.hasClass('is-play') ? imgbox_swiper.autoplay.stop() : imgbox_swiper.autoplay.start();
_this.toggleClass('is-play');
});
//按钮切换放大缩小
_imgbox.on('click', '.imgbox-an .toggle-zoom', function () {
var _this = $(this);
imgbox_swiper.zoom.toggle();
_this.toggleClass('is-zoom');
});
//切换全屏
_imgbox.on('click', '.imgbox-an .toggle-full', function () {
if (!document.fullscreenElement) {
//进入页面全屏
full_in();
} else {
full_out();
}
});
_imgbox.data('is_on', true);
}
//全屏
function full_in() {
var docElm = document.documentElement;
if (docElm.requestFullscreen) {
docElm.requestFullscreen();
} else if (docElm.msRequestFullscreen) {
docElm.msRequestFullscreen();
} else if (docElm.mozRequestFullScreen) {
docElm.mozRequestFullScreen();
} else if (docElm.webkitRequestFullScreen) {
docElm.webkitRequestFullScreen();
}
$(imgbox_selector + ' .imgbox-an .toggle-full .fa')
.removeClass('fa-expand')
.addClass('fa-compress');
$(imgbox_selector + '.show').addClass('full-screen'); //全屏
}
//退出全屏
function full_out() {
if (document.fullscreenElement) {
if (document.exitFullscreen) {
document.exitFullscreen();
} else if (document.msExitFullscreen) {
document.msExitFullscreen();
} else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
} else if (document.webkitCancelFullScreen) {
document.webkitCancelFullScreen();
}
}
$(imgbox_selector + ' .imgbox-an .toggle-full .fa')
.removeClass('fa-compress')
.addClass('fa-expand');
_imgbox.removeClass('full-screen'); //全屏
}
//链接处理
function link_replace(link) {
return link.indexOf('base64,') == -1 && link.length < 300 ? link.replace(/(.*\/)(.*)(-\d+x\d+\.)(.*)/g, '$1$2.$4').replace(/\??x-oss-process(.*)/, '') : link;
}
//定位show_style
function show_style(_this) {
var offset = _this.offset();
var offset_top = offset.top;
var offset_left = offset.left;
var scrollTop = $(document).scrollTop();
var height = _this.height();
var width = _this.width();
var s_top = offset_top - scrollTop + height / 2;
var s_left = offset_left + width / 2;
_imgbox.attr('style', '--imgbox-origin-top:' + s_top + 'px;--imgbox-origin-left:' + s_left + 'px;');
}
function thumb_open() {
var _thumb_btn = $(imgbox_selector + ' .imgbox-an .toggle-thumbs,.hide-but');
if (options.thumbs && _thumb_btn.length) {
if (imgbox_swiper.slides.length > 1) {
_thumb_btn.show();
} else {
_imgbox.removeClass('show-thumb');
_thumb_btn.hide();
}
}
}
function checkScrollbar() {
var fullWindowWidth = window.innerWidth;
if (!fullWindowWidth) {
// 兼容IE8
var documentElementRect = document.documentElement.getBoundingClientRect();
fullWindowWidth = documentElementRect.right - Math.abs(documentElementRect.left);
}
return document.body.clientWidth < fullWindowWidth;
}
function measureScrollbar() {
var scrollbarWidthData = _body.data('scrollbar-width');
if (scrollbarWidthData !== undefined) {
return scrollbarWidthData;
}
// thx walsh
var scrollDiv = document.createElement('div');
scrollDiv.className = 'modal-scrollbar-measure';
_body.append(scrollDiv);
var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth;
_body[0].removeChild(scrollDiv);
_body.data('scrollbar-width', scrollbarWidth);
return scrollbarWidth;
}
function setScrollbar() {
var bodyPad = parseInt(_body.css('padding-right') || 0, 10);
var scrollbarWidth = measureScrollbar();
if (checkScrollbar()) {
_body.css('padding-right', bodyPad + scrollbarWidth);
_fixed.each(function (index, element) {
var actualPadding = element.style.paddingRight;
var calculatedPadding = $(element).css('padding-right');
$(element)
.data('padding-right', actualPadding)
.css('transition', 'none')
.css('padding-right', parseFloat(calculatedPadding) + scrollbarWidth + 'px');
});
}
}
//显示
function show(_this) {
setScrollbar();
_body.addClass('imgbox-show');
//$(".modal").modal("hide");
show_style(_this);
_imgbox.addClass('show').removeClass('hide');
}
function close() {
_body.removeClass('imgbox-show').css('padding-right', '');
//等待动画结束,延迟
_fixed.css('padding-right', '');
setTimeout(function () {
_fixed.css('transition', '');
}, 10);
_imgbox.addClass('hideing').removeClass('show');
full_out(); //退出全屏
setTimeout(function () {
_imgbox.removeClass('hideing').addClass('hide').attr('style', '');
$('.toggle-palay.is-play').removeClass('is-play'); //停止播放
try {
imgbox_swiper.zoom.out(); //恢复放大缩小
imgbox_swiper.autoplay.stop(); //停止播放
} catch (e) {
console.log(e);
}
//恢复下滑关闭
$(imgbox_selector + ' .swiper-close').css({
opacity: '',
transform: '',
});
}, 300);
}
//滑动关闭
function touch_close() {
_imgbox.on('touchmove pointermove MSPointerMove', function (e) {
e.preventDefault ? e.preventDefault() : (e.returnValue = !1);
});
_imgbox.minitouch({
direction: 'bottom',
selector: '.swiper-close',
depreciation: 100,
onStart: false,
stop: function (_e, _this) {
var scale = _this
.find('img')
.css('transform')
.replace(/[^0-9\-,]/g, '')
.split(',')[0];
return scale && scale > 1;
},
onIng: function (_e, _this, distanceX, distanceY) {
var set_opacity = (150 - distanceY) / 80;
set_opacity = set_opacity < 1 && set_opacity > 0.2 && set_opacity;
_this.css('opacity', set_opacity);
},
inEnd: function (_e, _this) {
_this.css({
opacity: '',
});
},
onEnd: function (_e, _this) {
_imgbox.attr('style', '--imgbox-origin-top:' + t_h + 'px;--imgbox-origin-left:conter;');
var t_h = _this.height();
_this.css({
transform: 'translate3D(0px, ' + t_h + 'px, 0px)',
transition: '.2s linear',
opacity: 0,
});
// close();
setTimeout(close, 150);
},
});
}
function get_slide(each_this) {
var thumbs_src = each_this.attr('src') || each_this.attr('box-img');
var data_src = each_this.attr('data-src');
if (!thumbs_src && !data_src) return '';
var full_src = each_this.attr('data-full-url') || link_replace(data_src || thumbs_src);
var main_img = '<img src="' + thumbs_src + '" data-src="' + full_src + '" class="lazyload"><div class="swiper-lazy-preloader"></div>';
var main_img_html = '<div class="swiper-slide"><div class="swiper-close"><div class="swiper-zoom-container"><div class="absolute img-close"></div>' + main_img + '</div></div></div>';
return main_img_html;
}
function get_thumbs(each_this) {
var thumbs_src_b = each_this.attr('data-src') || each_this.attr('src');
if (!thumbs_src_b) return '';
var thumbs_img = '<img data-src="' + thumbs_src_b + '" class="lazyload fit-cover">';
var thumbs_img_html = '<div class="swiper-slide">' + thumbs_img + '</div>';
return thumbs_img_html;
}
function is_no(_this) {
//判断上级是否有链接,且不是链接到原图
var src = _this.attr('data-src') || _this.attr('src');
if (!src) return false;
src = link_replace(src);
var parent = _this.parent('a');
if (!parent.length) return false;
var href = parent.attr('box-img') || parent.attr('href');
href = link_replace(href);
return href && (href.indexOf(src) == -1 || src.indexOf(href) == -1);
}
}
tbquire(['swiper'], function () {
$('link#swiper').length || $('head').append('<link type="text/css" id="swiper" rel="stylesheet" href="' + _win.uri + '/css/swiper.min.css?ver=' + _win.ver + '">');
Miniimgbox.options.group = _win.imgbox_type === 'group';
Miniimgbox.options.thumbs = _win.imgbox_thumbs;
Miniimgbox.options.down = _win.imgbox_down;
Miniimgbox.options.play = _win.imgbox_play;
Miniimgbox.options.zoom = _win.imgbox_zoom;
Miniimgbox.options.full = _win.imgbox_full;
Miniimgbox('.alone-imgbox-img,a[data-imgbox]');
Miniimgbox('img', '.wp-posts-content');
Miniimgbox('img', '.imgbox-container');
Miniimgbox('.box-img', '.comment-content');
});
})(jQuery, window);
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
-266
View File
@@ -1,266 +0,0 @@
/* InstantClick 3.1.0 | (C) 2014 Alexandre Dieulot | http://instantclick.io/license */
var InstantClick = function (d, e) {
function w(a) {
var b = a.indexOf("#");
return 0 > b ? a : a.substr(0, b)
}
function z(a) {
for (; a && "A" != a.nodeName;) a = a.parentNode;
return a
}
function A(a) {
var b = e.protocol + "//" + e.host;
if (!(b = a.target || a.hasAttribute("download") || 0 != a.href.indexOf(b + "/") || -1 < a.href.indexOf("#") && w(a.href) == k)) {
if (J) {
a: {
do {
if (!a.hasAttribute) break;
if (a.hasAttribute("data-no-instant")) break;
if (a.hasAttribute("data-instant")) {
a = !0;
break a
}
} while (a = a.parentNode);a = !1
}
a = !a
}
else a: {
do {
if (!a.hasAttribute) break;
if (a.hasAttribute("data-instant")) break;
if (a.hasAttribute("data-no-instant")) {
a = !0;
break a
}
} while (a = a.parentNode);a = !1
}
b = a
}
return b ? !1 : !0
}
function t(a, b, c, g) {
for (var d = !1, e = 0; e < B[a].length; e++)
if ("receive" == a) {
var f = B[a][e](b, c, g);
f && ("body" in f && (c = f.body), "title" in f && (g = f.title), d = f)
} else B[a][e](b, c, g);
return d
}
function K(a, b, c, g) {
d.documentElement.replaceChild(b, d.body);
if (c) {
history.pushState(null, null, c);
b = c.indexOf("#");
b = -1 < b && d.getElementById(c.substr(b + 1));
g = 0;
if (b)
for (; b.offsetParent;) g +=
b.offsetTop, b = b.offsetParent;
scrollTo(0, g);
k = w(c)
} else scrollTo(0, g);
d.title = S && d.title == a ? a + String.fromCharCode(160) : a;
L();
C.done();
t("change", !1);
a = d.createEvent("HTMLEvents");
a.initEvent("instantclick:newpage", !0, !0);
dispatchEvent(a)
}
function M(a) {
G > +new Date - 500 || (a = z(a.target)) && A(a) && x(a.href)
}
function N(a) {
G > +new Date - 500 || (a = z(a.target)) && A(a) && (a.addEventListener("mouseout", T), H ? (O = a.href, l = setTimeout(x, H)) : x(a.href))
}
function U(a) {
G = +new Date;
(a = z(a.target)) && A(a) && (D ? a.removeEventListener("mousedown",
M) : a.removeEventListener("mouseover", N), x(a.href))
}
function V(a) {
var b = z(a.target);
!b || !A(b) || 1 < a.which || a.metaKey || a.ctrlKey || (a.preventDefault(), P(b.href))
}
function T() {
l ? (clearTimeout(l), l = !1) : v && !m && (p.abort(), m = v = !1)
}
function W() {
if (!(4 > p.readyState) && 0 != p.status) {
q.ready = +new Date - q.start;
if (p.getResponseHeader("Content-Type").match(/\/(x|ht|xht)ml/)) {
var a = d.implementation.createHTMLDocument("");
a.documentElement.innerHTML = p.responseText.replace(/<noscript[\s\S]+<\/noscript>/gi, "");
y = a.title;
u = a.body;
var b = t("receive", r, u, y);
b && ("body" in b && (u = b.body), "title" in b && (y = b.title));
b = w(r);
h[b] = {
body: u,
title: y,
scrollY: b in h ? h[b].scrollY : 0
};
for (var a = a.head.children, b = 0, c, g = a.length - 1; 0 <= g; g--)
if (c = a[g], c.hasAttribute("data-instant-track")) {
c = c.getAttribute("href") || c.getAttribute("src") || c.innerHTML;
for (var e = E.length - 1; 0 <= e; e--) E[e] == c && b++
} b != E.length && (F = !0)
} else F = !0;
m && (m = !1, P(r))
}
}
function L(a) {
d.body.addEventListener("touchstart", U, !0);
D ? d.body.addEventListener("mousedown", M, !0) : d.body.addEventListener("mouseover",
N, !0);
d.body.addEventListener("click", V, !0);
if (!a) {
a = d.body.getElementsByTagName("script");
var b, c, g, e;
i = 0;
for (j = a.length; i < j; i++) b = a[i], b.hasAttribute("data-no-instant") || (c = d.createElement("script"), b.src && (c.src = b.src), b.innerHTML && (c.innerHTML = b.innerHTML), g = b.parentNode, e = b.nextSibling, g.removeChild(b), g.insertBefore(c, e))
}
}
function x(a) {
!D && "display" in q && 100 > +new Date - (q.start + q.display) || (l && (clearTimeout(l), l = !1), a || (a = O), v && (a == r || m)) || (v = !0, m = !1, r = a, F = u = !1, q = {
start: +new Date
}, t("fetch"),
p.open("GET", a), p.send())
}
function P(a) {
"display" in q || (q.display = +new Date - q.start);
l || !v ? l && r && r != a ? e.href = a : (x(a), C.start(0, !0), t("wait"), m = !0) : m ? e.href = a : F ? e.href = r : u ? (h[k].scrollY = pageYOffset, m = v = !1, K(y, u, r)) : (C.start(0, !0), t("wait"), m = !0)
}
var I = navigator.userAgent,
S = -1 < I.indexOf(" CriOS/"),
Q = "createTouch" in d,
k, O, l, G, h = {},
p, r = !1,
y = !1,
F = !1,
u = !1,
q = {},
v = !1,
m = !1,
E = [],
J, D, H, B = {
fetch: [],
receive: [],
wait: [],
change: []
},
C = function () {
function a(a, e) {
n = a;
d.getElementById(f.id) && d.body.removeChild(f);
f.style.opacity =
"1";
d.getElementById(f.id) && d.body.removeChild(f);
g();
e && setTimeout(b, 0);
clearTimeout(l);
l = setTimeout(c, 500)
}
function b() {
n = 10;
g()
}
function c() {
n += 1 + 2 * Math.random();
98 <= n ? n = 98 : l = setTimeout(c, 500);
g()
}
function g() {
h.style[k] = "translate(" + n + "%)";
d.getElementById(f.id) || d.body.appendChild(f)
}
function e() {
d.getElementById(f.id) ? (clearTimeout(l), n = 100, g(), f.style.opacity = "0") : (a(100 == n ? 0 : n), setTimeout(e, 0))
}
function m() {
f.style.left = pageXOffset + "px";
f.style.width = innerWidth + "px";
f.style.top = pageYOffset +
"px";
var a = "orientation" in window && 90 == Math.abs(orientation);
f.style[k] = "scaleY(" + innerWidth / screen[a ? "height" : "width"] * 2 + ")"
}
var f, h, k, n, l;
return {
init: function () {
f = d.createElement("div");
f.id = "instantclick";
h = d.createElement("div");
h.id = "instantclick-bar";
h.className = "instantclick-bar";
f.appendChild(h);
var a = ["Webkit", "Moz", "O"];
k = "transform";
if (!(k in h.style))
for (var b = 0; 3 > b; b++) a[b] + "Transform" in h.style && (k = a[b] + "Transform");
var c = "transition";
if (!(c in h.style))
for (b = 0; 3 > b; b++) a[b] + "Transition" in
h.style && (c = "-" + a[b].toLowerCase() + "-" + c);
a = d.createElement("style");
a.innerHTML = "#instantclick{position:" + (Q ? "absolute" : "fixed") + ";top:0;left:0;width:100%;pointer-events:none;z-index:2147483647;" + c + ":opacity .25s .1s}.instantclick-bar{background:#29d;width:100%;margin-left:-100%;height:2px;" + c + ":all .25s}";
d.head.appendChild(a);
Q && (m(), addEventListener("resize", m), addEventListener("scroll", m))
},
start: a,
done: e
}
}(),
R = "pushState" in history && (!I.match("Android") || I.match("Chrome/")) && "file:" != e.protocol;
return {
supported: R,
init: function () {
if (!k)
if (R) {
for (var a = arguments.length - 1; 0 <= a; a--) {
var b = arguments[a];
!0 === b ? J = !0 : "mousedown" == b ? D = !0 : "number" == typeof b && (H = b)
}
k = w(e.href);
h[k] = {
body: d.body,
title: d.title,
scrollY: pageYOffset
};
for (var b = d.head.children, c, a = b.length - 1; 0 <= a; a--) c = b[a], c.hasAttribute("data-instant-track") && (c = c.getAttribute("href") || c.getAttribute("src") || c.innerHTML, E.push(c));
p = new XMLHttpRequest;
p.addEventListener("readystatechange", W);
L(!0);
C.init();
t("change", !0);
addEventListener("popstate",
function () {
var a = w(e.href);
a != k && (a in h ? (h[k].scrollY = pageYOffset, k = a, K(h[a].title, h[a].body, !1, h[a].scrollY)) : e.href = e.href)
})
} else t("change", !0)
},
on: function (a, b) {
B[a].push(b)
}
}
}(document, location);
-1
View File
@@ -1 +0,0 @@
"use strict";jQuery.cookie=function(e,o,t){if(void 0===o){var i=null;if(document.cookie&&""!=document.cookie)for(var r=document.cookie.split(";"),n=0;n<r.length;n++){var c=jQuery.trim(r[n]);if(c.substring(0,e.length+1)==e+"="){i=decodeURIComponent(c.substring(e.length+1));break}}return i}t=t||{},null===o&&(o="",t.expires=-1);var a="";if(t.expires&&("number"==typeof t.expires||t.expires.toUTCString)){var l;"number"==typeof t.expires?(l=new Date,l.setTime(l.getTime()+24*t.expires*60*60*1e3)):l=t.expires,a="; expires="+l.toUTCString()}var u=t.path?"; path="+t.path:"",s=t.domain?"; domain="+t.domain:"",m=t.secure?"; secure":"";document.cookie=[e,"=",encodeURIComponent(o),a,u,s,m].join("")};var lcs={get:function(e){return window.localStorage?localStorage.getItem(e):$.cookie(e)},set:function(e,o){window.localStorage?localStorage[e]=o:$.cookie(e,o)},remove:function(e){window.localStorage?localStorage.removeItem(e):$.cookie(e,"")}};
-754
View File
@@ -1,754 +0,0 @@
/*! lazysizes - v5.2.0 */
/**
* https://github.com/aFarkas/lazysizes
*/
(function (window, factory) {
var lazySizes = factory(window, window.document, Date);
window.lazySizes = lazySizes;
if (typeof module == 'object' && module.exports) {
module.exports = lazySizes;
}
})(typeof window != 'undefined' ? window : {}, function l(window, document, Date) {
// Pass in the windoe Date function also for SSR because the Date class can be lost
'use strict';
/*jshint eqnull:true */
var lazysizes, lazySizesCfg;
(function () {
var prop;
var lazySizesDefaults = {
lazyClass: 'lazyload',
loadedClass: 'lazyloaded',
loadingClass: 'lazyloading',
preloadClass: 'lazypreload',
loadafterClass: 'lazyloadafter',
errorClass: 'lazyerror',
//strictClass: 'lazystrict',
autosizesClass: 'lazyautosizes',
srcAttr: 'data-src',
srcsetAttr: 'data-srcset',
sizesAttr: 'data-sizes',
//preloadAfterLoad: false,
minSize: 40,
customMedia: {},
init: true,
expFactor: 1.5,
hFac: 0.8,
loadMode: 2,
loadHidden: true,
ricTimeout: 0,
throttleDelay: 125,
};
lazySizesCfg = window.lazySizesConfig || window.lazysizesConfig || {};
for (prop in lazySizesDefaults) {
if (!(prop in lazySizesCfg)) {
lazySizesCfg[prop] = lazySizesDefaults[prop];
}
}
})();
if (!document || !document.getElementsByClassName) {
return {
init: function () {},
cfg: lazySizesCfg,
noSupport: true,
};
}
var docElem = document.documentElement;
var supportPicture = window.HTMLPictureElement;
var _addEventListener = 'addEventListener';
var _getAttribute = 'getAttribute';
/**
* Update to bind to window because 'this' becomes null during SSR
* builds.
*/
var addEventListener = window[_addEventListener].bind(window);
var setTimeout = window.setTimeout;
var requestAnimationFrame = window.requestAnimationFrame || setTimeout;
var requestIdleCallback = window.requestIdleCallback;
var regPicture = /^picture$/i;
var loadEvents = ['load', 'error', 'lazyincluded', '_lazyloaded'];
var regClassCache = {};
var forEach = Array.prototype.forEach;
var hasClass = function (ele, cls) {
if (!regClassCache[cls]) {
regClassCache[cls] = new RegExp('(\\s|^)' + cls + '(\\s|$)');
}
return regClassCache[cls].test(ele[_getAttribute]('class') || '') && regClassCache[cls];
};
var addClass = function (ele, cls) {
if (!hasClass(ele, cls)) {
ele.setAttribute('class', (ele[_getAttribute]('class') || '').trim() + ' ' + cls);
}
};
var removeClass = function (ele, cls) {
var reg;
if ((reg = hasClass(ele, cls))) {
ele.setAttribute('class', (ele[_getAttribute]('class') || '').replace(reg, ' '));
}
};
var addRemoveLoadEvents = function (dom, fn, add) {
var action = add ? _addEventListener : 'removeEventListener';
if (add) {
addRemoveLoadEvents(dom, fn);
}
loadEvents.forEach(function (evt) {
dom[action](evt, fn);
});
};
var triggerEvent = function (elem, name, detail, noBubbles, noCancelable) {
var event = document.createEvent('Event');
if (!detail) {
detail = {};
}
detail.instance = lazysizes;
event.initEvent(name, !noBubbles, !noCancelable);
event.detail = detail;
elem.dispatchEvent(event);
return event;
};
var updatePolyfill = function (el, full) {
var polyfill;
if (!supportPicture && (polyfill = window.picturefill || lazySizesCfg.pf)) {
if (full && full.src && !el[_getAttribute]('srcset')) {
el.setAttribute('srcset', full.src);
}
polyfill({ reevaluate: true, elements: [el] });
} else if (full && full.src) {
el.src = full.src;
}
};
var getCSS = function (elem, style) {
return (getComputedStyle(elem, null) || {})[style];
};
var getWidth = function (elem, parent, width) {
width = width || elem.offsetWidth;
while (width < lazySizesCfg.minSize && parent && !elem._lazysizesWidth) {
width = parent.offsetWidth;
parent = parent.parentNode;
}
return width;
};
var rAF = (function () {
var running, waiting;
var firstFns = [];
var secondFns = [];
var fns = firstFns;
var run = function () {
var runFns = fns;
fns = firstFns.length ? secondFns : firstFns;
running = true;
waiting = false;
while (runFns.length) {
runFns.shift()();
}
running = false;
};
var rafBatch = function (fn, queue) {
if (running && !queue) {
fn.apply(this, arguments);
} else {
fns.push(fn);
if (!waiting) {
waiting = true;
(document.hidden ? setTimeout : requestAnimationFrame)(run);
}
}
};
rafBatch._lsFlush = run;
return rafBatch;
})();
var rAFIt = function (fn, simple) {
return simple
? function () {
rAF(fn);
}
: function () {
var that = this;
var args = arguments;
rAF(function () {
fn.apply(that, args);
});
};
};
var throttle = function (fn) {
var running;
var lastTime = 0;
var gDelay = lazySizesCfg.throttleDelay;
var rICTimeout = lazySizesCfg.ricTimeout;
var run = function () {
running = false;
lastTime = Date.now();
fn();
};
var idleCallback =
requestIdleCallback && rICTimeout > 49
? function () {
requestIdleCallback(run, { timeout: rICTimeout });
if (rICTimeout !== lazySizesCfg.ricTimeout) {
rICTimeout = lazySizesCfg.ricTimeout;
}
}
: rAFIt(function () {
setTimeout(run);
}, true);
return function (isPriority) {
var delay;
if ((isPriority = isPriority === true)) {
rICTimeout = 33;
}
if (running) {
return;
}
running = true;
delay = gDelay - (Date.now() - lastTime);
if (delay < 0) {
delay = 0;
}
if (isPriority || delay < 9) {
idleCallback();
} else {
setTimeout(idleCallback, delay);
}
};
};
//based on http://modernjavascript.blogspot.de/2013/08/building-better-debounce.html
var debounce = function (func) {
var timeout, timestamp;
var wait = 99;
var run = function () {
timeout = null;
func();
};
var later = function () {
var last = Date.now() - timestamp;
if (last < wait) {
setTimeout(later, wait - last);
} else {
(requestIdleCallback || run)(run);
}
};
return function () {
timestamp = Date.now();
if (!timeout) {
timeout = setTimeout(later, wait);
}
};
};
var loader = (function () {
var preloadElems, isCompleted, resetPreloadingTimer, loadMode, started;
var eLvW, elvH, eLtop, eLleft, eLright, eLbottom, isBodyHidden;
var regImg = /^img$/i;
var regIframe = /^iframe$/i;
var supportScroll = 'onscroll' in window && !/(gle|ing)bot/.test(navigator.userAgent);
var shrinkExpand = 0;
var currentExpand = 0;
var isLoading = 0;
var lowRuns = -1;
var resetPreloading = function (e) {
isLoading--;
if (!e || isLoading < 0 || !e.target) {
isLoading = 0;
}
};
var isVisible = function (elem) {
if (isBodyHidden == null) {
isBodyHidden = getCSS(document.body, 'visibility') == 'hidden';
}
return isBodyHidden || !(getCSS(elem.parentNode, 'visibility') == 'hidden' && getCSS(elem, 'visibility') == 'hidden');
};
var isNestedVisible = function (elem, elemExpand) {
var outerRect;
var parent = elem;
var visible = isVisible(elem);
eLtop -= elemExpand;
eLbottom += elemExpand;
eLleft -= elemExpand;
eLright += elemExpand;
while (visible && (parent = parent.offsetParent) && parent != document.body && parent != docElem) {
visible = (getCSS(parent, 'opacity') || 1) > 0;
if (visible && getCSS(parent, 'overflow') != 'visible') {
outerRect = parent.getBoundingClientRect();
visible = eLright > outerRect.left && eLleft < outerRect.right && eLbottom > outerRect.top - 1 && eLtop < outerRect.bottom + 1;
}
}
return visible;
};
var checkElements = function () {
var eLlen, i, rect, autoLoadElem, loadedSomething, elemExpand, elemNegativeExpand, elemExpandVal, beforeExpandVal, defaultExpand, preloadExpand, hFac;
var lazyloadElems = lazysizes.elements;
if ((loadMode = lazySizesCfg.loadMode) && isLoading < 8 && (eLlen = lazyloadElems.length)) {
i = 0;
lowRuns++;
for (; i < eLlen; i++) {
if (!lazyloadElems[i] || lazyloadElems[i]._lazyRace) {
continue;
}
if (!supportScroll || (lazysizes.prematureUnveil && lazysizes.prematureUnveil(lazyloadElems[i]))) {
unveilElement(lazyloadElems[i]);
continue;
}
if (!(elemExpandVal = lazyloadElems[i][_getAttribute]('data-expand')) || !(elemExpand = elemExpandVal * 1)) {
elemExpand = currentExpand;
}
if (!defaultExpand) {
defaultExpand = !lazySizesCfg.expand || lazySizesCfg.expand < 1 ? (docElem.clientHeight > 500 && docElem.clientWidth > 500 ? 500 : 370) : lazySizesCfg.expand;
lazysizes._defEx = defaultExpand;
preloadExpand = defaultExpand * lazySizesCfg.expFactor;
hFac = lazySizesCfg.hFac;
isBodyHidden = null;
if (currentExpand < preloadExpand && isLoading < 1 && lowRuns > 2 && loadMode > 2 && !document.hidden) {
currentExpand = preloadExpand;
lowRuns = 0;
} else if (loadMode > 1 && lowRuns > 1 && isLoading < 6) {
currentExpand = defaultExpand;
} else {
currentExpand = shrinkExpand;
}
}
if (beforeExpandVal !== elemExpand) {
eLvW = innerWidth + elemExpand * hFac;
elvH = innerHeight + elemExpand;
elemNegativeExpand = elemExpand * -1;
beforeExpandVal = elemExpand;
}
rect = lazyloadElems[i].getBoundingClientRect();
if ((eLbottom = rect.bottom) >= elemNegativeExpand && (eLtop = rect.top) <= elvH && (eLright = rect.right) >= elemNegativeExpand * hFac && (eLleft = rect.left) <= eLvW && (eLbottom || eLright || eLleft || eLtop) && (lazySizesCfg.loadHidden || isVisible(lazyloadElems[i])) && ((isCompleted && isLoading < 3 && !elemExpandVal && (loadMode < 3 || lowRuns < 4)) || isNestedVisible(lazyloadElems[i], elemExpand))) {
unveilElement(lazyloadElems[i]);
loadedSomething = true;
if (isLoading > 9) {
break;
}
} else if (!loadedSomething && isCompleted && !autoLoadElem && isLoading < 4 && lowRuns < 4 && loadMode > 2 && (preloadElems[0] || lazySizesCfg.preloadAfterLoad) && (preloadElems[0] || (!elemExpandVal && (eLbottom || eLright || eLleft || eLtop || lazyloadElems[i][_getAttribute](lazySizesCfg.sizesAttr) != 'auto')))) {
autoLoadElem = preloadElems[0] || lazyloadElems[i];
}
}
if (autoLoadElem && !loadedSomething) {
unveilElement(autoLoadElem);
}
}
};
var throttledCheckElements = throttle(checkElements);
var switchLoadingClass = function (e) {
var elem = e.target;
if (elem._lazyCache) {
delete elem._lazyCache;
return;
}
resetPreloading(e);
addClass(elem, lazySizesCfg.loadedClass);
removeClass(elem, lazySizesCfg.loadingClass);
addRemoveLoadEvents(elem, rafSwitchLoadingClass);
triggerEvent(elem, 'lazyloaded');
//添加loadafterClass,防止后期二次触发动画
setTimeout(function () {
addClass(elem, lazySizesCfg.loadafterClass);
}, 700);
};
var rafedSwitchLoadingClass = rAFIt(switchLoadingClass);
var rafSwitchLoadingClass = function (e) {
rafedSwitchLoadingClass({ target: e.target });
};
var changeIframeSrc = function (elem, src) {
try {
elem.contentWindow.location.replace(src);
} catch (e) {
elem.src = src;
}
};
var handleSources = function (source) {
var customMedia;
var sourceSrcset = source[_getAttribute](lazySizesCfg.srcsetAttr);
if ((customMedia = lazySizesCfg.customMedia[source[_getAttribute]('data-media') || source[_getAttribute]('media')])) {
source.setAttribute('media', customMedia);
}
if (sourceSrcset) {
source.setAttribute('srcset', sourceSrcset);
}
};
var lazyUnveil = rAFIt(function (elem, detail, isAuto, sizes, isImg) {
var src, srcset, parent, isPicture, event, firesLoad;
if (!(event = triggerEvent(elem, 'lazybeforeunveil', detail)).defaultPrevented) {
if (sizes) {
if (isAuto) {
addClass(elem, lazySizesCfg.autosizesClass);
} else {
elem.setAttribute('sizes', sizes);
}
}
srcset = elem[_getAttribute](lazySizesCfg.srcsetAttr);
src = elem[_getAttribute](lazySizesCfg.srcAttr);
if (isImg) {
parent = elem.parentNode;
isPicture = parent && regPicture.test(parent.nodeName || '');
}
firesLoad = detail.firesLoad || ('src' in elem && (srcset || src || isPicture));
event = { target: elem };
addClass(elem, lazySizesCfg.loadingClass);
if (firesLoad) {
clearTimeout(resetPreloadingTimer);
resetPreloadingTimer = setTimeout(resetPreloading, 2500);
addRemoveLoadEvents(elem, rafSwitchLoadingClass, true);
}
if (isPicture) {
forEach.call(parent.getElementsByTagName('source'), handleSources);
}
if (srcset) {
elem.setAttribute('srcset', srcset);
} else if (src && !isPicture) {
if (regIframe.test(elem.nodeName)) {
changeIframeSrc(elem, src);
} else {
elem.src = src;
}
}
if (isImg && (srcset || isPicture)) {
updatePolyfill(elem, { src: src });
}
}
if (elem._lazyRace) {
delete elem._lazyRace;
}
removeClass(elem, lazySizesCfg.lazyClass);
rAF(function () {
// Part of this can be removed as soon as this fix is older: https://bugs.chromium.org/p/chromium/issues/detail?id=7731 (2015)
var isLoaded = elem.complete && elem.naturalWidth > 1;
if (!firesLoad || isLoaded) {
if (isLoaded) {
addClass(elem, 'ls-is-cached');
}
switchLoadingClass(event);
elem._lazyCache = true;
setTimeout(function () {
if ('_lazyCache' in elem) {
delete elem._lazyCache;
}
}, 9);
}
if (elem.loading == 'lazy') {
isLoading--;
}
}, true);
});
var unveilElement = function (elem) {
if (elem._lazyRace) {
return;
}
var detail;
var isImg = regImg.test(elem.nodeName);
//allow using sizes="auto", but don't use. it's invalid. Use data-sizes="auto" or a valid value for sizes instead (i.e.: sizes="80vw")
var sizes = isImg && (elem[_getAttribute](lazySizesCfg.sizesAttr) || elem[_getAttribute]('sizes'));
var isAuto = sizes == 'auto';
if ((isAuto || !isCompleted) && isImg && (elem[_getAttribute]('src') || elem.srcset) && !elem.complete && !hasClass(elem, lazySizesCfg.errorClass) && hasClass(elem, lazySizesCfg.lazyClass)) {
return;
}
detail = triggerEvent(elem, 'lazyunveilread').detail;
if (isAuto) {
autoSizer.updateElem(elem, true, elem.offsetWidth);
}
elem._lazyRace = true;
isLoading++;
lazyUnveil(elem, detail, isAuto, sizes, isImg);
};
var afterScroll = debounce(function () {
lazySizesCfg.loadMode = 3;
throttledCheckElements();
});
var altLoadmodeScrollListner = function () {
if (lazySizesCfg.loadMode == 3) {
lazySizesCfg.loadMode = 2;
}
afterScroll();
};
var onload = function () {
if (isCompleted) {
return;
}
if (Date.now() - started < 999) {
setTimeout(onload, 999);
return;
}
isCompleted = true;
lazySizesCfg.loadMode = 3;
throttledCheckElements();
addEventListener('scroll', altLoadmodeScrollListner, true);
};
return {
_: function () {
started = Date.now();
lazysizes.elements = document.getElementsByClassName(lazySizesCfg.lazyClass);
preloadElems = document.getElementsByClassName(lazySizesCfg.lazyClass + ' ' + lazySizesCfg.preloadClass);
addEventListener('scroll', throttledCheckElements, true);
addEventListener('resize', throttledCheckElements, true);
addEventListener('pageshow', function (e) {
if (e.persisted) {
var loadingElements = document.querySelectorAll('.' + lazySizesCfg.loadingClass);
if (loadingElements.length && loadingElements.forEach) {
requestAnimationFrame(function () {
loadingElements.forEach(function (img) {
if (img.complete) {
unveilElement(img);
}
});
});
}
}
});
if (window.MutationObserver) {
new MutationObserver(throttledCheckElements).observe(docElem, { childList: true, subtree: true, attributes: true });
} else {
docElem[_addEventListener]('DOMNodeInserted', throttledCheckElements, true);
docElem[_addEventListener]('DOMAttrModified', throttledCheckElements, true);
setInterval(throttledCheckElements, 999);
}
addEventListener('hashchange', throttledCheckElements, true);
//, 'fullscreenchange'
['focus', 'mouseover', 'click', 'load', 'transitionend', 'animationend'].forEach(function (name) {
document[_addEventListener](name, throttledCheckElements, true);
});
if (/d$|^c/.test(document.readyState)) {
onload();
} else {
addEventListener('load', onload);
document[_addEventListener]('DOMContentLoaded', throttledCheckElements);
setTimeout(onload, 20000);
}
if (lazysizes.elements.length) {
checkElements();
rAF._lsFlush();
} else {
throttledCheckElements();
}
},
checkElems: throttledCheckElements,
unveil: unveilElement,
_aLSL: altLoadmodeScrollListner,
};
})();
var autoSizer = (function () {
var autosizesElems;
var sizeElement = rAFIt(function (elem, parent, event, width) {
var sources, i, len;
elem._lazysizesWidth = width;
width += 'px';
elem.setAttribute('sizes', width);
if (regPicture.test(parent.nodeName || '')) {
sources = parent.getElementsByTagName('source');
for (i = 0, len = sources.length; i < len; i++) {
sources[i].setAttribute('sizes', width);
}
}
if (!event.detail.dataAttr) {
updatePolyfill(elem, event.detail);
}
});
var getSizeElement = function (elem, dataAttr, width) {
var event;
var parent = elem.parentNode;
if (parent) {
width = getWidth(elem, parent, width);
event = triggerEvent(elem, 'lazybeforesizes', { width: width, dataAttr: !!dataAttr });
if (!event.defaultPrevented) {
width = event.detail.width;
if (width && width !== elem._lazysizesWidth) {
sizeElement(elem, parent, event, width);
}
}
}
};
var updateElementsSizes = function () {
var i;
var len = autosizesElems.length;
if (len) {
i = 0;
for (; i < len; i++) {
getSizeElement(autosizesElems[i]);
}
}
};
var debouncedUpdateElementsSizes = debounce(updateElementsSizes);
return {
_: function () {
autosizesElems = document.getElementsByClassName(lazySizesCfg.autosizesClass);
addEventListener('resize', debouncedUpdateElementsSizes);
},
checkElems: debouncedUpdateElementsSizes,
updateElem: getSizeElement,
};
})();
var init = function () {
if (!init.i && document.getElementsByClassName) {
init.i = true;
autoSizer._();
loader._();
}
};
setTimeout(function () {
if (lazySizesCfg.init) {
init();
}
});
lazysizes = {
cfg: lazySizesCfg,
autoSizer: autoSizer,
loader: loader,
init: init,
uP: updatePolyfill,
aC: addClass,
rC: removeClass,
hC: hasClass,
fire: triggerEvent,
gW: getWidth,
rAF: rAF,
};
return lazysizes;
});
File diff suppressed because one or more lines are too long
-751
View File
@@ -1,751 +0,0 @@
(function (factory) {
if (typeof exports === 'object') {
// Node/CommonJS
module.exports = factory();
} else if (typeof define === 'function' && define.amd) {
// AMD
define(factory);
} else {
// Browser globals (with support for web workers)
var glob;
try {
glob = window;
} catch (e) {
glob = self;
}
glob.SparkMD5 = factory();
}
}(function (undefined) {
'use strict';
/*
* Fastest md5 implementation around (JKM md5).
* Credits: Joseph Myers
*
* @see http://www.myersdaily.org/joseph/javascript/md5-text.html
* @see http://jsperf.com/md5-shootout/7
*/
/* this function is much faster,
so if possible we use it. Some IEs
are the only ones I know of that
need the idiotic second function,
generated by an if clause. */
var add32 = function (a, b) {
return (a + b) & 0xFFFFFFFF;
},
hex_chr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
function cmn(q, a, b, x, s, t) {
a = add32(add32(a, q), add32(x, t));
return add32((a << s) | (a >>> (32 - s)), b);
}
function md5cycle(x, k) {
var a = x[0],
b = x[1],
c = x[2],
d = x[3];
a += (b & c | ~b & d) + k[0] - 680876936 | 0;
a = (a << 7 | a >>> 25) + b | 0;
d += (a & b | ~a & c) + k[1] - 389564586 | 0;
d = (d << 12 | d >>> 20) + a | 0;
c += (d & a | ~d & b) + k[2] + 606105819 | 0;
c = (c << 17 | c >>> 15) + d | 0;
b += (c & d | ~c & a) + k[3] - 1044525330 | 0;
b = (b << 22 | b >>> 10) + c | 0;
a += (b & c | ~b & d) + k[4] - 176418897 | 0;
a = (a << 7 | a >>> 25) + b | 0;
d += (a & b | ~a & c) + k[5] + 1200080426 | 0;
d = (d << 12 | d >>> 20) + a | 0;
c += (d & a | ~d & b) + k[6] - 1473231341 | 0;
c = (c << 17 | c >>> 15) + d | 0;
b += (c & d | ~c & a) + k[7] - 45705983 | 0;
b = (b << 22 | b >>> 10) + c | 0;
a += (b & c | ~b & d) + k[8] + 1770035416 | 0;
a = (a << 7 | a >>> 25) + b | 0;
d += (a & b | ~a & c) + k[9] - 1958414417 | 0;
d = (d << 12 | d >>> 20) + a | 0;
c += (d & a | ~d & b) + k[10] - 42063 | 0;
c = (c << 17 | c >>> 15) + d | 0;
b += (c & d | ~c & a) + k[11] - 1990404162 | 0;
b = (b << 22 | b >>> 10) + c | 0;
a += (b & c | ~b & d) + k[12] + 1804603682 | 0;
a = (a << 7 | a >>> 25) + b | 0;
d += (a & b | ~a & c) + k[13] - 40341101 | 0;
d = (d << 12 | d >>> 20) + a | 0;
c += (d & a | ~d & b) + k[14] - 1502002290 | 0;
c = (c << 17 | c >>> 15) + d | 0;
b += (c & d | ~c & a) + k[15] + 1236535329 | 0;
b = (b << 22 | b >>> 10) + c | 0;
a += (b & d | c & ~d) + k[1] - 165796510 | 0;
a = (a << 5 | a >>> 27) + b | 0;
d += (a & c | b & ~c) + k[6] - 1069501632 | 0;
d = (d << 9 | d >>> 23) + a | 0;
c += (d & b | a & ~b) + k[11] + 643717713 | 0;
c = (c << 14 | c >>> 18) + d | 0;
b += (c & a | d & ~a) + k[0] - 373897302 | 0;
b = (b << 20 | b >>> 12) + c | 0;
a += (b & d | c & ~d) + k[5] - 701558691 | 0;
a = (a << 5 | a >>> 27) + b | 0;
d += (a & c | b & ~c) + k[10] + 38016083 | 0;
d = (d << 9 | d >>> 23) + a | 0;
c += (d & b | a & ~b) + k[15] - 660478335 | 0;
c = (c << 14 | c >>> 18) + d | 0;
b += (c & a | d & ~a) + k[4] - 405537848 | 0;
b = (b << 20 | b >>> 12) + c | 0;
a += (b & d | c & ~d) + k[9] + 568446438 | 0;
a = (a << 5 | a >>> 27) + b | 0;
d += (a & c | b & ~c) + k[14] - 1019803690 | 0;
d = (d << 9 | d >>> 23) + a | 0;
c += (d & b | a & ~b) + k[3] - 187363961 | 0;
c = (c << 14 | c >>> 18) + d | 0;
b += (c & a | d & ~a) + k[8] + 1163531501 | 0;
b = (b << 20 | b >>> 12) + c | 0;
a += (b & d | c & ~d) + k[13] - 1444681467 | 0;
a = (a << 5 | a >>> 27) + b | 0;
d += (a & c | b & ~c) + k[2] - 51403784 | 0;
d = (d << 9 | d >>> 23) + a | 0;
c += (d & b | a & ~b) + k[7] + 1735328473 | 0;
c = (c << 14 | c >>> 18) + d | 0;
b += (c & a | d & ~a) + k[12] - 1926607734 | 0;
b = (b << 20 | b >>> 12) + c | 0;
a += (b ^ c ^ d) + k[5] - 378558 | 0;
a = (a << 4 | a >>> 28) + b | 0;
d += (a ^ b ^ c) + k[8] - 2022574463 | 0;
d = (d << 11 | d >>> 21) + a | 0;
c += (d ^ a ^ b) + k[11] + 1839030562 | 0;
c = (c << 16 | c >>> 16) + d | 0;
b += (c ^ d ^ a) + k[14] - 35309556 | 0;
b = (b << 23 | b >>> 9) + c | 0;
a += (b ^ c ^ d) + k[1] - 1530992060 | 0;
a = (a << 4 | a >>> 28) + b | 0;
d += (a ^ b ^ c) + k[4] + 1272893353 | 0;
d = (d << 11 | d >>> 21) + a | 0;
c += (d ^ a ^ b) + k[7] - 155497632 | 0;
c = (c << 16 | c >>> 16) + d | 0;
b += (c ^ d ^ a) + k[10] - 1094730640 | 0;
b = (b << 23 | b >>> 9) + c | 0;
a += (b ^ c ^ d) + k[13] + 681279174 | 0;
a = (a << 4 | a >>> 28) + b | 0;
d += (a ^ b ^ c) + k[0] - 358537222 | 0;
d = (d << 11 | d >>> 21) + a | 0;
c += (d ^ a ^ b) + k[3] - 722521979 | 0;
c = (c << 16 | c >>> 16) + d | 0;
b += (c ^ d ^ a) + k[6] + 76029189 | 0;
b = (b << 23 | b >>> 9) + c | 0;
a += (b ^ c ^ d) + k[9] - 640364487 | 0;
a = (a << 4 | a >>> 28) + b | 0;
d += (a ^ b ^ c) + k[12] - 421815835 | 0;
d = (d << 11 | d >>> 21) + a | 0;
c += (d ^ a ^ b) + k[15] + 530742520 | 0;
c = (c << 16 | c >>> 16) + d | 0;
b += (c ^ d ^ a) + k[2] - 995338651 | 0;
b = (b << 23 | b >>> 9) + c | 0;
a += (c ^ (b | ~d)) + k[0] - 198630844 | 0;
a = (a << 6 | a >>> 26) + b | 0;
d += (b ^ (a | ~c)) + k[7] + 1126891415 | 0;
d = (d << 10 | d >>> 22) + a | 0;
c += (a ^ (d | ~b)) + k[14] - 1416354905 | 0;
c = (c << 15 | c >>> 17) + d | 0;
b += (d ^ (c | ~a)) + k[5] - 57434055 | 0;
b = (b << 21 |b >>> 11) + c | 0;
a += (c ^ (b | ~d)) + k[12] + 1700485571 | 0;
a = (a << 6 | a >>> 26) + b | 0;
d += (b ^ (a | ~c)) + k[3] - 1894986606 | 0;
d = (d << 10 | d >>> 22) + a | 0;
c += (a ^ (d | ~b)) + k[10] - 1051523 | 0;
c = (c << 15 | c >>> 17) + d | 0;
b += (d ^ (c | ~a)) + k[1] - 2054922799 | 0;
b = (b << 21 |b >>> 11) + c | 0;
a += (c ^ (b | ~d)) + k[8] + 1873313359 | 0;
a = (a << 6 | a >>> 26) + b | 0;
d += (b ^ (a | ~c)) + k[15] - 30611744 | 0;
d = (d << 10 | d >>> 22) + a | 0;
c += (a ^ (d | ~b)) + k[6] - 1560198380 | 0;
c = (c << 15 | c >>> 17) + d | 0;
b += (d ^ (c | ~a)) + k[13] + 1309151649 | 0;
b = (b << 21 |b >>> 11) + c | 0;
a += (c ^ (b | ~d)) + k[4] - 145523070 | 0;
a = (a << 6 | a >>> 26) + b | 0;
d += (b ^ (a | ~c)) + k[11] - 1120210379 | 0;
d = (d << 10 | d >>> 22) + a | 0;
c += (a ^ (d | ~b)) + k[2] + 718787259 | 0;
c = (c << 15 | c >>> 17) + d | 0;
b += (d ^ (c | ~a)) + k[9] - 343485551 | 0;
b = (b << 21 | b >>> 11) + c | 0;
x[0] = a + x[0] | 0;
x[1] = b + x[1] | 0;
x[2] = c + x[2] | 0;
x[3] = d + x[3] | 0;
}
function md5blk(s) {
var md5blks = [],
i; /* Andy King said do it this way. */
for (i = 0; i < 64; i += 4) {
md5blks[i >> 2] = s.charCodeAt(i) + (s.charCodeAt(i + 1) << 8) + (s.charCodeAt(i + 2) << 16) + (s.charCodeAt(i + 3) << 24);
}
return md5blks;
}
function md5blk_array(a) {
var md5blks = [],
i; /* Andy King said do it this way. */
for (i = 0; i < 64; i += 4) {
md5blks[i >> 2] = a[i] + (a[i + 1] << 8) + (a[i + 2] << 16) + (a[i + 3] << 24);
}
return md5blks;
}
function md51(s) {
var n = s.length,
state = [1732584193, -271733879, -1732584194, 271733878],
i,
length,
tail,
tmp,
lo,
hi;
for (i = 64; i <= n; i += 64) {
md5cycle(state, md5blk(s.substring(i - 64, i)));
}
s = s.substring(i - 64);
length = s.length;
tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
for (i = 0; i < length; i += 1) {
tail[i >> 2] |= s.charCodeAt(i) << ((i % 4) << 3);
}
tail[i >> 2] |= 0x80 << ((i % 4) << 3);
if (i > 55) {
md5cycle(state, tail);
for (i = 0; i < 16; i += 1) {
tail[i] = 0;
}
}
// Beware that the final length might not fit in 32 bits so we take care of that
tmp = n * 8;
tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);
lo = parseInt(tmp[2], 16);
hi = parseInt(tmp[1], 16) || 0;
tail[14] = lo;
tail[15] = hi;
md5cycle(state, tail);
return state;
}
function md51_array(a) {
var n = a.length,
state = [1732584193, -271733879, -1732584194, 271733878],
i,
length,
tail,
tmp,
lo,
hi;
for (i = 64; i <= n; i += 64) {
md5cycle(state, md5blk_array(a.subarray(i - 64, i)));
}
// Not sure if it is a bug, however IE10 will always produce a sub array of length 1
// containing the last element of the parent array if the sub array specified starts
// beyond the length of the parent array - weird.
// https://connect.microsoft.com/IE/feedback/details/771452/typed-array-subarray-issue
a = (i - 64) < n ? a.subarray(i - 64) : new Uint8Array(0);
length = a.length;
tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
for (i = 0; i < length; i += 1) {
tail[i >> 2] |= a[i] << ((i % 4) << 3);
}
tail[i >> 2] |= 0x80 << ((i % 4) << 3);
if (i > 55) {
md5cycle(state, tail);
for (i = 0; i < 16; i += 1) {
tail[i] = 0;
}
}
// Beware that the final length might not fit in 32 bits so we take care of that
tmp = n * 8;
tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);
lo = parseInt(tmp[2], 16);
hi = parseInt(tmp[1], 16) || 0;
tail[14] = lo;
tail[15] = hi;
md5cycle(state, tail);
return state;
}
function rhex(n) {
var s = '',
j;
for (j = 0; j < 4; j += 1) {
s += hex_chr[(n >> (j * 8 + 4)) & 0x0F] + hex_chr[(n >> (j * 8)) & 0x0F];
}
return s;
}
function hex(x) {
var i;
for (i = 0; i < x.length; i += 1) {
x[i] = rhex(x[i]);
}
return x.join('');
}
// In some cases the fast add32 function cannot be used..
if (hex(md51('hello')) !== '5d41402abc4b2a76b9719d911017c592') {
add32 = function (x, y) {
var lsw = (x & 0xFFFF) + (y & 0xFFFF),
msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return (msw << 16) | (lsw & 0xFFFF);
};
}
// ---------------------------------------------------
/**
* ArrayBuffer slice polyfill.
*
* @see https://github.com/ttaubert/node-arraybuffer-slice
*/
if (typeof ArrayBuffer !== 'undefined' && !ArrayBuffer.prototype.slice) {
(function () {
function clamp(val, length) {
val = (val | 0) || 0;
if (val < 0) {
return Math.max(val + length, 0);
}
return Math.min(val, length);
}
ArrayBuffer.prototype.slice = function (from, to) {
var length = this.byteLength,
begin = clamp(from, length),
end = length,
num,
target,
targetArray,
sourceArray;
if (to !== undefined) {
end = clamp(to, length);
}
if (begin > end) {
return new ArrayBuffer(0);
}
num = end - begin;
target = new ArrayBuffer(num);
targetArray = new Uint8Array(target);
sourceArray = new Uint8Array(this, begin, num);
targetArray.set(sourceArray);
return target;
};
})();
}
// ---------------------------------------------------
/**
* Helpers.
*/
function toUtf8(str) {
if (/[\u0080-\uFFFF]/.test(str)) {
str = unescape(encodeURIComponent(str));
}
return str;
}
function utf8Str2ArrayBuffer(str, returnUInt8Array) {
var length = str.length,
buff = new ArrayBuffer(length),
arr = new Uint8Array(buff),
i;
for (i = 0; i < length; i += 1) {
arr[i] = str.charCodeAt(i);
}
return returnUInt8Array ? arr : buff;
}
function arrayBuffer2Utf8Str(buff) {
return String.fromCharCode.apply(null, new Uint8Array(buff));
}
function concatenateArrayBuffers(first, second, returnUInt8Array) {
var result = new Uint8Array(first.byteLength + second.byteLength);
result.set(new Uint8Array(first));
result.set(new Uint8Array(second), first.byteLength);
return returnUInt8Array ? result : result.buffer;
}
function hexToBinaryString(hex) {
var bytes = [],
length = hex.length,
x;
for (x = 0; x < length - 1; x += 2) {
bytes.push(parseInt(hex.substr(x, 2), 16));
}
return String.fromCharCode.apply(String, bytes);
}
// ---------------------------------------------------
/**
* SparkMD5 OOP implementation.
*
* Use this class to perform an incremental md5, otherwise use the
* static methods instead.
*/
function SparkMD5() {
// call reset to init the instance
this.reset();
}
/**
* Appends a string.
* A conversion will be applied if an utf8 string is detected.
*
* @param {String} str The string to be appended
*
* @return {SparkMD5} The instance itself
*/
SparkMD5.prototype.append = function (str) {
// Converts the string to utf8 bytes if necessary
// Then append as binary
this.appendBinary(toUtf8(str));
return this;
};
/**
* Appends a binary string.
*
* @param {String} contents The binary string to be appended
*
* @return {SparkMD5} The instance itself
*/
SparkMD5.prototype.appendBinary = function (contents) {
this._buff += contents;
this._length += contents.length;
var length = this._buff.length,
i;
for (i = 64; i <= length; i += 64) {
md5cycle(this._hash, md5blk(this._buff.substring(i - 64, i)));
}
this._buff = this._buff.substring(i - 64);
return this;
};
/**
* Finishes the incremental computation, reseting the internal state and
* returning the result.
*
* @param {Boolean} raw True to get the raw string, false to get the hex string
*
* @return {String} The result
*/
SparkMD5.prototype.end = function (raw) {
var buff = this._buff,
length = buff.length,
i,
tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
ret;
for (i = 0; i < length; i += 1) {
tail[i >> 2] |= buff.charCodeAt(i) << ((i % 4) << 3);
}
this._finish(tail, length);
ret = hex(this._hash);
if (raw) {
ret = hexToBinaryString(ret);
}
this.reset();
return ret;
};
/**
* Resets the internal state of the computation.
*
* @return {SparkMD5} The instance itself
*/
SparkMD5.prototype.reset = function () {
this._buff = '';
this._length = 0;
this._hash = [1732584193, -271733879, -1732584194, 271733878];
return this;
};
/**
* Gets the internal state of the computation.
*
* @return {Object} The state
*/
SparkMD5.prototype.getState = function () {
return {
buff: this._buff,
length: this._length,
hash: this._hash.slice()
};
};
/**
* Gets the internal state of the computation.
*
* @param {Object} state The state
*
* @return {SparkMD5} The instance itself
*/
SparkMD5.prototype.setState = function (state) {
this._buff = state.buff;
this._length = state.length;
this._hash = state.hash;
return this;
};
/**
* Releases memory used by the incremental buffer and other additional
* resources. If you plan to use the instance again, use reset instead.
*/
SparkMD5.prototype.destroy = function () {
delete this._hash;
delete this._buff;
delete this._length;
};
/**
* Finish the final calculation based on the tail.
*
* @param {Array} tail The tail (will be modified)
* @param {Number} length The length of the remaining buffer
*/
SparkMD5.prototype._finish = function (tail, length) {
var i = length,
tmp,
lo,
hi;
tail[i >> 2] |= 0x80 << ((i % 4) << 3);
if (i > 55) {
md5cycle(this._hash, tail);
for (i = 0; i < 16; i += 1) {
tail[i] = 0;
}
}
// Do the final computation based on the tail and length
// Beware that the final length may not fit in 32 bits so we take care of that
tmp = this._length * 8;
tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);
lo = parseInt(tmp[2], 16);
hi = parseInt(tmp[1], 16) || 0;
tail[14] = lo;
tail[15] = hi;
md5cycle(this._hash, tail);
};
/**
* Performs the md5 hash on a string.
* A conversion will be applied if utf8 string is detected.
*
* @param {String} str The string
* @param {Boolean} [raw] True to get the raw string, false to get the hex string
*
* @return {String} The result
*/
SparkMD5.hash = function (str, raw) {
// Converts the string to utf8 bytes if necessary
// Then compute it using the binary function
return SparkMD5.hashBinary(toUtf8(str), raw);
};
/**
* Performs the md5 hash on a binary string.
*
* @param {String} content The binary string
* @param {Boolean} [raw] True to get the raw string, false to get the hex string
*
* @return {String} The result
*/
SparkMD5.hashBinary = function (content, raw) {
var hash = md51(content),
ret = hex(hash);
return raw ? hexToBinaryString(ret) : ret;
};
// ---------------------------------------------------
/**
* SparkMD5 OOP implementation for array buffers.
*
* Use this class to perform an incremental md5 ONLY for array buffers.
*/
SparkMD5.ArrayBuffer = function () {
// call reset to init the instance
this.reset();
};
/**
* Appends an array buffer.
*
* @param {ArrayBuffer} arr The array to be appended
*
* @return {SparkMD5.ArrayBuffer} The instance itself
*/
SparkMD5.ArrayBuffer.prototype.append = function (arr) {
var buff = concatenateArrayBuffers(this._buff.buffer, arr, true),
length = buff.length,
i;
this._length += arr.byteLength;
for (i = 64; i <= length; i += 64) {
md5cycle(this._hash, md5blk_array(buff.subarray(i - 64, i)));
}
this._buff = (i - 64) < length ? new Uint8Array(buff.buffer.slice(i - 64)) : new Uint8Array(0);
return this;
};
/**
* Finishes the incremental computation, reseting the internal state and
* returning the result.
*
* @param {Boolean} raw True to get the raw string, false to get the hex string
*
* @return {String} The result
*/
SparkMD5.ArrayBuffer.prototype.end = function (raw) {
var buff = this._buff,
length = buff.length,
tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
i,
ret;
for (i = 0; i < length; i += 1) {
tail[i >> 2] |= buff[i] << ((i % 4) << 3);
}
this._finish(tail, length);
ret = hex(this._hash);
if (raw) {
ret = hexToBinaryString(ret);
}
this.reset();
return ret;
};
/**
* Resets the internal state of the computation.
*
* @return {SparkMD5.ArrayBuffer} The instance itself
*/
SparkMD5.ArrayBuffer.prototype.reset = function () {
this._buff = new Uint8Array(0);
this._length = 0;
this._hash = [1732584193, -271733879, -1732584194, 271733878];
return this;
};
/**
* Gets the internal state of the computation.
*
* @return {Object} The state
*/
SparkMD5.ArrayBuffer.prototype.getState = function () {
var state = SparkMD5.prototype.getState.call(this);
// Convert buffer to a string
state.buff = arrayBuffer2Utf8Str(state.buff);
return state;
};
/**
* Gets the internal state of the computation.
*
* @param {Object} state The state
*
* @return {SparkMD5.ArrayBuffer} The instance itself
*/
SparkMD5.ArrayBuffer.prototype.setState = function (state) {
// Convert string to buffer
state.buff = utf8Str2ArrayBuffer(state.buff, true);
return SparkMD5.prototype.setState.call(this, state);
};
SparkMD5.ArrayBuffer.prototype.destroy = SparkMD5.prototype.destroy;
SparkMD5.ArrayBuffer.prototype._finish = SparkMD5.prototype._finish;
/**
* Performs the md5 hash on an array buffer.
*
* @param {ArrayBuffer} arr The array buffer
* @param {Boolean} [raw] True to get the raw string, false to get the hex one
*
* @return {String} The result
*/
SparkMD5.ArrayBuffer.hash = function (arr, raw) {
var hash = md51_array(new Uint8Array(arr)),
ret = hex(hash);
return raw ? hexToBinaryString(ret) : ret;
};
return SparkMD5;
}));
File diff suppressed because one or more lines are too long
+4 -11
View File
@@ -44,8 +44,6 @@ tbquire.config({
baseUrl: _win.uri + '/js/runtime',
urlArgs: 'ver=' + _win.ver,
paths: {
'jquery.cookie' : 'libs/jquery.cookie.min',
'lazysizes' : 'libs/lazysizes.min',
'clipboard' : 'libs/clipboard.min',
'swiper' : 'libs/swiper.min',
'dplayer' : '../../widgets/third-party/DPlayer.min',
@@ -54,19 +52,14 @@ tbquire.config({
'flv' : '../../widgets/third-party/flv.min',
'grade' : 'libs/grade.min',
'qrcode' : 'libs/jquery.qrcode.min',
'sortablejs' : 'libs/Sortable.min',
'spark-md5' : 'libs/spark-md5.min',
'translate' : 'libs/translate.min',
'waterfall' : 'waterfall.min',
'enlighterjs' : 'enlighter/enlighterjs.min',
'mini-touch' : 'mini-touch.min',
'editextend' : 'editextend.min',
'petite-vue' : 'libs/petite-vue.iife',
'svg-icon' : 'svg-icon',
'imgbox' : 'imgbox.min',
'tilt' : '../../widgets/third-party/vanilla-tilt.min',
'weixin-share' : 'weixin-share.min',
'weixin-sdk' : ['//res.wx.qq.com/open/js/jweixin-1.6.0','//res2.wx.qq.com/open/js/jweixin-1.6.0'],
'shop—main' : _win.uri+'/inc/functions/shop/assets/js/main.min',
'svg-icon' : 'svg-icon',
'main' : 'main.min'
}
})
tbquire(['main']);
+26 -25
View File
@@ -1872,7 +1872,7 @@ function post_ajax(_this, con, jcon, item, loader, pag, next, trigger, replace,
}
swiper_tab_AutoHeight($con);
window.AksrtFrontend.rehydrate($con[0], 'ajax');
auto_fun();
},
});
return !1;
@@ -1884,7 +1884,7 @@ _win.bd.on('click', '[remote-box]', function () {
if (remote) {
jQuery.post(remote, null, function (data) {
_this.html(data).removeAttr('remote-box');
window.AksrtFrontend.rehydrate(_this[0], 'ajax');
auto_fun();
_this.trigger('aksrt:remote-loaded');
});
}
@@ -2176,7 +2176,7 @@ _win.bd.on('show.bs.modal loaded.bs.modal', '.modal:not(.flex)', function () {
});
_win.bd.on('show.bs.modal loaded.bs.modal', '.modal', function () {
window.AksrtFrontend.rehydrate(this, 'modal');
auto_fun();
});
_win.modal_z_index = 1050;
@@ -2420,9 +2420,7 @@ function z_auto() {
}
}
window.auto_fun = debounce(function (root) {
window.AksrtFrontend.rehydrate(root && root.nodeType ? root : document, 'ajax');
}, 100);
window.auto_fun = debounce(z_auto_fun, 100);
function z_auto_fun() {
jQuery(document).trigger('auto_fun');
@@ -2435,15 +2433,12 @@ function z_auto_fun() {
//可复制
jQuery('.cloneable').cloneable();
//倒计时
jQuery('[data-countdown]').countdown();
auto_maxHeight();
//兼容性图片懒加载
jQuery('img[data-src]:not(.lazyload,.lazyloaded,.lazyloading,.swiper-lazy)').addClass('lazyload');
//瀑布流布局,暂未启用,要抖动,且需要修改div结构
/**
tbquire(['waterfall'], function () {
jQuery('.waterfall-box').waterfall();
});
*/
/* 提示工具*/
jQuery("[data-toggle='tooltip']").tooltip({
@@ -2496,6 +2491,9 @@ function z_auto_fun() {
theme: _win.highlight_zt,
});
});
//图片灯箱
_win.imgbox && jQuery('.alone-imgbox-img,a[data-imgbox],.comment-content .box-img,.wp-posts-content img,.imgbox-container').length && tbquire(['imgbox']);
}
//页面滚动监听函数
@@ -3087,6 +3085,10 @@ _win.bd.on('input focus', 'textarea[autoHeight]', function () {
_win.bd.on('click', '.rewards', function () {
jQuery('#rewards-popover').modal('show');
});
//作者页、文章导航、前台编辑、通用模板、微信分享均由 AKSRT 自有脚本按路由入队,
//legacy main 不再通过 tbquire 重复加载同功能的旧模块副本。
//搜索关键词高亮
if (_win.bd.hasClass('search')) {
var val = jQuery('.search-desc-text .search-key').text();
@@ -3497,7 +3499,7 @@ jQuery.fn.AutoSearch = function () {
_this.removeClass(loading);
_remind.html(result.remind || '');
_icon.html(_icon_html);
window.AksrtFrontend.rehydrate(_container[0], 'ajax');
auto_fun();
},
'json'
);
@@ -3874,7 +3876,7 @@ function aksrt_ajax(_this, data, success, noty, no_loading) {
notyf(n.msg, ys);
}
_this.attr('disabled', false).html(_text).trigger('aksrt_ajax.success', n); //完成
_this.attr('disabled', false).html(_text).trigger('zib_ajax.success', n); //完成
jQuery.isFunction(success) && success(n, _this, data);
if (n.hide_modal) {
@@ -3893,7 +3895,7 @@ function aksrt_ajax(_this, data, success, noty, no_loading) {
}
//AJAX执行完成后自动切换到下一个tab
_win.bd.on('aksrt_ajax.success', '[next-tab]', function (e, n) {
_win.bd.on('zib_ajax.success', '[next-tab]', function (e, n) {
var _next = jQuery(this).attr('next-tab');
if (_next && n && !n.error) {
jQuery('a[href="#' + _next + '"]').tab('show');
@@ -3946,6 +3948,12 @@ function posts_limit_height() {
}
}
auto_fun();
thumb_dplayer(_wid > 640 ? '.posts-item .item-thumbnail,.forum-lists-cover' : '.posts-item,.forum-posts', '.video-thumb-box[video-url]');
//页面加载之后自动点击
jQuery('[load-click]').attr('no-scroll', true).click();
//图片延迟懒加载-ias自动加载
jQuery(document).on('lazybeforeunveil', function (e) {
var _this = jQuery(e.target);
@@ -4524,7 +4532,7 @@ _win.bd.on('click', '.customize-preview-widget-edit', function (e) {
});
//页面加载完毕之后加载的函数
function initLegacyDocumentReady() {
jQuery(document).ready(function () {
setTimeout(function () {
//页面加载完毕之后再延迟两秒加载的函数
@@ -4670,7 +4678,8 @@ function initLegacyDocumentReady() {
yiyan_nr(jQuery(this));
});
/*文章目录*/
/*文章目录由 AKSRT section-navs 按需入队,legacy 不再重复加载。*/
//手势控制
jQuery('[mini-touch]').each(function () {
var _this = jQuery(this);
@@ -4687,12 +4696,4 @@ function initLegacyDocumentReady() {
},
});
});
}
window.AksrtFrontend.register('aksrt-legacy-main', function (root, reason) {
z_auto_fun();
if (reason !== 'init') return;
initLegacyDocumentReady();
thumb_dplayer(_wid > 640 ? '.posts-item .item-thumbnail,.forum-lists-cover' : '.posts-item,.forum-posts', '.video-thumb-box[video-url]');
jQuery('[load-click]').attr('no-scroll', true).click();
});
+1 -1
View File
File diff suppressed because one or more lines are too long
-122
View File
@@ -1,122 +0,0 @@
'use strict';
jQuery.fn.minitouch = function (options) {
// 合并默认选项和用户提供的选项
options = jQuery.extend({
direction: 'bottom',
selector: '',
start_selector: '',
depreciation: 50,
stop: false,
onStart: false,
onIng: false,
onEnd: false,
inEnd: false,
}, options);
var $element = jQuery(this); // 当前元素
var isStop = false; // 是否停止拖动
var threshold = options.depreciation; // 拖动阈值
var initialX = 0, initialY = 0; // 初始触摸坐标
var finalX = 0, finalY = 0; // 结束触摸坐标
var angle = 0; // 触摸角度
var deltaX = 0, deltaY = 0; // 移动距离
var isDragging = false; // 是否正在拖动
// CSS过渡效果函数
var applyCssTransition = function (element, translateX, translateY, isDragging, cursorStyle) {
var transformValue, cssProperties = {};
if (isDragging) {
translateX += "px";
translateY += "px";
transformValue = "translate3D(" + translateX + "," + translateY + " , 0)";
var prefix = getCssTransitionSupport();
cssProperties[prefix + "transform"] = transformValue;
cssProperties[prefix + "transition"] = prefix + "transform 0s linear";
cssProperties["cursor"] = cursorStyle;
} else {
cssProperties[getCssTransitionSupport() + "transform"] = "";
cssProperties[getCssTransitionSupport() + "transition"] = "";
}
element.css(cssProperties);
}
// 检测CSS过渡支持
var getCssTransitionSupport = function () {
var style = document.body.style || document.documentElement.style;
return style.WebkitTransition ? "-webkit-" :
style.MozTransition ? "-moz-" :
style.OTransition ? "-o-" :
style.transition ? "" :
void 0;
}
var touchSelector = options.start_selector || options.selector;
// 触摸开始事件
$element.on('touchstart pointerdown MSPointerDown', touchSelector, function (event) {
initialX = initialY = finalX = finalY = angle = deltaX = deltaY = 0;
initialX = event.originalEvent.pageX || event.originalEvent.touches[0].pageX;
initialY = event.originalEvent.pageY || event.originalEvent.touches[0].pageY;
isDragging = true;
// 兼容swiper
if (jQuery(event.target).parentsUntil(touchSelector, '.swiper-container,.scroll-x').length) {
isDragging = false;
}
})
// 触摸移动事件
.on("touchmove pointermove MSPointerMove", touchSelector, function (event) {
var $moveElement = options.start_selector ?
(options.selector ? $element.find(options.selector) : $element.find(options.start_selector)) :
jQuery(this);
if (jQuery.isFunction(options.stop)) {
isStop = options.stop($element, $moveElement, initialX, initialY);
}
if (isDragging && !isStop) {
finalX = event.originalEvent.pageX || event.originalEvent.touches[0].pageX;
finalY = event.originalEvent.pageY || event.originalEvent.touches[0].pageY;
deltaX = finalX - initialX;
deltaY = finalY - initialY;
angle = 180 * Math.atan2(deltaY, deltaX) / Math.PI;
// 根据方向限制移动距离
if (options.direction === "right") {
deltaY = 0;
deltaX = (angle > -40 && angle < 40 && deltaX > 0) ? deltaX : 0;
} else if (options.direction === "left") {
deltaY = 0;
deltaX = (angle > 150 || angle < -150) && deltaX < 0 ? deltaX : 0;
} else if (options.direction === "top") {
deltaX = 0;
deltaY = (angle > -130 && angle < -50 && deltaY < 0) ? deltaY : 0;
} else if (options.direction === "bottom") {
deltaX = 0;
deltaY = (angle > 50 && angle < 130 && deltaY > 0) ? deltaY : 0;
}
if (deltaX !== 0 || deltaY !== 0) {
event.preventDefault ? event.preventDefault() : event.returnValue = false;
applyCssTransition($moveElement, deltaX, deltaY, isDragging, 'grab');
jQuery.isFunction(options.onIng) && options.onIng($element, $moveElement, deltaX, deltaY);
}
}
})
// 触摸结束事件
.on('touchend touchcancel pointerup MSPointerUp', touchSelector, function () {
var $moveElement = options.start_selector ?
(options.selector ? $element.find(options.selector) : $element.find(options.start_selector)) :
jQuery(this);
if (isDragging && !isStop) {
applyCssTransition($moveElement, 0, 0, "null", '');
jQuery.isFunction(options.inEnd) && options.inEnd($element, $moveElement, deltaX, deltaY);
if (Math.abs(deltaX) > threshold || Math.abs(deltaY) > threshold) {
jQuery.isFunction(options.onEnd) && options.onEnd($element, $moveElement, deltaX, deltaY);
}
initialX = initialY = finalX = finalY = angle = deltaX = deltaY = 0;
isDragging = false;
}
});
}
-1
View File
@@ -1 +0,0 @@
"use strict";jQuery.fn.minitouch=function(t){t=jQuery.extend({direction:"bottom",selector:"",start_selector:"",depreciation:50,stop:!1,onStart:!1,onIng:!1,onEnd:!1,inEnd:!1},t);var n=jQuery(this),e=!1,o=t.depreciation,i=0,r=0,a=0,s=0,c=0,l=0,u=0,d=!1,p=function(t,n,e,o,i){var r,a={};if(o){n+="px",e+="px",r="translate3D("+n+","+e+" , 0)";var s=g();a[s+"transform"]=r,a[s+"transition"]=s+"transform 0s linear",a.cursor=i}else a[g()+"transform"]="",a[g()+"transition"]="";t.css(a)},g=function(){var t=document.body.style||document.documentElement.style;return t.WebkitTransition?"-webkit-":t.MozTransition?"-moz-":t.OTransition?"-o-":t.transition?"":void 0},v=t.start_selector||t.selector;n.on("touchstart pointerdown MSPointerDown",v,function(t){i=r=a=s=c=l=u=0,i=t.originalEvent.pageX||t.originalEvent.touches[0].pageX,r=t.originalEvent.pageY||t.originalEvent.touches[0].pageY,d=!0,jQuery(t.target).parentsUntil(v,".swiper-container,.scroll-x").length&&(d=!1)}).on("touchmove pointermove MSPointerMove",v,function(o){var g=t.start_selector?t.selector?n.find(t.selector):n.find(t.start_selector):jQuery(this);jQuery.isFunction(t.stop)&&(e=t.stop(n,g,i,r)),d&&!e&&(a=o.originalEvent.pageX||o.originalEvent.touches[0].pageX,s=o.originalEvent.pageY||o.originalEvent.touches[0].pageY,l=a-i,u=s-r,c=180*Math.atan2(u,l)/Math.PI,"right"===t.direction?(u=0,l=c>-40&&c<40&&l>0?l:0):"left"===t.direction?(u=0,l=(c>150||c<-150)&&l<0?l:0):"top"===t.direction?(l=0,u=c>-130&&c<-50&&u<0?u:0):"bottom"===t.direction&&(l=0,u=c>50&&c<130&&u>0?u:0),0===l&&0===u||(o.preventDefault?o.preventDefault():o.returnValue=!1,p(g,l,u,d,"grab"),jQuery.isFunction(t.onIng)&&t.onIng(n,g,l,u)))}).on("touchend touchcancel pointerup MSPointerUp",v,function(){var g=t.start_selector?t.selector?n.find(t.selector):n.find(t.start_selector):jQuery(this);d&&!e&&(p(g,0,0,"null",""),jQuery.isFunction(t.inEnd)&&t.inEnd(n,g,l,u),(Math.abs(l)>o||Math.abs(u)>o)&&jQuery.isFunction(t.onEnd)&&t.onEnd(n,g,l,u),i=r=a=s=c=l=u=0,d=!1)})};
-289
View File
@@ -1,289 +0,0 @@
'use strict';
function miniupload() {
var _body = jQuery('body');
var input_selector = '[aksrtupload="image_upload"]';
var submit_selector = '[aksrtupload="submit"]';
var form_selector = '.form-upload,.mini-upload,form';
var add_html = '<div class="add"></div>';
var add_selector = '.add';
var mini_file = {};
var pre_html;
_body.on('change', input_selector, function (e) {
var _this = jQuery(this);
var files = this.files || e.dataTransfer.files;
var form = jQuery(_this.parents(form_selector)[0]);
var size_max = _this.attr('size_max') || Number(_win.upload_img_size) || 3;
var pre_selector = _this.attr('data-preview') || '.preview';
var pre = form.find(pre_selector);
pre_html = pre.html();
var accept = _this.attr('accept'); //允许上传的文件类型
var multiple = _this.attr('multiple'); //是否允许多选
var multiple_max = _this.attr('multiple_max'); //多选最多允许几个
var accept_yanz = false;
if (-1 !== accept.indexOf('image')) {
accept_yanz = 'image';
}
if (-1 !== accept.indexOf('vedio')) {
accept_yanz = 'vedio';
}
var upload_id = _this.attr('upload_id');
//设置唯一ID标识
if (!_this.attr('upload_id')) {
upload_id = parseInt((Math.random() + 1) * Math.pow(10, 4));
_this.attr('upload_id', upload_id);
}
if (!mini_file[upload_id]) {
mini_file[upload_id] = [];
}
jQuery.each(files, function (key, val) {
var name = val.name;
if (accept_yanz && -1 == val.type.indexOf(accept_yanz)) {
//如果限制文件格式
notyf(aksrt_sprintf('upload_format_error', name), 'danger'), _this.val('');
} else if (size_max && val.size > size_max * 1048567) {
//限制文件大小
notyf(aksrt_sprintf('upload_size_exceeded', name, size_max), 'danger');
} else if (!pre.find('[preview-name="' + name + '"]').length) {
//不允许重复文件
mini_file[upload_id].push(val);
}
});
var a_file = [];
var ii = 1;
var empty = false;
jQuery.each(mini_file[upload_id], function (key, val) {
if (multiple_max && multiple_max < ii) {
//限制文件数量
notyf(aksrt_sprintf('upload_count_exceeded', multiple_max), 'danger');
return false;
} else {
ii++;
a_file.push(val);
ToB64(val, function (e) {
var img = '<img class="fit-cover" preview-name="' + val.name + '" src="' + e + '">';
if (multiple) {
if (!empty) {
pre.html('');
empty = true;
}
var cloce = '<div class="preview-remove" upload-id="' + upload_id + '" file-key="' + jQuery.inArray(val, a_file) + '"><svg class="ic-close" aria-hidden="true"><use xlink:href="#icon-close"></use></svg></div>';
img = '<div class="preview-item">' + img + cloce + '</div>';
pre.append(img).find(add_selector).remove();
if (multiple_max && multiple_max >= ii) {
pre.append(add_html);
}
} else {
pre.html(img);
}
});
}
});
mini_file[upload_id] = a_file;
form.find('[auto-submit]').click();
});
_body.on('click', '.preview-remove', function () {
var _this = jQuery(this);
var file_key = _this.attr('file-key');
var upload_id = _this.attr('upload-id');
_this.parent().animate(
{
width: 0,
},
200,
'swing',
function () {
var pre = jQuery(this).parent();
jQuery(this).remove();
mini_file[upload_id].splice(file_key, 1);
if (!pre.find(add_selector).length) {
pre.append(add_html);
}
}
);
return false;
});
_body.on('click', '.preview ' + add_selector, function () {
var _this = jQuery(this);
var form = jQuery(_this.parents(form_selector)[0]);
form.find(input_selector).click();
});
//提交表单
_body.on('click', submit_selector, function (e) {
var _this = jQuery(this);
if (_this.attr('disabled')) {
return false;
}
if (e.preventDefault) e.preventDefault();
else e.returnValue = false;
var _text = _this.html();
var form = jQuery(_this.parents(form_selector)[0]);
var _input = form.find(input_selector);
var formData = new FormData();
//循环插入文件
var is_files = _this.attr('aksrtupload-nomust');
_input.each(function () {
var _this = jQuery(this);
var upload_id = _this.attr('upload_id');
if (upload_id && mini_file[upload_id]) {
var ii = 0;
var tag = _this.attr('data-tag') || 'file';
jQuery.each(mini_file[upload_id], function (key, val) {
var append_tag = ii ? tag + '_' + ii : tag;
formData.append(append_tag, val, val.name);
ii++;
});
if (ii > 1) {
formData.append(tag + '_file_count', ii);
}
is_files = ii;
}
});
//必须选择图片判断
if (!is_files) return notyf(aksrt__('upload_select_first'), 'danger');
//添加其它数据
var serializeObject = form.serializeObject();
jQuery.each(serializeObject, function (key, val) {
formData.append(key, val);
});
//循环插入_POST内容
form.find('[data-name]').each(function () {
var _th = jQuery(this);
var n = _th.attr('data-name');
var v = _th.val() || _th.attr('data-value');
if (v === undefined) {
v = '';
}
if (formData.get(n) === null) {
formData.append(n, v);
}
});
/**
for (var [a, b] of formData.entries()) {
console.log(a, b);
} */
var miniuploaded = function (no_preview_reset) {
_this.attr('disabled', false).html(_text);
_input
.attr('disabled', false)
.val('')
.each(function () {
var _this = jQuery(this);
var upload_id = _this.attr('upload_id');
if (upload_id && mini_file[upload_id]) {
mini_file[upload_id] = [];
}
});
if (!no_preview_reset && pre_html) {
form.find('.preview').html(pre_html);
}
};
var notyf_id = 'miniupload_ajax';
notyf(aksrt__('processing_wait'), 'load', '', notyf_id);
_this.attr('disabled', true).html('<span class="miniupload-ing"><i class="loading mr3 c-white"></i><span class="loading-text c-white">' + aksrt__('uploading') + '<count class="px12 ml3"></count></span><div class="progress progress-striped active"><div class="progress-bar progress-bar-success" role="progressbar" style="width:0;"></div></div></span>');
_input.attr('disabled', true);
jQuery.ajax({
url: _win.ajax_url,
type: 'POST',
data: formData,
// 告诉jQuery不要去处理发送的数据
processData: false,
cache: false,
// 告诉jQuery不要去设置Content-Type请求头
contentType: false,
dataType: 'json',
error: function (n) {
var _msg = aksrt_sprintf('ajax_error', n.status, n.statusText);
if (aksrt_is_fatal_error_response(n.responseText)) {
_msg = aksrt__('ajax_fatal_error');
}
notyf(_msg, 'danger', '', notyf_id);
miniuploaded();
},
xhr: jqXhr(function (e) {
var percent = Math.round((e.loaded / e.total) * 100);
_this.find('count').html(percent + '%');
percent >= 100 && _this.find('.loading-text').html(aksrt__('upload_processing') + ' ...');
form.find('.progress .progress-bar').css('width', percent + '%');
}),
success: function (n) {
var ys = n.ys ? n.ys : n.error ? 'danger' : '';
notyf(n.msg || aksrt__('operation_success'), ys, '', notyf_id);
miniuploaded(n.no_preview_reset);
if (n.hide_modal) {
jQuery(_this.parents('.modal')[0]).modal('hide');
}
if (n.url && n.replace_img) {
jQuery('img' + n.replace_img).attr('src', n.url);
}
if (n.reload) {
if (n.goto) {
window.location.href = n.goto;
window.location.reload;
} else {
window.location.reload();
}
}
_this.trigger('miniuploaded', n, form);
},
});
});
//图片转Base64
function ToB64(e, n) {
if ('undefined' == typeof FileReader) return notyf(aksrt__('upload_unsupported'), 'danger');
var r = new FileReader();
r.readAsDataURL(e),
(r.onload = function (e) {
n && n(e.target.result);
});
}
//绑定上传进度
function jqXhr(fun) {
jqXhr.onprogress = fun;
//使用闭包实现监听绑
return function () {
//通过jQuery.ajaxSettings.xhr();获得XMLHttpRequest对象
var xhr = jQuery.ajaxSettings.xhr();
//判断监听函数是否为函数
if (typeof jqXhr.onprogress !== 'function') return xhr;
//如果有监听函数并且xhr对象支持绑定时就把监听函数绑定上去
if (jqXhr.onprogress && xhr.upload) {
xhr.upload.onprogress = jqXhr.onprogress;
}
return xhr;
};
}
}
if (!_win.is_miniupload) {
miniupload();
_win.is_miniupload = true;
}
File diff suppressed because one or more lines are too long
-4
View File
@@ -1,4 +0,0 @@
/**延迟加载函数 */
setTimeout(function () {
jQuery(".admin-set-page .admin-set-info").fadeOut(1e3);
}, 2000);
-1
View File
@@ -1 +0,0 @@
setTimeout(function(){jQuery(".admin-set-page .admin-set-info").fadeOut(1e3)},2e3);
-130
View File
@@ -1,130 +0,0 @@
//文档导航页面
jQuery('.document-search form').submit(function () {
var _this = jQuery(this);
var _search = jQuery('.document-search');
var search = _this.find('[name="s"]').val();
if (!search.length) {
return notyf(aksrt__('search_enter_keyword'), 'warning'), !1;
}
if (search.length < 2) {
return notyf(aksrt__('search_keyword_short'), 'warning'), !1;
}
_search.addClass('is-loading');
var data = {
search: search,
};
jQuery('.cat-load').removeClass('is-loading active');
return document_ajax(_search, data), !1;
});
_win.bd.on('click', '.cat-load', function () {
jQuery('.cat-load').removeClass('is-loading active');
var _this = jQuery(this);
_this.addClass('is-loading active');
var data = {
cat_id: _this.attr('cat-id'),
};
return document_ajax(_this, data), !1;
});
_win.bd.on('click', '.document-search .search_keywords', function () {
var _this = jQuery(this);
var text = _this.text();
jQuery('.document-search form [name="s"]').val(text).trigger('input');
return jQuery('.document-search form').submit(), !1;
});
//翻页
_win.bd.on('click', '.document-nav-container .pagenav a', function () {
var _this = jQuery(this);
if (_this.hasClass('pag-jump')) {
_this.addClass('ajax-next');
return;
}
return document_ajax(_this, {}, _this.attr('href')), !1;
});
function document_ajax(_this, data, ajax_url) {
var container = jQuery('.document-nav-container').addClass('is-loading');
data.one_cat = container.attr('one-cat');
data.action = 'documentnav_posts';
ajax_url = ajax_url || _win.ajax_url;
jQuery.ajax({
type: 'POST',
url: ajax_url,
data: data,
dataType: 'json',
error: function (n) {
var _msg = aksrt_sprintf('ajax_error', n.status, n.statusText);
if (aksrt_is_fatal_error_response(n.responseText)) {
_msg = aksrt__('ajax_fatal_error');
}
notyf(_msg, 'danger');
},
success: function (n) {
if (n.error || !n.html) {
notyf(aksrt__('ajax_retry_failed'), 'danger');
}
n.html && container.html(n.html);
n.history_search && jQuery('.history-search>div').html(n.history_search);
setTimeout(function () {
container.removeClass('is-loading');
}, 20);
setTimeout(function () {
_this.removeClass('is-loading');
}, 300);
},
});
}
//前台投稿
_win.bd.on('click', '.new-posts-submit', function () {
var _this = jQuery(this),
type = _this.attr('action'),
form = _this.parents('form'),
data = form.serializeObject();
data.action = type;
data.post_content = tinyMCE.activeEditor.getContent();
var featured = jQuery('.featured-edit');
if (featured.length) {
var featured_data = featured.data('featured_data');
data.featured_data = featured_data ? featured_data.data : false;
}
aksrt_ajax(_this, data, function (n) {
n.url && jQuery('.view-btn').html('<a target="_blank" href="' + n.url + '" class="but c-blue"><i class="fa far fa-file-alt"></i> ' + aksrt__('preview_post') + '</a>');
n.time && jQuery('.modified-time').html('<span class="badg">' + aksrt__('last_saved') + n.time + '</div>');
n.ok && jQuery('.form-control').val('');
n.singin && jQuery('.signin-loader:first').click();
n.posts_id && form.find('input[name="posts_id"]').val(n.posts_id);
window.post_is_save = true;
if (n.open_url) {
window.location.href = n.open_url;
window.location.reload;
}
});
});
//链接列表页面模板
_win.bd.on('click', '.link-nav-box ul li a', function () {
var _href = jQuery(jQuery(this).attr('href'));
scrollTopTo(_href);
return false;
});
if (jQuery('.link-nav-box').length) {
_win.bd.scrollspy({
target: '.link-nav-box',
offset: 105,
});
if (_wid < 769) {
_win.bd.on('activate.bs.scrollspy', '.link-nav-box .nav li', function () {
jQuery(this).closest('.nav').Tabcenter();
});
}
}
-1
View File
@@ -1 +0,0 @@
function document_ajax(a,t,n){var i=jQuery(".document-nav-container").addClass("is-loading");t.one_cat=i.attr("one-cat"),t.action="documentnav_posts",n=n||_win.ajax_url,jQuery.ajax({type:"POST",url:n,data:t,dataType:"json",error:function(a){var t=aksrt_sprintf("ajax_error",a.status,a.statusText);aksrt_is_fatal_error_response(a.responseText)&&(t=aksrt__("ajax_fatal_error")),notyf(t,"danger")},success:function(t){!t.error&&t.html||notyf(aksrt__("ajax_retry_failed"),"danger"),t.html&&i.html(t.html),t.history_search&&jQuery(".history-search>div").html(t.history_search),setTimeout(function(){i.removeClass("is-loading")},20),setTimeout(function(){a.removeClass("is-loading")},300)}})}jQuery(".document-search form").submit(function(){var a=jQuery(this),t=jQuery(".document-search"),n=a.find('[name="s"]').val();if(!n.length)return notyf(aksrt__("search_enter_keyword"),"warning"),!1;if(n.length<2)return notyf(aksrt__("search_keyword_short"),"warning"),!1;t.addClass("is-loading");var i={search:n};return jQuery(".cat-load").removeClass("is-loading active"),document_ajax(t,i),!1}),_win.bd.on("click",".cat-load",function(){jQuery(".cat-load").removeClass("is-loading active");var a=jQuery(this);a.addClass("is-loading active");var t={cat_id:a.attr("cat-id")};return document_ajax(a,t),!1}),_win.bd.on("click",".document-search .search_keywords",function(){var a=jQuery(this),t=a.text();return jQuery('.document-search form [name="s"]').val(t).trigger("input"),jQuery(".document-search form").submit(),!1}),_win.bd.on("click",".document-nav-container .pagenav a",function(){var a=jQuery(this);if(!a.hasClass("pag-jump"))return document_ajax(a,{},a.attr("href")),!1;a.addClass("ajax-next")}),_win.bd.on("click",".new-posts-submit",function(){var a=jQuery(this),t=a.attr("action"),n=a.parents("form"),i=n.serializeObject();i.action=t,i.post_content=tinyMCE.activeEditor.getContent();var e=jQuery(".featured-edit");if(e.length){var o=e.data("featured_data");i.featured_data=!!o&&o.data}aksrt_ajax(a,i,function(a){a.url&&jQuery(".view-btn").html('<a target="_blank" href="'+a.url+'" class="but c-blue"><i class="fa far fa-file-alt"></i> '+aksrt__("preview_post")+"</a>"),a.time&&jQuery(".modified-time").html('<span class="badg">'+aksrt__("last_saved")+a.time+"</div>"),a.ok&&jQuery(".form-control").val(""),a.singin&&jQuery(".signin-loader:first").click(),a.posts_id&&n.find('input[name="posts_id"]').val(a.posts_id),window.post_is_save=!0,a.open_url&&(window.location.href=a.open_url,window.location.reload)})}),_win.bd.on("click",".link-nav-box ul li a",function(){var a=jQuery(jQuery(this).attr("href"));return scrollTopTo(a),!1}),jQuery(".link-nav-box").length&&(_win.bd.scrollspy({target:".link-nav-box",offset:105}),_wid<769&&_win.bd.on("activate.bs.scrollspy",".link-nav-box .nav li",function(){jQuery(this).closest(".nav").Tabcenter()}));
-546
View File
@@ -1,546 +0,0 @@
const poster = (function () {
const DEBUG = 0;
const WIDTH = 768;
const HEIGHT = 1168;
function init(config) {
const $container = document.querySelector(config.selector);
const $wrapper = createDom('div', 'id', 'wrapper');
const $canvas = createDom('canvas', 'id', 'canvas', 'block');
const $day = createDom('canvas', 'id', 'day');
const $date = createDom('canvas', 'id', 'date');
const $title = createDom('canvas', 'id', 'title');
const $content = createDom('canvas', 'id', 'content');
const $tags = createDom('canvas', 'id', 'tags');
const $logo = createDom('canvas', 'id', 'logo');
const $description = createDom('canvas', 'id', 'description');
appendChilds($wrapper, $canvas, $day, $date, $title, $content, $logo, $tags, $description);
$container.appendChild($wrapper);
const date = new Date();
// day
const $weekarray = [aksrt__('week_sun'), aksrt__('week_mon'), aksrt__('week_tue'), aksrt__('week_wed'), aksrt__('week_thu'), aksrt__('week_fri'), aksrt__('week_sat')];
const dayStyle = {
font: '35px Arial',
color: 'rgba(255, 255, 255, 1)',
position: 'left',
};
drawOneline($day, dayStyle, aksrt__('week_prefix') + $weekarray[date.getDay()]);
// date
const dateStyle = {
font: '28px Arial',
color: 'rgba(255, 255, 255, 1)',
position: 'left',
};
drawOneline($date, dateStyle, date.getMonth() + 1 + ' / ' + date.getDate());
// title canvas
const titleStyle = {
font: 'bold 35px Arial',
lineHeight: 1.5,
color: '#424242',
length: 2,
position: 'left',
};
titleStyle.font = (config.titleStyle && config.titleStyle.font) || titleStyle.font;
titleStyle.color = (config.titleStyle && config.titleStyle.color) || titleStyle.color;
titleStyle.position = (config.titleStyle && config.titleStyle.position) || titleStyle.position;
drawMoreLines($title, titleStyle, config.title);
// content canvas
const contentStyle = {
font: '25px Arial',
lineHeight: 1.5,
position: 'left',
color: 'rgba(88, 88, 88, 1)',
};
contentStyle.font = (config.contentStyle && config.contentStyle.font) || contentStyle.font;
contentStyle.color = (config.contentStyle && config.contentStyle.color) || contentStyle.color;
contentStyle.lineHeight = (config.contentStyle && config.contentStyle.lineHeight) || contentStyle.lineHeight;
contentStyle.position = (config.contentStyle && config.contentStyle.position) || contentStyle.position;
drawMoreLines($content, contentStyle, config.content);
// tags
const tagsStyle = {
font: '24px Roboto Slab',
position: 'left',
color: '#fc4e1f',
};
tagsStyle.color = (config.tagsStyle && config.tagsStyle.color) || tagsStyle.color;
drawMoreLines($tags, tagsStyle, config.tags);
// description
const descriptionStyle = {
font: '22px Arial',
color: '#b4b4b4',
lineHeight: 1.2,
position: 'center',
};
drawMoreLines($description, descriptionStyle, config.description);
// background image
const image = new Image();
image.crossOrigin = 'Anonymous';
const logo = new Image();
var logoLoadCount = 0;
logo.crossOrigin = 'Anonymous';
logo.src = config.logo;
logo.onerror = function () {
logoLoadCount++;
if (logoLoadCount < 3) {
logo.src = config.logo;
}
};
const qrcode = new Image();
qrcode.src = config.qrcode;
var loadCount = 0;
const setSrc = function () {
if (loadCount == 0) {
config.banner ? (image.src = config.banner) : (loadCount = 1);
}
if (loadCount == 1) {
config.banner_default ? (image.src = config.banner_default) : (loadCount = 2);
}
if (loadCount == 2) {
image.src = config.banner_spare;
}
onload();
};
const onload = function () {
$canvas.width = WIDTH;
$canvas.height = HEIGHT;
image.onload = function () {
const ctx = $canvas.getContext('2d');
ctx.fillStyle = 'rgba(255, 255, 255, 1)';
ctx.fillRect(0, 0, $canvas.width, $canvas.height);
//绘制顶部主图
var img_height = config.type === 'product' ? $canvas.width : $canvas.height / 2;
const imgRect = coverImg($canvas.width, img_height, image.width, image.height);
ctx.drawImage(image, imgRect.sx, imgRect.sy, imgRect.sWidth, imgRect.sHeight, 0, 0, $canvas.width, img_height);
//绘制顶部日期
ctx.drawImage($day, 0, 35);
ctx.drawImage($date, 0, 85);
//绘制标题竖线
ctx.strokeStyle = '#00a1ff';
ctx.lineWidth = 7;
ctx.beginPath();
ctx.lineCap = 'round';
ctx.moveTo(40, img_height + 38);
ctx.lineTo(40, img_height + 74);
ctx.stroke();
if (config.type === 'product') {
drawTextOverflow(ctx, config.title, $canvas.width, 1, 'bold 35px Arial', '#424242', 50, 20, img_height + 69);
//绘制价格
var price_color = config.is_points ? '#ff6f06' : '#FB3961';
var unit = config.is_points ? aksrt__('points') : aksrt__('currency_yuan');
var price_height = img_height + 69 + 50 + 20;
var price_c, unit_c, original_price_c, original_unit_c;
if (config.is_points) {
price_c = drawTextOverflow(ctx, config.price, $canvas.width, 1, 'bold 40px Arial', price_color, 50, 0, price_height);
unit_c = drawTextOverflow(ctx, unit, $canvas.width, 1, '22px Arial', price_color, 50, 0 + 4 + price_c.width, price_height - 2);
if (config.original_price) {
original_price_c = drawTextOverflow(ctx, config.original_price, $canvas.width - price_c.width - unit_c.width, 1, '25px Arial', '#878787', 50, 8 + price_c.width + unit_c.width, price_height);
original_unit_c = drawTextOverflow(ctx, unit, $canvas.width - price_c.width - unit_c.width, 1, '22px Arial', '#878787', 50, 8 + 2 + price_c.width + unit_c.width + original_price_c.width, price_height - 1);
//绘制划掉原价
ctx.strokeStyle = '#878787';
ctx.lineWidth = 2;
ctx.beginPath();
ctx.lineCap = 'round';
ctx.moveTo(8 + price_c.width + unit_c.width + 42, price_height - 15);
ctx.lineTo(8 + price_c.width + unit_c.width + 42 + original_unit_c.width + original_price_c.width, price_height - 3);
ctx.stroke();
}
} else {
unit_c = drawTextOverflow(ctx, unit, $canvas.width, 1, '26px Arial', price_color, 50, -10, price_height - 1);
price_c = drawTextOverflow(ctx, config.price, $canvas.width, 1, 'bold 40px Arial', price_color, 50, -10 + unit_c.width, price_height);
if (config.original_price) {
original_unit_c = drawTextOverflow(ctx, unit, $canvas.width - price_c.width - unit_c.width, 1, '23px Arial', '#878787', 50, 0 + price_c.width + unit_c.width, price_height - 1);
original_price_c = drawTextOverflow(ctx, config.original_price, $canvas.width - price_c.width - unit_c.width, 1, '25px Arial', '#878787', 50, 0 + price_c.width + unit_c.width + original_unit_c.width, price_height);
//绘制划掉原价
ctx.strokeStyle = '#878787';
ctx.lineWidth = 2;
ctx.beginPath();
ctx.lineCap = 'round';
ctx.moveTo(0 + price_c.width + unit_c.width + 42, price_height - 15);
ctx.lineTo(0 + price_c.width + unit_c.width + 42 + original_unit_c.width + original_price_c.width, price_height - 3);
ctx.stroke();
}
}
//绘制标签
var price_width = price_c.width + unit_c.width + (original_unit_c && original_unit_c.width ? original_unit_c.width : 0) + (original_price_c && original_price_c.width ? original_price_c.width : 0);
var tags_width = $canvas.width - price_width - 20;
if (tags_width > 200) {
drawTextOverflow(ctx, config.tags, tags_width, 1, '25px Arial', '#fc4545', 50, price_width + 50, price_height);
}
} else {
ctx.drawImage($title, 20, img_height + 40);
//绘制标签
ctx.drawImage($tags, 0, img_height + 160);
//绘制内容
ctx.drawImage($content, 0, img_height + 220);
}
//绘制底部logo和二维码
ctx.strokeStyle = 'rgba(122, 122, 122, 0.2)';
ctx.lineWidth = 2;
ctx.rect(30, $canvas.height - 230, $canvas.width - 60, 200);
ctx.stroke();
const logoRect = containImg(80, $canvas.height - 190, 300, 100, logo.width, logo.height);
ctx.drawImage(logo, logoRect.dx, logoRect.dy, logoRect.dWidth, logoRect.dHeight);
ctx.drawImage(qrcode, $canvas.width - 200, $canvas.height - 200, 120, 120);
ctx.drawImage($description, 0, $canvas.height - 60);
const img = new Image();
img.crossOrigin = 'Anonymous';
img.src = $canvas.toDataURL('image/png');
const radio = config.radio || 0.7;
img.width = WIDTH * radio;
img.height = HEIGHT * radio;
img.className = 'loaded-img';
ctx.clearRect(0, 0, $canvas.width, $canvas.height);
$canvas.style.display = 'none';
if ($container.querySelector('.loaded-img')) {
$container.querySelector('.loaded-img').src = img.src;
} else {
$container.appendChild(img);
}
$container.removeChild($wrapper);
$container.classList.add('loaded');
jQuery.isFunction(config.callback) && config.callback($container);
};
image.onerror = function () {
loadCount++;
if (loadCount >= 3) {
return jQuery.isFunction(config.onerror) && config.onerror($container);
}
setSrc();
};
};
setSrc();
}
/**
* canvas多行文本溢出
* @param {Object} context - canvas组件的绘图上下文
* @param {String} text - 文本内容
* @param {Number} maxWidth - 文本最大宽度
* @param {Number} maxRow - 文本最多显示行数
* @param {Number} fontSize - 字体样式
* @param {String} color - 文本颜色
* @param {Number} lineHeight - 文本行高
* @param {Number} x - 文本的x坐标
* @param {Number} y - 文本的y坐标
*/
function drawTextOverflow(context, text, maxWidth, maxRow, font, color, lineHeight, x, y) {
let arr = [];
let temp = '';
let row = [];
maxWidth = maxWidth - 120;
x = x + 38;
text = text.replace(/[\r\n]/g, ''); // 去除回车换行符
arr = text.split('');
context.fillStyle = color;
context.font = font;
if (context.measureText(text).width <= maxWidth) {
row.push(text);
} else {
for (let i = 0; i < arr.length; i++) {
// 超出最大行数且字符有剩余,添加...
if (row.length == maxRow && i < arr.length - 1) {
row[row.length - 1] += '...';
break;
}
// 字符换行计算
if (context.measureText(temp).width < maxWidth) {
temp += arr[i];
// 遍历到最后一位字符
if (i === arr.length - 1) {
row.push(temp);
}
} else {
i--; // 防止字符丢失
row.push(temp);
temp = '';
}
}
}
// 绘制文本
var width = 0;
for (let i = 0; i < row.length; i++) {
width = Math.max(width, context.measureText(row[i]).width);
context.fillText(row[i], x, y + i * lineHeight, maxWidth);
}
return {
width: width,
height: row.length * lineHeight,
};
}
function containImg(sx, sy, box_w, box_h, source_w, source_h) {
var dx = sx,
dy = sy,
dWidth = box_w,
dHeight = box_h;
if (source_w > source_h || (source_w == source_h && box_w < box_h)) {
dHeight = (source_h * dWidth) / source_w;
dy = sy + (box_h - dHeight) / 2;
} else if (source_w < source_h || (source_w == source_h && box_w > box_h)) {
dWidth = (source_w * dHeight) / source_h;
dx = sx + (box_w - dWidth) / 2;
}
return {
dx,
dy,
dWidth,
dHeight,
};
}
function coverImg(box_w, box_h, source_w, source_h) {
var sx = 0,
sy = 0,
sWidth = source_w,
sHeight = source_h;
if (source_w > source_h || (source_w == source_h && box_w < box_h)) {
sWidth = (box_w * sHeight) / box_h;
sx = (source_w - sWidth) / 2;
} else if (source_w < source_h || (source_w == source_h && box_w > box_h)) {
sHeight = (box_h * sWidth) / box_w;
sy = (source_h - sHeight) / 2;
}
return {
sx,
sy,
sWidth,
sHeight,
};
}
function createDom(name, key, value, display = 'none') {
const $dom = document.createElement(name);
$dom.setAttribute(key, value);
$dom.style.display = display;
$dom.width = WIDTH;
return $dom;
}
function appendChilds(parent, ...doms) {
doms.forEach((dom) => {
parent.appendChild(dom);
});
}
function drawOneline(canvas, style, content) {
const ctx = canvas.getContext('2d');
canvas.height = parseInt(style.font.match(/\d+/), 10) + 20;
ctx.font = style.font;
ctx.fillStyle = style.color;
ctx.textBaseline = 'top';
let lineWidth = 0;
let idx = 0;
let truncated = false;
for (let i = 0; i < content.length; i++) {
lineWidth += ctx.measureText(content[i]).width;
if (lineWidth > canvas.width - 60) {
truncated = true;
idx = i;
break;
}
}
let padding = 30;
if (truncated) {
content = content.substring(0, idx);
padding = canvas.width / 2 - lineWidth / 2;
}
if (DEBUG) {
ctx.strokeStyle = '#6fda92';
ctx.strokeRect(0, 0, canvas.width, canvas.height);
}
if (style.position === 'center') {
ctx.textAlign = 'center';
ctx.fillText(content, canvas.width / 2, 2);
} else if (style.position === 'left') {
ctx.fillText(content, padding, 2);
} else {
ctx.textAlign = 'right';
ctx.fillText(content, canvas.width - padding, 2);
}
}
function drawMoreLines(canvas, style, content) {
const ctx = canvas.getContext('2d');
const fontHeight = parseInt(style.font.match(/\d+/), 10);
if (DEBUG) {
ctx.strokeStyle = '#6fda92';
ctx.strokeRect(0, 0, canvas.width, canvas.height);
}
ctx.font = style.font;
ctx.fillStyle = style.color;
ctx.textBaseline = 'top';
ctx.textAlign = 'center';
let alignX = 0;
if (style.position === 'center') {
alignX = canvas.width / 2;
} else if (style.position === 'left') {
ctx.textAlign = 'left';
alignX = 40;
} else {
ctx.textAlign = 'right';
alignX = canvas.width - 40;
}
let lineWidth = 0;
let lastSubStrIndex = 0;
let offsetY = 2;
for (let i = 0; i < content.length; i++) {
lineWidth += ctx.measureText(content[i]).width;
if (lineWidth > canvas.width - 120) {
ctx.fillText(content.substring(lastSubStrIndex, i), alignX, offsetY);
offsetY += fontHeight * style.lineHeight;
lineWidth = 0;
lastSubStrIndex = i;
}
if (i === content.length - 1) {
ctx.fillText(content.substring(lastSubStrIndex, i + 1), alignX, offsetY);
}
}
}
return {
init,
};
})();
jQuery('body').on('click', '[poster-share]', function () {
var _this = jQuery(this);
var _id = _this.attr('poster-share');
var modal_id = 'modal_poster_' + _id;
var modal_selector = '#' + modal_id;
var modal_html =
'<div class="modal fade flex jc" id="' +
modal_id +
'" tabindex="-1" role="dialog" aria-hidden="false">\
<div class="modal-dialog poster-share hover-show" role="document">\
<div class="modal-content" style="height:220px;overflow:hidden">\
<div class="poster-imgbox hover-show">\
</div>\
<div class="flex jc loading-mask absolute main-bg radius8"><div class="loading zts fa-2x"></div><div class="muted-2-color box-body">' + aksrt__('poster_generating') + '</div>\
</div>\
</div>\
<div class="padding-6 abs-center hover-show-con text-center" style="top:auto;"><a type="button" href="javascript:;" class="but cir jb-blue poster-download hide"><i class="fa fas fa-download" aria-hidden="true"></i></a><button data-dismiss="modal" class="but cir jb-yellow ml10"><svg aria-hidden="true" class="icon em12"><use xlink:href="#icon-close"></use></svg></button></div>\
</div>\
</div>';
jQuery('.modal:not(' + modal_selector + ')').modal('hide');
var _modal = jQuery(modal_selector);
if (_modal.length) {
_modal.modal('show');
return false;
}
jQuery('body').append(modal_html);
_modal = jQuery(modal_selector);
_modal.modal('show');
var ajax_data = {
action: 'poster_share_data',
id: _id,
};
function posterDownload(e) {
if (e == null) {
return;
}
_modal
.find('.poster-download')
.attr('href', _modal.find('img').attr('src'))
.attr('download', 'poster_' + _id + '.png')
.removeClass('hide');
var b_height = _modal.find('.poster-imgbox').outerHeight();
_modal.find('.loading-mask').fadeOut(200);
_modal.find('.modal-content').css({
height: b_height,
transition: '.2s',
});
setTimeout(function () {
_modal.find('.modal-content').css({
height: '',
overflow: '',
transition: '',
});
}, 200);
}
aksrt_ajax(
_this,
ajax_data,
function (_poster) {
poster.init({
banner: _poster.banner,
banner_default: _poster.banner_default,
banner_spare: _poster.banner_spare,
selector: modal_selector + ' .poster-imgbox',
title: _poster.title,
content: _poster.content,
logo: _poster.logo,
tags: _poster.tags,
description: _poster.description,
qrcode: _poster.qrcode,
type: _poster.type,
is_points: _poster.is_points,
price: _poster.price,
original_price: _poster.original_price,
onerror: function () {
notyf(aksrt__('poster_load_failed'), 'danger');
},
callback: posterDownload,
});
},
'stop',
true
);
});
File diff suppressed because one or more lines are too long
-108
View File
@@ -1,108 +0,0 @@
//严格模式
'use strict';
function section_navs(selector) {
var navbox_selector = '.posts-nav-box';
var _body = _win.bd;
var nav_class = 'posts-nav-lists';
var nav_selector = '.' + nav_class;
var selector_s = selector + ' h1,' + selector + ' h2,' + selector + ' h3,' + selector + ' h4';
var index = 0;
function autoScrollToTop() {
var hash = window.location.hash;
if (hash && jQuery(hash).length) {
jQuery('a[href="' + hash + '"]').click();
}
}
var add_box = function () {
var navs_lists = GetnavsLists();
if (!navs_lists) return;
jQuery(navbox_selector).each(function () {
var _this = jQuery(this);
var name = _this.attr('data-title') || '';
name = name && '<div class="box-body notop"><div class="title-theme">' + name + '</div></div>';
_this.append(name + '<div class="aksrt-panel"><div class="' + nav_class + ' scroll-y mini-scrollbar list-unstyled"></div></div>');
});
add_lists(navs_lists);
setTimeout(function () {
autoScrollToTop();
}, 20);
};
//设置排除的元素
function isExcludedElement(el) {
return el.hasClass('item-heading') || el.parents('.no-nav').length;
}
function GetnavsLists() {
var navs_lists = '';
jQuery(selector_s).each(function (indexInArray) {
var _this = jQuery(this);
if (!isExcludedElement(_this)) {
var tag = _this.prop('tagName');
var text = _this.text();
var _class = 'n-' + tag;
_class += indexInArray == 1 ? ' active' : '';
index = indexInArray;
_this.attr('id', 'wznav_' + index);
navs_lists += '<li class="' + _class + '"><a class="text-ellipsis" href="#wznav_' + index + '">' + text + '</a></li>';
}
});
return navs_lists;
}
var add_lists = function (navs_lists) {
jQuery(nav_selector).html('<ul class="bl relative nav">' + navs_lists + '</ul>');
_body.on('click', nav_selector + ' a', function () {
var _href = jQuery(jQuery(this).attr('href'));
_href.parents('.panel').each(function () {
var _collapse = jQuery(this).find('.collapse');
if (_collapse.length) {
_collapse.collapse('show');
}
});
jQuery('.read-more-open').click();
scrollTopTo(_href);
return false;
});
_body.scrollspy({
target: nav_selector,
offset: 105,
});
collapse();
};
//显示折叠内容
var collapse = function () {
var find_selector = '.n-H1,.n-H2';
jQuery(nav_selector + ' .bl').each(function () {
var _this = jQuery(this);
if (_this.innerHeight() > 380) {
_this.find(find_selector).each(function () {
var _this = jQuery(this);
var _n_h2 = _this.nextUntil(find_selector);
if (_n_h2.length) {
_n_h2.addClass('yc');
_this.append('<i class="fa fas fa-angle-right nav-toggle-collapse"></i>');
}
});
}
});
_body.on('click', nav_selector + ' .nav-toggle-collapse', function () {
jQuery(this).toggleClass('fa-rotate-90').parent().nextUntil(find_selector).toggleClass('yc');
});
};
if (jQuery(selector_s).length > 2) {
add_box();
}
}
section_navs('[data-nav]');
-1
View File
@@ -1 +0,0 @@
"use strict";function section_navs(t){function n(){var t=window.location.hash;t&&jQuery(t).length&&jQuery('a[href="'+t+'"]').click()}function a(t){return t.hasClass("item-heading")||t.parents(".no-nav").length}function i(){var t="";return jQuery(o).each(function(n){var i=jQuery(this);if(!a(i)){var s=i.prop("tagName"),e=i.text(),l="n-"+s;l+=1==n?" active":"",r=n,i.attr("id","wznav_"+r),t+='<li class="'+l+'"><a class="text-ellipsis" href="#wznav_'+r+'">'+e+"</a></li>"}}),t}var s=".posts-nav-box",e=_win.bd,l="posts-nav-lists",c="."+l,o=t+" h1,"+t+" h2,"+t+" h3,"+t+" h4",r=0,h=function(){var t=i();t&&(jQuery(s).each(function(){var t=jQuery(this),n=t.attr("data-title")||"";n=n&&'<div class="box-body notop"><div class="title-theme">'+n+"</div></div>",t.append(n+'<div class="aksrt-panel"><div class="'+l+' scroll-y mini-scrollbar list-unstyled"></div></div>')}),v(t),setTimeout(function(){n()},20))},v=function(t){jQuery(c).html('<ul class="bl relative nav">'+t+"</ul>"),e.on("click",c+" a",function(){var t=jQuery(jQuery(this).attr("href"));return t.parents(".panel").each(function(){var t=jQuery(this).find(".collapse");t.length&&t.collapse("show")}),jQuery(".read-more-open").click(),scrollTopTo(t),!1}),e.scrollspy({target:c,offset:105}),f()},f=function(){var t=".n-H1,.n-H2";jQuery(c+" .bl").each(function(){var n=jQuery(this);n.innerHeight()>380&&n.find(t).each(function(){var n=jQuery(this),a=n.nextUntil(t);a.length&&(a.addClass("yc"),n.append('<i class="fa fas fa-angle-right nav-toggle-collapse"></i>'))})}),e.on("click",c+" .nav-toggle-collapse",function(){jQuery(this).toggleClass("fa-rotate-90").parent().nextUntil(t).toggleClass("yc")})};jQuery(o).length>2&&h()}section_navs("[data-nav]");
-33
View File
@@ -1,33 +0,0 @@
tbquire(["weixin-sdk"], function () {
var _data = WeChatShareDate;
wx.config({
debug: false,
appId: _data.appId,
timestamp: _data.timestamp,
nonceStr: _data.nonceStr,
signature: _data.signature,
jsApiList: [
'updateTimelineShareData',
'updateAppMessageShareData'
]
});
wx.ready(function () {
var _title = _data.title || document.title;
var _link = _data.url || window.location.href;
var _desc = _data.desc || jQuery('meta[name="description"]').attr('content');
var _img = _data.img;
wx.updateTimelineShareData({
title: _title,
link: _link,
imgUrl: _img
});
wx.updateAppMessageShareData({
title: _title,
desc: _desc,
link: _link,
imgUrl: _img
});
});
});
-1
View File
@@ -1 +0,0 @@
tbquire(["weixin-sdk"],function(){var e=WeChatShareDate;wx.config({debug:!1,appId:e.appId,timestamp:e.timestamp,nonceStr:e.nonceStr,signature:e.signature,jsApiList:["updateTimelineShareData","updateAppMessageShareData"]}),wx.ready(function(){var t=e.title||document.title,a=e.url||window.location.href,i=e.desc||jQuery('meta[name="description"]').attr("content"),n=e.img;wx.updateTimelineShareData({title:t,link:a,imgUrl:n}),wx.updateAppMessageShareData({title:t,desc:i,link:a,imgUrl:n})})});
-837
View File
@@ -1,837 +0,0 @@
console.log('legacy Widget');
(function ($, document) {
function aksrt__(key) {
var map = window.aksrt_widget_set_var && window.aksrt_widget_set_var.i18n;
if (map && Object.prototype.hasOwnProperty.call(map, key)) {
return map[key];
}
return key;
}
/** 带图片上传的小工具 repeater 行(幻灯片 / 友情链接等) */
function buildMediaRepeaterRow(labelPrefix, index, nameAttr, labels) {
var i1 = index + 1;
var titleLabel = labelPrefix + i1 + (labels.title || '-标题:');
var decLabel = labelPrefix + i1 + (labels.dec || '-简介');
var hrefLabel = labelPrefix + i1 + (labels.href || '-链接');
var linkLabel = labelPrefix + i1 + (labels.link || '-图片');
return (
'<div class="widget_ui_slider_g">' +
'<div class="panel"><h4 class="panel-title">' +
labelPrefix +
i1 +
'</h4><div class="panel-conter">' +
'<label>' +
titleLabel +
'<input style="width:100%;" type="text" name="' +
nameAttr +
'[' +
index +
'][title]" value=""></label>' +
'<label>' +
decLabel +
'<input style="width:100%;" type="text" name="' +
nameAttr +
'[' +
index +
'][dec]" value=""></label>' +
'<label>' +
hrefLabel +
'<input style="width:100%;" type="text" name="' +
nameAttr +
'[' +
index +
'][href]" value=""></label>' +
'<div class=""><label>' +
linkLabel +
'<input style="width:100%;" type="text" name="' +
nameAttr +
'[' +
index +
'][link]" value=""></label>' +
'<button type="button" class="button ashu_upload_button">' +
aksrt__('admin_select_image') +
'</button>' +
'<button type="button" class="button delimg_upload_button">' +
aksrt__('admin_remove_image') +
'</button>' +
'<div class="widget_ui_slider_box"></div></div></div></div></div>'
);
}
/** 消息 repeater 行 */
function buildNoticeRepeaterRow(index, nameAttr) {
var i1 = index + 1;
return (
'<div class="widget_ui_slider_g">' +
'<div class="panel"><h4 class="panel-title">消息' +
i1 +
'</h4><div class="panel-conter">' +
'<label>消息' +
i1 +
'-内容(必填):<input style="width:100%;" type="text" name="' +
nameAttr +
'[' +
index +
'][title]" value=""></label>' +
'<label>消息' +
i1 +
'-图标<input style="width:100%;" type="text" name="' +
nameAttr +
'[' +
index +
'][icon]" value=""></label>' +
'<label>消息' +
i1 +
'-链接<input style="width:100%;" type="text" name="' +
nameAttr +
'[' +
index +
'][href]" value=""></label>' +
'</div></div></div>'
);
}
/** WIE:导入模式单选 HTML */
function getImportModeHtml(radioName, replaceSpanClass, appendSpanClass) {
return (
'<div class="aksrt-wie-modal__import-mode">' +
'<div class="aksrt-wie-modal__import-mode-title description"></div>' +
'<div class="flex ac hh">' +
'<label class="aksrt-wie-modal__import-mode-row"><input type="radio" name="' +
radioName +
'" value="replace" /> <span class="' +
replaceSpanClass +
'"></span></label>' +
'<label class="aksrt-wie-modal__import-mode-row"><input type="radio" name="' +
radioName +
'" value="append" checked="checked" /> <span class="' +
appendSpanClass +
'"></span></label>' +
'</div></div>'
);
}
/** WIE:填充导入模式文案 */
function bindImportModeI18n($root, replaceSelector, appendSelector) {
$root.find('.aksrt-wie-modal__import-mode-title').text(aksrt__('importModeLabel'));
$root.find(replaceSelector).text(aksrt__('importModeReplace'));
$root.find(appendSelector).text(aksrt__('importModeAppend'));
}
/** WIE:admin-ajax POST */
function wiePost(zibConfig, action, data) {
return $.ajax({
url: zibConfig.ajaxUrl,
type: 'POST',
dataType: 'json',
data: $.extend(
{
action: action,
nonce: zibConfig.nonce,
},
data || {}
),
});
}
/** WIE:解析服务端 message */
function getWieMessage(res, fallbackKey) {
return (res.data && res.data.message) || aksrt__(fallbackKey);
}
/** WIE:清空结果区样式 */
function clearWieResult($result) {
return $result.removeClass('is-ok is-warn is-err').text('');
}
/** WIE:显示错误 */
function showWieError($result, message) {
$result.removeClass('is-ok is-warn').addClass('is-err').text(message);
}
/** WIE:网络错误 */
function showNetworkError($result) {
showWieError($result, aksrt__('admin_network_error'));
}
/** WIE:导入成功后的刷新按钮 */
function getReloadBtnHtml() {
return (
'<p class="aksrt-wie-modal__reload-wrap"><a href="' +
window.location.href +
'" class="button button-primary aksrt-wie-modal__reload">' +
(aksrt__('reloadPage') || '刷新页面') +
'</a></p>'
);
}
/**
* WIE:渲染导入成功/失败结果
* @param {jQuery} $result
* @param {object} res - WP ajax 响应
* @param {object} [opts]
* @param {string} [opts.failKey]
* @param {boolean} [opts.autoReload]
* @param {Function} [opts.onSuccess]
*/
function renderImportResult($result, res, opts) {
opts = opts || {};
var failKey = opts.failKey || 'admin_import_failed';
clearWieResult($result);
if (res.success && res.data) {
var reloadBtn = getReloadBtnHtml();
var lines = [res.data.message || aksrt__('admin_import_success')];
if (res.data.warnings && res.data.warnings.length) {
lines = lines.concat(res.data.warnings);
$result.addClass('is-warn').html(lines.join('<br>') + reloadBtn);
} else {
$result.addClass('is-ok').html(lines[0] + reloadBtn);
}
if (opts.onSuccess) {
opts.onSuccess(res);
}
if (opts.autoReload) {
forceRefreshPage();
}
return true;
}
showWieError($result, getWieMessage(res, failKey));
return false;
}
/** WIE:提交按钮 loading */
function withButtonLoading($btn, loadingText, idleText, requestFn) {
$btn.prop('disabled', true).text(loadingText);
var jq = requestFn();
if (!jq || !jq.always) {
$btn.prop('disabled', false).text(idleText);
return jq;
}
return jq.always(function () {
$btn.prop('disabled', false).text(idleText);
});
}
/** WIE:强制刷新页面 */
function forceRefreshPage() {
setTimeout(function () {
window.location.reload();
}, 200);
}
/**
* WIE:弹层工厂(导出/导入、模板选择共用外壳)
* @param {object} opts
* @returns {{ ensure: Function, close: Function, open: Function, $result: Function, $el: Function, setImportModeDefault: Function }}
*/
function createWieModal(opts) {
var $modal = null;
function ensure() {
if ($modal && $modal.length) {
return $modal;
}
var shell =
'<div id="' +
opts.id +
'" class="aksrt-wie-modal' +
(opts.extraClass ? ' ' + opts.extraClass : '') +
'" aria-hidden="true">' +
'<div class="aksrt-wie-modal__backdrop" ' +
opts.closeAttr +
'="1"></div>' +
'<div class="aksrt-wie-modal__dialog" role="dialog" aria-modal="true">' +
'<button type="button" class="aksrt-wie-modal__close' +
(opts.closeBtnClass ? ' ' + opts.closeBtnClass : '') +
'" aria-label="关闭">&times;</button>' +
(opts.bodyHtml || '') +
(opts.actionsHtml || '') +
'<p class="aksrt-wie-modal__result' +
(opts.resultExtraClass ? ' ' + opts.resultExtraClass : '') +
'"></p>' +
'</div></div>';
$modal = $(shell).appendTo('body');
if (opts.importMode) {
bindImportModeI18n($modal, opts.importMode.replaceSelector, opts.importMode.appendSelector);
}
if (opts.onInit) {
opts.onInit($modal);
}
$modal.find('.aksrt-wie-modal__close, ' + (opts.cancelSelector || '')).on('click', close);
$modal.on('click', '[' + opts.closeAttr + ']', close);
$modal.find('.aksrt-wie-modal__dialog').on('click', function (e) {
e.stopPropagation();
});
return $modal;
}
function close() {
if ($modal && $modal.length) {
$modal.removeClass('is-open').attr('aria-hidden', 'true');
}
}
function open() {
ensure();
clearWieResult($result());
$modal.addClass('is-open').attr('aria-hidden', 'false');
}
function $result() {
return ensure().find(opts.resultSelector || '.aksrt-wie-modal__result');
}
function setImportModeDefault(radioName, value) {
ensure().find('input[name="' + radioName + '"][value="' + (value || 'append') + '"]').prop('checked', true);
}
return {
ensure: ensure,
close: close,
open: open,
$result: $result,
$el: function () {
return ensure();
},
setImportModeDefault: setImportModeDefault,
};
}
/** WIE:渲染模板列表项 */
function appendTemplateListItem($list, template) {
var id = template.id || '';
var $item = $('<div class="aksrt-wie-template-item"/>');
var $row = $('<div class="aksrt-wie-template-item-row"/>');
var $label = $('<label class="aksrt-wie-template-item-label"/>');
$label.append($('<input type="radio" name="aksrt-wie-template-id" />').val(id));
var $meta = $('<span class="aksrt-wie-template-item-meta"/>');
$meta.append($('<span class="aksrt-wie-template-item-title"/>').text(template.title || id));
if (template.desc) {
$meta.append($('<span class="aksrt-wie-template-item-desc"/>').html(template.desc));
}
if (template.remind) {
$meta.append($('<span class="aksrt-wie-template-item-remind"/>').html('<i class="fa fas fa-fw fa-info-circle"></i>' + template.remind));
}
$label.append($meta);
$row.append($label);
$item.append($row);
$list.append($item);
}
$(document).ready(function () {
var _body = $('body');
var img_ss = '';
$('body').on('click', '.add_lists_button', function () {
var _s_i = parseInt($(this).attr('data-count'));
var _s_m = $(this).attr('data-name');
var _s_html =
'<div class="widget_ui_slider_g">\
<div class="panel"><h4 class="panel-title">栏目' +
(_s_i + 1) +
'</h4><div class="panel-conter">\
<label>栏目' +
(_s_i + 1) +
'-标题(必填):\
<input style="width:100%;" type="text" name="' +
_s_m +
'[' +
_s_i +
'][title]" value="">\
</label>\
<label>栏目' +
(_s_i + 1) +
'-分类限制:\
<input style="width:100%;" type="text" name="' +
_s_m +
'[' +
_s_i +
'][cat]" value="">\
</label>\
<label>栏目' +
(_s_i + 1) +
'-专题限制:\
<input style="width:100%;" type="text" name="' +
_s_m +
'[' +
_s_i +
'][topics]" value="">\
</label>\
<label>栏目' +
(_s_i + 1) +
'-排序方式:\
<select style="width:100%;" name="' +
_s_m +
'[' +
_s_i +
'][orderby]">\
<option value="comment_count">评论数</option>\
<option value="views" selected="selected">浏览量</option>\
<option value="like">点赞数</option>\
<option value="favorite">收藏数</option>\
<option value="date">发布时间</option>\
<option value="modified">更新时间</option>\
<option value="rand">随机排序</option>\
</select>\
</label></div></div></div>';
$(this)
.attr('data-count', _s_i + 1)
.before(_s_html);
});
$('body').on('click', '.rem_lists_button', function () {
$(this).prev().prev('.widget_ui_slider_g').remove();
var add_b = $(this).siblings('.add_button');
var _s_i = parseInt(add_b.attr('data-count'));
add_b.attr('data-count', _s_i - 1);
});
var ashu_upload_frame;
img_ss = '';
$('body').on('click', '.delimg_upload_button', function () {
$(this).siblings('div').html('');
$(this).siblings('label').find('input').val('');
});
$('body').on('click', '.add_slider_button', function () {
var _s_i = parseInt($(this).attr('data-count'));
var _s_i1 = _s_i + 1;
var _s_m = $(this).attr('data-name');
var _s_html = buildMediaRepeaterRow('幻灯片', _s_i, _s_m, {
title: '-标题:',
dec: '-简介',
href: '-链接',
link: '-图片',
});
$(this).attr('data-count', _s_i1).before(_s_html);
});
$('body').on('click', '.add_links_button', function () {
var _s_i = parseInt($(this).attr('data-count'));
var _s_i1 = _s_i + 1;
var _s_m = $(this).attr('data-name');
var _s_html = buildMediaRepeaterRow('链接', _s_i, _s_m, {
title: '-名称(必填):',
dec: '-简介',
href: '-链接(必填)',
link: '-图片',
});
$(this).attr('data-count', _s_i1).before(_s_html);
});
$('body').on('click', '.add_notice_button', function () {
var _s_i = parseInt($(this).attr('data-count'));
var _s_i1 = _s_i + 1;
var _s_m = $(this).attr('data-name');
$(this).attr('data-count', _s_i1).before(buildNoticeRepeaterRow(_s_i, _s_m));
});
$('body').on('click', '.ashu_upload_button', function (event) {
var _his = $(this);
event.preventDefault();
if (ashu_upload_frame) {
ashu_upload_frame.open();
return;
}
ashu_upload_frame = wp.media({
title: aksrt__('admin_select_image_slide'),
button: {
text: aksrt__('confirm'),
},
multiple: true,
});
ashu_upload_frame.on('select', function () {
var attachment = ashu_upload_frame.state().get('selection').first().toJSON();
img_ss = '<img src="' + attachment.url + '">';
_his.siblings('div').html(img_ss);
_his.siblings('label').find('input').val(attachment.url);
});
ashu_upload_frame.open();
});
$('body').on('click', '.cat-help-button', function () {
$(this).siblings('.cat-help-con').slideToggle();
});
$('body').on('click', '.panel-title', function () {
$(this).siblings('.panel-conter').slideToggle();
});
/**
* 侧栏小工具:在侧栏描述下注入导出/导入,弹层内 JSON 文本域
*/
(function () {
var _zib = window.aksrt_widget_set_var;
if (!_zib || !_zib.ajaxUrl) {
return;
}
var state = { mode: 'export', sidebarId: '' };
var tplState = { sidebarId: '' };
var ioModal = createWieModal({
id: 'aksrt-wie-modal',
closeAttr: 'data-aksrt-wie-close',
cancelSelector: '.aksrt-wie-modal__cancel',
importMode: {
replaceSelector: '.aksrt-wie-import-txt-replace',
appendSelector: '.aksrt-wie-import-txt-append',
},
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>' +
getImportModeHtml('aksrt-wie-import-mode', 'aksrt-wie-import-txt-replace', 'aksrt-wie-import-txt-append'),
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: function ($modal) {
$modal.find('.aksrt-wie-modal__copy').on('click', function () {
var ta = $modal.find('.aksrt-wie-modal__textarea')[0];
if (!ta) {
return;
}
ta.select();
ta.setSelectionRange(0, ta.value.length);
try {
document.execCommand('copy');
$(this).text(aksrt__('copyDone'));
} catch (err) {
alert(aksrt__('copyFail'));
}
});
$modal.find('.aksrt-wie-modal__submit').on('click', doImportSubmit);
},
});
var tplModal = createWieModal({
id: 'aksrt-wie-template-modal',
extraClass: 'aksrt-wie-template-layer',
closeAttr: 'data-aksrt-wie-tpl-close',
closeBtnClass: 'aksrt-wie-tpl-close',
cancelSelector: '.aksrt-wie-template-cancel',
resultExtraClass: 'aksrt-wie-template-result',
importMode: {
replaceSelector: '.aksrt-wie-tpl-txt-replace',
appendSelector: '.aksrt-wie-tpl-txt-append',
},
bodyHtml:
'<h3 class="aksrt-wie-modal__title aksrt-wie-template-head-title"></h3>' +
'<p class="aksrt-wie-modal__hint description aksrt-wie-template-head-hint"></p>' +
'<div class="aksrt-wie-template-list-wrap"><p class="aksrt-wie-template-list-status description"></p><div class="aksrt-wie-template-list"></div></div>' +
getImportModeHtml('aksrt-wie-template-import-mode', 'aksrt-wie-tpl-txt-replace', 'aksrt-wie-tpl-txt-append').replace(
'aksrt-wie-modal__import-mode',
'aksrt-wie-modal__import-mode 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-template-cancel"></button>' +
'</p>',
onInit: function ($modal) {
$modal.find('.aksrt-wie-template-head-title').text(aksrt__('templateModalTitle'));
$modal.find('.aksrt-wie-template-head-hint').html(aksrt__('templateHint'));
$modal.find('.aksrt-wie-template-submit').text(aksrt__('templateSubmit'));
$modal.find('.aksrt-wie-template-cancel').text(aksrt__('close'));
var $tplDialog = $modal.find('.aksrt-wie-modal__dialog');
$modal.find('.aksrt-wie-template-submit').on('click', doTemplateImportSubmit);
$tplDialog.on('click', '.aksrt-wie-template-item-expand', function (e) {
e.preventDefault();
e.stopPropagation();
var $btn = $(this);
var expanded = $btn.hasClass('is-expanded');
var $item = $btn.closest('.aksrt-wie-template-item');
var $mods = $item.find('.aksrt-wie-template-item-modules');
if (expanded) {
$btn.removeClass('is-expanded').attr('aria-expanded', 'false');
$btn.attr('aria-label', aksrt__('templateExpandModules'));
$mods.hide();
} else {
$btn.addClass('is-expanded').attr('aria-expanded', 'true');
$btn.attr('aria-label', aksrt__('templateCollapseModules'));
$mods.show();
}
});
},
});
function setModeUi(mode) {
var $modal = ioModal.$el();
var $copy = $modal.find('.aksrt-wie-modal__copy');
var $sub = $modal.find('.aksrt-wie-modal__submit');
if (mode === 'export') {
$copy.show().text(aksrt__('copy'));
$sub.hide();
$modal.find('.aksrt-wie-modal__import-mode').hide();
} else {
$copy.hide();
$sub.show().text(aksrt__('submitImport')).prop('disabled', false);
$modal.find('.aksrt-wie-modal__import-mode').show();
}
$modal.find('.aksrt-wie-modal__cancel').text(aksrt__('close'));
}
function openModal(mode, sidebarId) {
state.mode = mode;
state.sidebarId = sidebarId;
var $modal = ioModal.ensure();
clearWieResult(ioModal.$result());
$modal
.find('.aksrt-wie-modal__textarea')
.prop('readonly', mode === 'export')
.val('');
if (mode === 'export') {
$modal.find('.aksrt-wie-modal__title').text(aksrt__('exportTitle'));
$modal.find('.aksrt-wie-modal__hint').text(aksrt__('exportHint'));
setModeUi('export');
fetchExport();
} else {
$modal.find('.aksrt-wie-modal__title').text(aksrt__('importTitle'));
$modal.find('.aksrt-wie-modal__hint').text(aksrt__('importHint'));
ioModal.setImportModeDefault('aksrt-wie-import-mode', 'append');
setModeUi('import');
}
ioModal.open();
}
function fetchExport() {
var $modal = ioModal.$el();
var $ta = $modal.find('.aksrt-wie-modal__textarea');
$ta.val(aksrt__('loadingExport'));
wiePost(_zib, 'aksrt_wie_export_sidebar', {
sidebar_id: state.sidebarId,
})
.done(function (res) {
if (res.success && res.data && res.data.json_text) {
$ta.val(res.data.json_text);
} else {
$ta.val('');
showWieError(ioModal.$result(), getWieMessage(res, 'admin_export_failed'));
}
})
.fail(function () {
$ta.val('');
showNetworkError(ioModal.$result());
});
}
function doImportSubmit() {
var $modal = ioModal.$el();
var importMode = $modal.find('input[name="aksrt-wie-import-mode"]:checked').val() || 'replace';
var confirmMsg =
importMode === 'append'
? aksrt__('confirmImportAppend') || aksrt__('confirmImport')
: aksrt__('confirmImportReplace') || aksrt__('confirmImport');
if (!window.confirm(confirmMsg)) {
return;
}
var raw = $.trim($modal.find('.aksrt-wie-modal__textarea').val());
if (!raw) {
showWieError(ioModal.$result(), aksrt__('admin_paste_json_first'));
return;
}
var $sub = $modal.find('.aksrt-wie-modal__submit');
withButtonLoading($sub, aksrt__('loadingImport'), aksrt__('submitImport'), function () {
return wiePost(_zib, 'aksrt_wie_import_sidebar', {
sidebar_id: state.sidebarId,
json: raw,
import_mode: importMode,
})
.done(function (res) {
if (res.success && res.data) {
$modal.find('.aksrt-wie-modal__textarea').val('');
}
renderImportResult(ioModal.$result(), res);
})
.fail(function () {
showNetworkError(ioModal.$result());
});
});
}
function openTemplatePicker(sidebarId) {
tplState.sidebarId = sidebarId;
var $modal = tplModal.ensure();
tplModal.setImportModeDefault('aksrt-wie-template-import-mode', 'append');
var $list = $modal.find('.aksrt-wie-template-list').empty();
var $st = $modal.find('.aksrt-wie-template-list-status').text(aksrt__('templateLoadingList'));
tplModal.open();
wiePost(_zib, 'aksrt_wie_list_templates', {})
.done(function (res) {
$st.text('');
if (!res.success || !res.data || !res.data.templates || !res.data.templates.length) {
$list.empty();
$st.text(aksrt__('templateEmpty'));
return;
}
res.data.templates.forEach(function (t) {
appendTemplateListItem($list, t);
});
})
.fail(function () {
$st.text(aksrt__('admin_network_error'));
});
}
function doTemplateImportSubmit() {
var $modal = tplModal.$el();
var tid = $modal.find('input[name="aksrt-wie-template-id"]:checked').val();
if (!tid) {
alert(aksrt__('templatePick'));
return;
}
var importMode = $modal.find('input[name="aksrt-wie-template-import-mode"]:checked').val() || 'replace';
var titleText =
$.trim(
$modal
.find('input[name="aksrt-wie-template-id"]:checked')
.closest('.aksrt-wie-template-item')
.find('.aksrt-wie-template-item-title')
.first()
.text()
) || tid;
var modeLabel = importMode === 'append' ? aksrt__('importModeAppend') || '追加' : aksrt__('importModeReplace') || '覆盖';
var cmsg = (aksrt__('confirmTemplate') || '确定导入?').replace('{title}', titleText).replace('{mode}', modeLabel);
if (!window.confirm(cmsg)) {
return;
}
var $sub = $modal.find('.aksrt-wie-template-submit');
withButtonLoading($sub, aksrt__('loadingImport'), aksrt__('templateSubmit'), function () {
return wiePost(_zib, 'aksrt_wie_import_template', {
sidebar_id: tplState.sidebarId,
template_id: tid,
import_mode: importMode,
})
.done(function (res) {
renderImportResult(tplModal.$result(), res, { autoReload: true });
})
.fail(function () {
showNetworkError(tplModal.$result());
});
});
}
function injectToolbarAfter($anchor, sidebarId) {
if (!$anchor || !$anchor.length || !sidebarId) {
return;
}
if ($anchor.next('.aksrt-wie-toolbar').length) {
return;
}
var $tb = $(
'<div class="aksrt-wie-toolbar"><button type="button" class="button button-small aksrt-wie-btn-export">' +
aksrt__('admin_export_modules') +
'</button>' +
'<button type="button" class="button button-small aksrt-wie-btn-import">' +
aksrt__('admin_import_modules') +
'</button>' +
'<button type="button" class="button button-small aksrt-wie-btn-template">' +
aksrt__('admin_import_template') +
'</button></div>'
);
$tb.find('.aksrt-wie-btn-export').data('zibWieSid', sidebarId);
$tb.find('.aksrt-wie-btn-import').data('zibWieSid', sidebarId);
$tb.find('.aksrt-wie-btn-template').data('zibWieSid', sidebarId);
$anchor.after($tb);
}
function scanWidgetsScreen() {
$('.widgets-holder-wrap:not(#available-widgets):not(.inactive-sidebar):not(.is-wid-load)').each(function () {
var $wrap = $(this);
var $sort = $wrap.find('.widgets-sortables').first();
var sid = $sort.attr('id');
if (!sid) {
return;
}
var $desc = $sort.find('.sidebar-description .description').first();
var $anchor = $desc.length ? $desc : $sort.find('.description').first();
$wrap.addClass('is-wid-load');
injectToolbarAfter($anchor, sid);
});
}
function scanCustomize() {
$('.control-section-sidebar:not(.aksrt-is-load)').each(function () {
var $sec = $(this);
var accId = $sec.attr('id') || '';
var prefix = 'sub-accordion-section-sidebar-widgets-';
if (accId.indexOf(prefix) !== 0) {
return;
}
var sid = accId.slice(prefix.length);
if (!sid) {
return;
}
$sec.addClass('aksrt-is-load');
var $desc = $sec.find('.section-meta .description').first();
var $anchor = $desc.length ? $desc : $sec.find('.accordion-section-title, .customize-section-title').first();
injectToolbarAfter($anchor, sid);
});
$('.customize-control-widget_form:not(.aksrt-is-load)').each(function () {
var $form = $(this);
var $nav = $form.find('.widget-reorder-nav');
if ($nav.length) {
var $delete = $('<span class="aksrt-wie-btn_delete dashicons-trash" tabindex="0">' + aksrt__('admin_remove_module') + '</span>');
$form.find('.widget-reorder-nav').append($delete);
$form.addClass('aksrt-is-load');
}
});
}
_body.on('click', '.aksrt-wie-btn_delete', function () {
var $this = $(this);
var $form = $this.closest('.customize-control-widget_form');
$form.find('.widget-control-remove').click();
});
_body.on('click', '.aksrt-wie-modal__reload', function () {
window.location.reload();
});
_body.on('click', '.aksrt-wie-btn-export', function () {
var sid = $(this).data('zibWieSid');
if (sid) {
openModal('export', sid);
}
});
_body.on('click', '.aksrt-wie-btn-import', function () {
var sid = $(this).data('zibWieSid');
if (sid) {
openModal('import', sid);
}
});
_body.on('click', '.aksrt-wie-btn-template', function () {
var sid = $(this).data('zibWieSid');
if (sid) {
openTemplatePicker(sid);
}
});
if (_body.hasClass('widgets-php')) {
scanWidgetsScreen();
}
if (_body.hasClass('wp-customizer')) {
if (typeof wp !== 'undefined' && wp.customize) {
wp.customize.bind('ready', function () {
setTimeout(scanCustomize, 300);
});
}
_body.on('click', '.control-panel-widgets .control-section-sidebar', function () {
setTimeout(scanCustomize, 100);
});
}
})();
});
})(jQuery, document);
File diff suppressed because one or more lines are too long
+13 -24
View File
@@ -40,10 +40,8 @@
return count >= MIN_HEADINGS ? html : '';
}
function fillBoxes(listsHtml, scope) {
var boxes = Array.prototype.slice.call(scope.querySelectorAll(NAVBOX));
if (scope.nodeType === 1 && scope.matches(NAVBOX)) boxes.unshift(scope);
boxes.forEach(function (box) {
function fillBoxes(listsHtml) {
document.querySelectorAll(NAVBOX).forEach(function (box) {
var existing = box.querySelector('.' + NAV_CLASS);
if (existing) {
existing.innerHTML = listsHtml;
@@ -77,13 +75,7 @@
window.scrollTo({ top: top, behavior: 'smooth' });
}
var clicksBound = false;
var scrollspyBound = false;
var autoHashHandled = false;
function bindClicks() {
if (clicksBound) return;
clicksBound = true;
document.addEventListener('click', function (e) {
var a = e.target && e.target.closest ? e.target.closest('.' + NAV_CLASS + ' a[href^="#"]') : null;
if (!a) return;
@@ -95,11 +87,9 @@
});
}
function scrollspy(scope) {
if (scrollspyBound) return;
var links = scope.querySelectorAll('.' + NAV_CLASS + ' a[href^="#"]');
function scrollspy() {
var links = document.querySelectorAll('.' + NAV_CLASS + ' a[href^="#"]');
if (!links.length) return;
scrollspyBound = true;
var map = [];
links.forEach(function (a) {
var id = a.getAttribute('href').slice(1);
@@ -121,32 +111,31 @@
}
function autoHash() {
if (autoHashHandled || !window.location.hash) return;
autoHashHandled = true;
if (window.location.hash) {
setTimeout(function () {
smoothTo(window.location.hash);
}, 40);
}
}
function init(scope) {
scope = scope || document;
function init() {
if (document.documentElement.dataset.aksrtSectionNavInitialized === '1') return;
document.documentElement.dataset.aksrtSectionNavInitialized = '1';
if (document.querySelector('.posts-nav-box .toc-list, .posts-nav-box.toc-widget .toc-list')) {
return;
}
var root = scope.nodeType === 1 && scope.matches('[data-nav], .article-content, .entry-content, main.article')
? scope
: scope.querySelector('[data-nav], .article-content, .entry-content, main.article');
var root = document.querySelector('[data-nav], .article-content, .entry-content, main.article');
if (!root) return;
var listsHtml = buildLists(root);
if (!listsHtml) return;
if (!document.querySelector(NAVBOX) && !document.querySelector('.' + NAV_CLASS)) {
return;
}
fillBoxes(listsHtml, document);
fillBoxes(listsHtml);
bindClicks();
scrollspy(document);
scrollspy();
autoHash();
}
window.AksrtFrontend.register('aksrt-section-navs', init);
jQuery(document).off('auto_fun.aksrt-section-navs').on('auto_fun.aksrt-section-navs', init);
})();
+7 -20
View File
@@ -29,11 +29,8 @@
});
}
function initSignin(scope) {
scope = scope || document;
var buttons = [];
if (scope.nodeType === 1 && scope.matches('[data-signin-btn]')) buttons.push(scope);
if (scope.querySelectorAll) scope.querySelectorAll('[data-signin-btn]').forEach(function (button) { buttons.push(button); });
function initSignin() {
var buttons = Array.prototype.slice.call(document.querySelectorAll('[data-signin-btn]'));
var freshButtons = buttons.filter(function (button) {
return button.dataset.aksrtSigninInitialized !== '1';
});
@@ -43,19 +40,12 @@
button.dataset.aksrtSigninInitialized = '1';
});
function elements(selector) {
var items = [];
if (scope.nodeType === 1 && scope.matches(selector)) items.push(scope);
if (scope.querySelectorAll) scope.querySelectorAll(selector).forEach(function (item) { items.push(item); });
return items;
}
function statuses() {
return elements('[data-signin-status]');
return document.querySelectorAll('[data-signin-status]');
}
function currentButtons() {
return elements('[data-signin-btn]');
return document.querySelectorAll('[data-signin-btn]');
}
function setStatus(text) {
@@ -108,8 +98,7 @@
}
function captchaMount() {
if (scope.nodeType === 1 && scope.matches('[data-signin-captcha]')) return scope;
return scope.querySelector ? scope.querySelector('[data-signin-captcha]') : null;
return document.querySelector('[data-signin-captcha]');
}
function doSignin(captchaPayload) {
@@ -126,7 +115,7 @@
}
notyf(result.json.message || '签到成功', 'success', 5, 'aksrt-balance-signin-toast');
elements('[data-credits-value]').forEach(function (element) {
document.querySelectorAll('[data-credits-value]').forEach(function (element) {
element.textContent = Number(result.json.balance || 0).toLocaleString();
});
setButtonState('done');
@@ -160,7 +149,5 @@
refresh();
}
if (window.AksrtFrontend && typeof window.AksrtFrontend.register === 'function') {
window.AksrtFrontend.register('signin', initSignin);
}
jQuery(document).off('auto_fun.aksrt-signin').on('auto_fun.aksrt-signin', initSignin);
})();
+2 -6
View File
@@ -10,11 +10,8 @@
(function () {
'use strict';
window.AksrtFrontend.register('aksrt-site-notice', function (root) {
root = root || document;
var el = root.nodeType === 1 && root.matches('#aksrt-site-notice') ? root : root.querySelector('#aksrt-site-notice');
if (!el || el.dataset.aksrtNoticeBound === '1') return;
el.dataset.aksrtNoticeBound = '1';
var el = document.getElementById('aksrt-site-notice');
if (!el) return;
// 弹窗周期(小时),0=永不过期
var expiresHours = parseInt(el.dataset.expires || '24', 10) || 0;
@@ -91,5 +88,4 @@
// Delay slightly so it doesn't flash on fast navigations
setTimeout(show, 500);
}
});
})();
-6
View File
@@ -19,9 +19,6 @@
if (typeof window.notyf === 'function') window.notyf(message, type);
}
function bindOnce() {
if (document.__aksrtUserBadgeActionsBound) return;
document.__aksrtUserBadgeActionsBound = true;
document.addEventListener('click', function (event) {
var button = event.target.closest('[data-aksrt-badge-action]');
if (!button || button.classList.contains('is-loading')) return;
@@ -60,7 +57,4 @@
notice(error.message || '网络错误', 'danger');
});
});
}
window.AksrtFrontend.register('aksrt-user-badge-actions', bindOnce);
})(window, document);
+5 -12
View File
@@ -219,9 +219,6 @@
};
// ── 剧集切换按钮事件委托 ──
function bindEpisodeSwitch() {
if (document.__aksrtVideoEpisodeBound) return;
document.__aksrtVideoEpisodeBound = true;
document.addEventListener('click', function (e) {
var switchBtn = e.target.closest('.switch-video, .switch-iframe');
if (!switchBtn) return;
@@ -260,23 +257,19 @@
switchBtn.classList.add('is-active');
switchBtn.classList.add('active');
});
}
// ── Public API ──
window.AksrtVideoPlayer = AksrtVideoPlayer;
function init(root) {
root = root || document;
// ── Auto-init ──
function init() {
injectStyle();
bindEpisodeSwitch();
var elements = [];
if (root && root.nodeType === 1 && root.matches('[data-aksrt-video]')) elements.push(root);
Array.prototype.push.apply(elements, root.querySelectorAll('[data-aksrt-video]'));
elements.forEach(function (el) {
document.querySelectorAll('[data-aksrt-video]').forEach(function (el) {
new AksrtVideoPlayer(el);
});
}
window.AksrtFrontend.register('aksrt-video-player', init);
jQuery(document).off('auto_fun.aksrt-video-player').on('auto_fun.aksrt-video-player', function () { init(document); });
})();
+7 -20
View File
@@ -154,31 +154,18 @@
});
}
function autoInit(root) {
var elements = [];
if (root && root.nodeType === 1 && root.matches('[data-aksrt-waterfall]')) elements.push(root);
Array.prototype.push.apply(elements, (root || document).querySelectorAll('[data-aksrt-waterfall]'));
elements.forEach(function (el) {
if (el._aksrtWaterfall) return;
function autoInit() {
document.querySelectorAll('[data-aksrt-waterfall]:not([data-aksrt-waterfall-bound])').forEach(function (el) {
el.dataset.aksrtWaterfallBound = '1';
var cols = parseInt(el.dataset.aksrtWaterfallColumns) || 0;
var gap = parseInt(el.dataset.aksrtWaterfallGap) || 16;
el._aksrtWaterfall = new Waterfall(el, { columns: cols, gap: gap });
waterfallInstances.push(el._aksrtWaterfall);
waterfallInstances.push(new Waterfall(el, { columns: cols, gap: gap }));
});
relayoutAll();
}
function bindGlobalEvents() {
if (document.__aksrtWaterfallEventsBound) return;
document.__aksrtWaterfallEventsBound = true;
document.addEventListener('post_ajax.ed', relayoutAll);
document.addEventListener('aksrt:posts:rendered', relayoutAll);
document.addEventListener('lazyloaded', relayoutAll, true);
}
window.AksrtFrontend.register('aksrt-waterfall', function (root) {
bindGlobalEvents();
autoInit(root);
});
jQuery(document).off('auto_fun.aksrt-waterfall').on('auto_fun.aksrt-waterfall', autoInit);
jQuery(document).off('lazyloaded.aksrt-waterfall').on('lazyloaded.aksrt-waterfall', relayoutAll);
// Export to global
window.AksrtWaterfall = Waterfall;
+2 -5
View File
@@ -249,10 +249,7 @@
});
}
window.AksrtFrontend.register('aksrt-yiyan', function (root) {
var elements = [];
if (root && root.nodeType === 1 && root.matches('[data-aksrt-yiyan]')) elements.push(root);
Array.prototype.push.apply(elements, (root || document).querySelectorAll('[data-aksrt-yiyan]'));
elements.forEach(initYiyan);
jQuery(document).off('auto_fun.aksrt-yiyan').on('auto_fun.aksrt-yiyan', function () {
document.querySelectorAll('[data-aksrt-yiyan]').forEach(initYiyan);
});
})();
+24 -21
View File
@@ -166,7 +166,7 @@
}
if (data.paginate_html) container.insertAdjacentHTML('beforeend', data.paginate_html);
container.dataset.page = String(data.page || page);
window.AksrtFrontend.rehydrate(container, 'ajax');
scan(container);
})
.catch(function () { container.innerHTML = errorMarkup(); })
.finally(function () {
@@ -262,28 +262,31 @@
requestAnimationFrame(frame);
}
function elementsIn(root, selector) {
var scope = root || document;
var elements = [];
if (scope.matches && scope.matches(selector)) elements.push(scope);
if (scope.querySelectorAll) {
scope.querySelectorAll(selector).forEach(function (element) { elements.push(element); });
}
return elements;
}
function scan(root) {
var scope = root || document;
elementsIn(scope, '.aksrt-widget-video[data-video-url]').forEach(initVideo);
elementsIn(scope, '.aksrt-widget-toc').forEach(initToc);
elementsIn(scope, '.aksrt-widget-quote').forEach(initQuote);
elementsIn(scope, '[data-widget-items]').forEach(initItems);
elementsIn(scope, '.aksrt-widget-tabs, .widget-tab-post').forEach(initTabs);
elementsIn(scope, '.aksrt-faq').forEach(initFaq);
elementsIn(scope, '.aksrt-feature-intro').forEach(initFeatures);
elementsIn(scope, '[data-count-up]').forEach(initCount);
if (typeof window.VanillaTilt !== 'undefined') elementsIn(scope, '[data-aksrt-tilt]').forEach(function (el) { if (once(el, 'Tilt')) window.VanillaTilt.init(el); });
scope.querySelectorAll('.aksrt-widget-video[data-video-url]').forEach(initVideo);
scope.querySelectorAll('.aksrt-widget-toc').forEach(initToc);
scope.querySelectorAll('.aksrt-widget-quote').forEach(initQuote);
scope.querySelectorAll('[data-widget-items]').forEach(initItems);
scope.querySelectorAll('.aksrt-widget-tabs, .widget-tab-post').forEach(initTabs);
scope.querySelectorAll('.aksrt-faq').forEach(initFaq);
scope.querySelectorAll('.aksrt-feature-intro').forEach(initFeatures);
scope.querySelectorAll('[data-count-up]').forEach(initCount);
if (typeof window.VanillaTilt !== 'undefined') scope.querySelectorAll('[data-aksrt-tilt]').forEach(function (el) { if (once(el, 'Tilt')) window.VanillaTilt.init(el); });
}
window.AksrtFrontend.register('aksrt-widgets', scan);
function ready() {
scan(document);
if ('MutationObserver' in window) {
new MutationObserver(function (mutations) {
mutations.forEach(function (mutation) { mutation.addedNodes.forEach(function (node) { if (node.nodeType === 1) scan(node); }); });
}).observe(document.body, { childList: true, subtree: true });
}
}
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', ready);
else ready();
// AJAX 注入新内容后由 auto_fun 重扫(once() data 标记保证幂等)。
if (window.jQuery) window.jQuery(document).on('auto_fun', function () { scan(document); });
})();
+7
View File
@@ -1,6 +1,13 @@
<?php
defined('ABSPATH') || exit;
// window._win runtime bridge (legacy aksrt_win_var)
add_action('wp_head', static function () {
if (function_exists('aksrt_print_win_var')) {
aksrt_print_win_var();
}
}, 1);
// 前端隐藏 WordPress Admin Bar
// ============================================================
+1 -2
View File
@@ -226,8 +226,7 @@ add_action('init', function () {
if (empty($slides)) return '';
return '<div class="aksrt-carousel-block swiper aksrt-lightbox-trigger" data-aksrt-lightbox="1" data-autoplay="' . $autoplay . '" data-delay="' . $delay . '" data-effect="' . $effect . '">'
return '<div class="aksrt-carousel-block swiper" data-autoplay="' . $autoplay . '" data-delay="' . $delay . '" data-effect="' . $effect . '">'
. '<div class="swiper-wrapper">' . $slides . '</div>'
. '<div class="swiper-pagination"></div>'
. '<div class="swiper-button-prev"></div><div class="swiper-button-next"></div>'
+1 -1
View File
@@ -1,6 +1,6 @@
<?php
/**
* Float button commerce types.
* Float button commerce types + runtime window._win bridge (legacy parity).
*
* @package AKSRT
*/
+3 -5
View File
@@ -31,7 +31,7 @@ if (!function_exists('aksrt_single_render_cover')) :
?>
<div class="single-head-cover">
<div class="single-video">
<div class="graphic single-cover single-cover--video" style="padding-bottom:<?php echo esc_attr((string) $video_scale); ?>%;">
<div class="graphic single-cover single-cover--video imgbox-container" style="padding-bottom:<?php echo esc_attr((string) $video_scale); ?>%;">
<div class="aksrt-video single-cover__player" data-aksrt-video data-src="<?php echo esc_url($ctx['cover_url']); ?>"<?php echo $poster !== '' ? ' data-poster="' . esc_url($poster) . '"' : ''; ?> style="position:absolute;inset:0;width:100%;height:100%;"></div>
</div>
<div class="single-video-footer dplayer-featured">
@@ -631,14 +631,12 @@ if (!function_exists('aksrt_single_render_article')) :
<?php endif; ?>
<?php if ($ctx['front_content'] !== '') : ?>
<div class="post_front_content theme-box box-body"<?php echo !empty($settings['lightbox']) ? ' data-aksrt-lightbox="1"' : ''; ?>><?php echo wp_kses_post((string) $ctx['front_content']); ?></div>
<div class="post_front_content theme-box box-body"><?php echo wp_kses_post((string) $ctx['front_content']); ?></div>
<?php endif; ?>
<div class="theme-box wp-posts-content<?php echo $maxheight > 0 ? ' limit-height' : ''; ?>"
<?php echo $maxheight > 0 ? ' style="max-height:' . esc_attr((string) $maxheight) . 'px;"' : ''; ?>
data-maxheight="<?php echo esc_attr((string) ($maxheight > 0 ? max(0, $maxheight - 80) : 0)); ?>"
<?php echo !empty($settings['lightbox']) ? ' data-aksrt-lightbox="1"' : ''; ?>>
data-maxheight="<?php echo esc_attr((string) ($maxheight > 0 ? max(0, $maxheight - 80) : 0)); ?>">
<?php the_content(); ?>
<?php
wp_link_pages([
+11 -2
View File
@@ -195,10 +195,19 @@ if (!function_exists('aksrt_header_user_box_html')) :
}
if (!empty($ctx['can_publish'])) {
// legacy:用户卡片发布按钮由 nav_user_newposts_btn 门控,文案可配。
$newposts_type = class_exists('\AKSRT\Settings\Settings')
? \AKSRT\Settings\Settings::get_value('nav_user_newposts_btn', 'post')
: 'post';
if (!empty($newposts_type)) {
$newposts_text = class_exists('\AKSRT\Settings\Settings')
? (string) \AKSRT\Settings\Settings::get_value('nav_user_newposts_btn_text', __('发布内容', 'aksrt'))
: __('发布内容', 'aksrt');
$pub_url = (string) $ctx['publish_url'];
$href .= '<a rel="nofollow" href="' . esc_url($pub_url) . '">';
$href .= '<div class="badg mb6 toggle-radius c-green"><i class="fa fas fa-edit" aria-hidden="true"></i></div>';
$href .= '<div class="c-green">' . esc_html__('发布内容', 'aksrt') . '</div></a>';
$href .= '<div class="c-green">' . esc_html($newposts_text) . '</div></a>';
}
}
$href .= '<a href="javascript:;" data-toggle="modal" data-target="#modal_signout">';
@@ -346,7 +355,7 @@ if (!function_exists('aksrt_menu_button')) :
$account = '<ul class="list-inline splitters relative aksrt-navbar-account'
. ($user_id <= 0 && '2' === $layout ? ' navbar-text' : '') . '">'
. $notification_but . $sign_but . $search_but . '</ul>';
$button = '<div class="aksrt-navbar-actions navbar-form navbar-right">'
$button = '<div class="aksrt-navbar-actions navbar-form navbar-right navbar-but">'
. $actions . $utility_buttons . $account . '</div>';
$fold = '<div class="navbar-form navbar-right hide show-nav-but" style="margin-right:-10px;">'

Some files were not shown because too many files have changed in this diff Show More