feat(creator-studio): 前台 Gutenberg 创作工作台与受保护付费附件
前台投稿页改为沉浸式创作工作台:Gutenberg 负责区块解析与序列化, React + TypeScript 负责工作台外壳与发布抽屉,Jio 服务端继续作为权限、 审核与付费的唯一权威。 - 新增 assets/creator-studio 独立构建(wp-scripts,锁定 WP 6.4 时代包), 仅在投稿模板加载,构建缺失或游客访问时回退原有 TinyMCE 表单 - 自动保存(4s 防抖 + rev 冲突 409)、本地快照恢复、发布配置抽屉、 移动端全屏单列与安全区适配 - 图片插入走现有 front-submit 上传管线,保留能力校验与待认领生命周期 - 已发布文章的改稿写入私有版本,审核通过前线上内容/链接/付费条款不变; 原生后台「改稿审核」一次性应用或退回,并校验源文章并发指纹 - 私有附件新表 jio_private_asset + jio_dl_token.asset_id,schema 升到 3.4.0; 文件存放 ABSPATH 之外,未配置私有存储时 fail closed - 下载令牌绑定文章/附件/用户/IP/UA/次数,每次交付复核 Visibility 的 订单、VIP 与配额判定;中断传输归还次数 - 付费字段改为写入前校验,非法价格不再留下半保存文章 - 新增 creator-studio 契约测试;更新受影响的 schema/下载/投稿契约 Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
7a8279f8e7
commit
fac4a714e0
45 files changed
+28495
-56
No files matched your search
@@ -0,0 +1,3 @@
|
||||
node_modules/
|
||||
build/*.map
|
||||
.DS_Store
|
||||
@@ -0,0 +1,56 @@
|
||||
# Jio Creator Studio(前台沉浸式创作工作台)
|
||||
|
||||
面向作者的前台写作体验:Gutenberg 作为内容内核,React + TypeScript 负责工作台与发布抽屉,Jio 服务端继续作为权限、审核、付费与附件交付的唯一权威。
|
||||
|
||||
## 启动
|
||||
|
||||
```bash
|
||||
cd assets/creator-studio
|
||||
npm install # 首次安装(packages 已锁定 WordPress 6.4 时代的版本)
|
||||
npm run build # 产物写入 assets/creator-studio/build/
|
||||
```
|
||||
|
||||
PHP 读取 `build/index.asset.php`(依赖清单 + 版本)并只在投稿模板加载,构建产物缺失时自动回退到原有 TinyMCE 投稿表单。
|
||||
|
||||
## 使用前提
|
||||
|
||||
- 已登录且具备 `new_post_add`(编辑已有文章需作者本人或审核权限)。
|
||||
- 私有附件(付费资料)需要在 `wp-config.php` 里配置私有目录:
|
||||
|
||||
```php
|
||||
define('JIO_PRIVATE_STORAGE_DIR', '/var/private/jio-assets'); // ABSPATH 之外
|
||||
```
|
||||
|
||||
若目录位于站点根目录内,还必须在 Web 服务器层禁止访问,并显式声明:
|
||||
|
||||
```php
|
||||
define('JIO_PRIVATE_STORAGE_VERIFIED', true);
|
||||
```
|
||||
|
||||
未配置时付费资料上传/下载接口返回 501(fail closed),普通图片与视频上传不受影响。
|
||||
|
||||
## 关键行为
|
||||
|
||||
| 场景 | 行为 |
|
||||
| --- | --- |
|
||||
| 新文章草稿/投稿 | 复用 `FrontSubmit::persist()`;草稿为 `draft`,投稿按 `new_post_audit_no` 决定 `publish` 或 `pending` |
|
||||
| 编辑已发布文章 | 写入私有改稿版本(`jio_submission`),线上文章与永久链接保持不变 |
|
||||
| 审核通过 | 后台「文章 → 改稿审核」一次性应用内容、摘要、分类、标签、封面与付费设置 |
|
||||
| 自动保存 | 云端 4 秒防抖 + `rev` 版本号;冲突返回 409,不覆盖较新内容 |
|
||||
| 本地恢复 | 仅保存标题与序列化正文,恢复前询问用户 |
|
||||
| 付费附件 | 上传到私有存储,只保存随机 `asset_key`;下载先取短期令牌,服务端每次复核订单/VIP/配额 |
|
||||
|
||||
## 相关代码
|
||||
|
||||
- 服务端:`src/Core/CreatorRest.php`、`CreatorStudio.php`、`SubmissionVersion.php`、`PreviewToken.php`
|
||||
- 安全交付:`src/Content/PrivateAssets.php`、`src/Content/ProtectedDownload.php`
|
||||
- 原生审核:`src/Admin/Native/SubmissionReview.php`
|
||||
- 前端:`assets/creator-studio/src/`(`index.tsx` / `panels/` / `hooks/` / `services/` / `styles/`)
|
||||
- 契约测试:`tests/widget-system/creator-studio-contract.test.cjs`
|
||||
|
||||
## 测试
|
||||
|
||||
```bash
|
||||
node --test tests/widget-system/*.test.cjs
|
||||
php tools/audit-psr4-paths.php
|
||||
```
|
||||
@@ -0,0 +1 @@
|
||||
<?php return array('dependencies' => array('react', 'wp-block-editor', 'wp-block-library', 'wp-blocks', 'wp-data', 'wp-element', 'wp-i18n', 'wp-wordcount'), 'version' => '9f8085a073c5e67a84ed');
|
||||
@@ -0,0 +1 @@
|
||||
.jio-page-submit{background:#fafbfa}.jio-page-submit .float-btn,.jio-page-submit .footer,.jio-page-submit .footer-tabbar,.jio-page-submit .header,.jio-page-submit .jio-float-buttons{display:none!important}.jio-page-submit #main-content.container{max-width:none;padding:0}#jio-creator-studio.is-ready{display:block}.jio-creator{--jc-ink:#243330;--jc-ink-soft:#5c6b66;--jc-paper:#fafbfa;--jc-line:#e2e9e5;--jc-accent:#267665;--jc-accent-strong:#1d5f52;--jc-warn:#b4573f;--jc-bar:60px;-webkit-font-smoothing:antialiased;background:var(--jc-paper);color:var(--jc-ink);font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Noto Sans SC,PingFang SC,Microsoft YaHei,sans-serif;min-height:100vh;min-height:100dvh}.jio-creator *,.jio-creator :after,.jio-creator :before{box-sizing:border-box}.jio-creator button{color:inherit;font:inherit}.jio-creator__bar{align-items:center;backdrop-filter:blur(10px);background:rgba(250,251,250,.92);border-bottom:1px solid var(--jc-line);display:flex;gap:16px;height:var(--jc-bar);padding:0 clamp(16px,4vw,40px);position:sticky;top:0;z-index:30}.jio-creator__back{align-items:center;color:var(--jc-ink-soft);display:inline-flex;gap:6px;text-decoration:none}.jio-creator__back:focus-visible,.jio-creator__back:hover{color:var(--jc-accent)}.jio-creator__brand{color:var(--jc-ink-soft);font-size:13px;letter-spacing:.06em;margin-right:auto}.jio-creator__actions{align-items:center;display:flex;gap:10px}.jio-creator__save{align-items:center;color:var(--jc-ink-soft);display:inline-flex;font-size:13px;gap:6px}.jio-creator__save>i{color:var(--jc-line);font-size:7px}.jio-creator__save time{font-variant-numeric:tabular-nums;opacity:.7}.jio-creator__save.is-saved>i{color:var(--jc-accent)}.jio-creator__save.is-conflict,.jio-creator__save.is-conflict>i,.jio-creator__save.is-error,.jio-creator__save.is-error>i{color:var(--jc-warn)}.jio-creator__btn,.jio-creator__ghost,.jio-creator__primary{align-items:center;border:1px solid transparent;border-radius:8px;cursor:pointer;display:inline-flex;font-size:14px;justify-content:center;min-height:36px;padding:0 16px;transition:background .18s ease,border-color .18s ease,color .18s ease}.jio-creator__ghost{background:transparent;border-color:var(--jc-line)}.jio-creator__ghost:focus-visible,.jio-creator__ghost:hover{border-color:var(--jc-accent);color:var(--jc-accent)}.jio-creator__primary{background:var(--jc-accent);color:#fff}.jio-creator__primary:focus-visible,.jio-creator__primary:hover{background:var(--jc-accent-strong)}.jio-creator__primary:disabled{cursor:not-allowed;opacity:.5}.jio-creator__notice{align-items:center;background:#f1f5f2;border-bottom:1px solid var(--jc-line);color:var(--jc-ink-soft);display:flex;font-size:13px;gap:12px;margin:0 auto;max-width:820px;padding:10px 16px}.jio-creator__notice>span{flex:1}.jio-creator__notice button{background:transparent;border:0;color:var(--jc-accent);cursor:pointer}.jio-creator__notice.is-error{background:#fdf2ee;color:var(--jc-warn)}.jio-creator__hint{color:var(--jc-ink-soft);font-size:13px;margin:18px auto 0;max-width:820px;padding:0 clamp(16px,4vw,40px)}.jio-creator__canvas{margin:0 auto;padding:clamp(24px,5vw,56px) clamp(16px,4vw,40px) 120px;width:min(820px,100%)}.jio-creator__title{display:block;margin-bottom:8px}.jio-creator__title textarea{background:transparent;border:0;color:var(--jc-ink);font-family:Songti SC,"Noto Serif SC","Source Han Serif SC",serif;font-size:clamp(26px,3.4vw,34px);font-weight:600;line-height:1.35;min-height:56px;padding:0;resize:none;width:100%}.jio-creator__title textarea:focus{outline:0}.jio-creator__title textarea::-moz-placeholder{color:#b7c2bd}.jio-creator__title textarea::placeholder{color:#b7c2bd}.jio-creator__excerpt{display:block;margin-bottom:28px}.jio-creator__excerpt>span{color:var(--jc-ink-soft);display:block;font-size:12px;margin-bottom:6px}.jio-creator__excerpt textarea{background:transparent;border:0;border-bottom:1px solid var(--jc-line);color:var(--jc-ink-soft);font-family:inherit;font-size:15px;line-height:1.7;padding:8px 0;resize:none;width:100%}.jio-creator__excerpt textarea:focus{border-color:var(--jc-accent);outline:0}.jio-creator__editor{position:relative}.jio-creator__editor .block-editor-writing-flow{font-size:17px;line-height:1.85}.jio-creator__editor .block-editor-default-block-appender textarea.block-editor-default-block-appender__content{color:#b7c2bd}.jio-creator__editor .block-editor-block-list__layout{padding-bottom:80px}.jio-creator__editor .wp-block{max-width:none}.jio-creator__inspector{margin-top:24px}.jio-creator__inspector .block-editor-block-inspector{border-top:1px solid var(--jc-line);padding-top:16px}.jio-creator__inspector .block-editor-block-inspector:empty{display:none}.jio-creator__inspector .components-panel__body{border:0}.jio-creator__footer{border-top:1px solid var(--jc-line);color:var(--jc-ink-soft);display:flex;font-size:12px;justify-content:space-between;padding-top:20px}.jio-creator-drawer{display:flex;inset:0;justify-content:flex-end;posiLine truncated
|
||||
@@ -0,0 +1 @@
|
||||
(()=>{"use strict";const e=window.React,t=window.wp.element,a=window.wp.blocks,r=window.wp.blockLibrary,n=window.wp.data,o=window.wp.blockEditor,i=window.wp.wordcount,l=window.wp.i18n;function c(e,t){const a=e&&(e.message||e.error)||(401===t?"登录状态已失效,请刷新页面重新登录。":"请求失败,请稍后重试。"),r=new Error(String(a));return r.status=t,r.code=e&&e.code?String(e.code):"",r.data=e,r}async function s(e){try{return await e.json()}catch(e){return null}}async function m(e,t,a){const r=await fetch(e,{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json","X-WP-Nonce":a},body:JSON.stringify(t)}),n=await s(r);if(!r.ok)throw c(n,r.status);return n}async function u(e,t,a,r={}){const n=new FormData;n.append("file",t),Object.entries(r).forEach(([e,t])=>n.append(e,t));const o=await fetch(e,{method:"POST",credentials:"same-origin",headers:{"X-WP-Nonce":a},body:n}),i=await s(o);if(!o.ok)throw c(i,o.status);return i}const d=window.jioCreatorStudio||{},p=d.nonce||"";function _(a){const{draft:r,setDraft:n,capabilities:o,limits:i,taxonomy:c,isPublishedEdit:s,onClose:m,onSaveDraft:_,onSubmit:y,privateStorage:f,privateUploads:b,saving:E,captcha:g}=a,[j,h]=(0,t.useState)(""),[w,v]=(0,t.useState)(""),[N,k]=(0,t.useState)(!1),S=(0,t.useRef)(null),C=(0,t.useRef)(null),x=(0,t.useRef)(null);(0,t.useEffect)(()=>{const e=x.current,t=document.getElementById("jio-creator-captcha");if(!e||!t)return;const a=t.parentElement;return e.appendChild(t),t.removeAttribute("hidden"),()=>{a&&(a.appendChild(t),t.setAttribute("hidden",""))}},[]);const I=(0,t.useMemo)(()=>(r.title||"").trim().length,[r.title])>=Number(i.titleMin||1),L=()=>{const e=j.trim();if(!e)return;const t=e.split(/[,,\n]+/u).map(e=>e.trim()).filter(Boolean);n({tags:Array.from(new Set([...r.tags,...t]))}),h("")};return(0,e.createElement)("div",{className:"jio-creator-drawer",role:"dialog","aria-modal":"true","aria-labelledby":"jio-creator-publish-title"},(0,e.createElement)("button",{type:"button",className:"jio-creator-drawer__backdrop","aria-label":(0,l.__)("关闭","jio"),onClick:m}),(0,e.createElement)("div",{className:"jio-creator-drawer__panel"},(0,e.createElement)("header",{className:"jio-creator-drawer__head"},(0,e.createElement)("h2",{id:"jio-creator-publish-title"},s?(0,l.__)("提交改稿","jio"):(0,l.__)("发布文章","jio")),(0,e.createElement)("button",{type:"button",className:"jio-creator-drawer__close",onClick:m,"aria-label":(0,l.__)("关闭","jio")},(0,e.createElement)("i",{className:"fa fas fa-times","aria-hidden":"true"}))),(0,e.createElement)("div",{className:"jio-creator-drawer__body"},s&&(0,e.createElement)("p",{className:"jio-creator-drawer__note"},(0,l.__)("审核通过前,读者看到的仍然是当前线上版本。","jio")),(0,e.createElement)("section",{className:"jio-creator-field"},(0,e.createElement)("h3",null,(0,l.__)("封面","jio")),r.featured?.data?.url?(0,e.createElement)("div",{className:"jio-creator-cover"},(0,e.createElement)("img",{src:String(r.featured.data.url),alt:""}),(0,e.createElement)("button",{type:"button",onClick:()=>n({featured:{type:"",data:{}}}),"aria-label":(0,l.__)("移除封面","jio")},(0,e.createElement)("i",{className:"fa fas fa-times","aria-hidden":"true"}))):o.canUploadImage?(0,e.createElement)("label",{className:"jio-creator-cover-empty"},(0,e.createElement)("input",{ref:S,type:"file",accept:"image/*",onChange:()=>{(async()=>{const e=S.current?.files?.[0];if(e&&d.media?.uploadUrl?.image){v(""),k(!0);try{const t=await u(d.media.uploadUrl.image,e,p),a=Number(t.attachment_id||t.id||0),r=String(t.url||"");if(!a||!r)throw new Error((0,l.__)("上传后无法读取图片。","jio"));n({featured:{type:"image",mediaId:a,data:{id:a,url:r}}})}catch(e){v(String(e?.message||(0,l.__)("上传失败","jio")))}finally{k(!1)}}})()},disabled:N}),(0,e.createElement)("i",{className:"fa fas fa-plus","aria-hidden":"true"}),(0,e.createElement)("span",null,N?(0,l.__)("上传中…","jio"):(0,l.__)("上传封面","jio"))):(0,e.createElement)("p",{className:"jio-creator-muted"},(0,l.__)("当前账号不能设置封面。","jio"))),(0,e.createElement)("section",{className:"jio-creator-field"},(0,e.createElement)("h3",null,(0,l.__)("分类","jio")),(0,e.createElement)("div",{className:"jio-creator-chips"},0===c.categories.length&&(0,e.createElement)("span",{className:"jio-creator-muted"},(0,l.__)("暂无可选分类","jio")),c.categories.map(t=>(0,e.createElement)("label",{key:t.id,className:"jio-creator-chip"+(r.categories.includes(t.id)?" is-active":"")},(0,e.createElement)("input",{type:"checkbox",checked:r.categories.includes(t.id),onChange:()=>(e=>{const t=r.categories.includes(e);n({categories:t?r.categories.filter(t=>t!==e):[...r.categories,e]})})(t.id)}),(0,e.createElement)("span",null,t.name))))),c.tags&&(0,e.createElement)("section",{className:"jio-creator-field"},(0,e.createElement)("h3",null,(0,l.__)("标签","jio")),(0,e.createElement)("div",{className:"jio-creator-Line truncated
|
||||
Generated
+23386
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"name": "jio-creator-studio",
|
||||
"version": "1.0.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"build": "wp-scripts build",
|
||||
"start": "wp-scripts start"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/react": "18.3.31",
|
||||
"@types/react-dom": "18.3.7",
|
||||
"@wordpress/block-editor": "11.8.0",
|
||||
"@wordpress/block-library": "^8.8.0",
|
||||
"@wordpress/blocks": "12.8.0",
|
||||
"@wordpress/components": "23.8.0",
|
||||
"@wordpress/data": "9.5.0",
|
||||
"@wordpress/element": "5.8.0",
|
||||
"@wordpress/i18n": "4.31.0",
|
||||
"@wordpress/scripts": "26.4.0",
|
||||
"@wordpress/wordcount": "3.31.0",
|
||||
"sass": "1.77.8",
|
||||
"typescript": "5.4.5"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
/**
|
||||
* 顶栏保存状态。状态文案即用户对“内容有没有保存”的唯一反馈。
|
||||
*
|
||||
* @package Jio
|
||||
*/
|
||||
|
||||
import { __ } from '@wordpress/i18n';
|
||||
|
||||
export type SaveStatus = 'ready' | 'saving' | 'saved' | 'error' | 'conflict' | 'submitting' | 'submitted';
|
||||
|
||||
export type SaveStateValue = { state: SaveStatus; at: string };
|
||||
|
||||
const LABELS: Record<SaveStatus, string> = {
|
||||
ready: __('尚未保存', 'jio'),
|
||||
saving: __('保存中…', 'jio'),
|
||||
saved: __('已保存', 'jio'),
|
||||
error: __('保存失败', 'jio'),
|
||||
conflict: __('内容已在别处更新', 'jio'),
|
||||
submitting: __('提交中…', 'jio'),
|
||||
submitted: __('已提交', 'jio'),
|
||||
};
|
||||
|
||||
export function SaveState({ value }: { value: SaveStateValue }) {
|
||||
return (
|
||||
<span className={`jio-creator__save is-${value.state}`} role="status" aria-live="polite">
|
||||
<i className="fa fas fa-circle" aria-hidden="true" />
|
||||
<span>{LABELS[value.state] || LABELS.ready}</span>
|
||||
{value.state === 'saved' && value.at ? <time>{value.at}</time> : null}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
/**
|
||||
* 自动保存节奏控制。
|
||||
*
|
||||
* - 云端自动保存 4 秒防抖,保存进行中不叠加请求;
|
||||
* - 本地快照 1.5 秒防抖,由调用方写入 localStorage;
|
||||
* - 页面隐藏/失焦时立即冲刷一次,避免切走丢稿。
|
||||
*
|
||||
* 回调放进 ref,保证 schedule 引用稳定:否则每次输入产生的重渲染都会重置
|
||||
* 定时器,自动保存永远不会触发。
|
||||
*
|
||||
* @package Jio
|
||||
*/
|
||||
|
||||
import { useCallback, useEffect, useMemo, useRef } from '@wordpress/element';
|
||||
|
||||
type Options = {
|
||||
enabled: boolean;
|
||||
onSave: () => Promise<boolean>;
|
||||
onLocal: () => void;
|
||||
remoteDelay?: number;
|
||||
localDelay?: number;
|
||||
};
|
||||
|
||||
export function useAutosave({ enabled, onSave, onLocal, remoteDelay = 4000, localDelay = 1500 }: Options) {
|
||||
const remoteTimer = useRef<number | null>(null);
|
||||
const localTimer = useRef<number | null>(null);
|
||||
const inFlight = useRef(false);
|
||||
|
||||
const saveRef = useRef(onSave);
|
||||
const localRef = useRef(onLocal);
|
||||
saveRef.current = onSave;
|
||||
localRef.current = onLocal;
|
||||
|
||||
const clear = useCallback(() => {
|
||||
if (remoteTimer.current) {
|
||||
window.clearTimeout(remoteTimer.current);
|
||||
remoteTimer.current = null;
|
||||
}
|
||||
if (localTimer.current) {
|
||||
window.clearTimeout(localTimer.current);
|
||||
localTimer.current = null;
|
||||
}
|
||||
}, []);
|
||||
|
||||
const flush = useCallback(async () => {
|
||||
if (inFlight.current) {
|
||||
return;
|
||||
}
|
||||
inFlight.current = true;
|
||||
try {
|
||||
await saveRef.current();
|
||||
} finally {
|
||||
inFlight.current = false;
|
||||
}
|
||||
}, []);
|
||||
|
||||
const schedule = useCallback(() => {
|
||||
clear();
|
||||
localRef.current();
|
||||
if (!enabled) {
|
||||
return;
|
||||
}
|
||||
localTimer.current = window.setTimeout(() => localRef.current(), localDelay);
|
||||
remoteTimer.current = window.setTimeout(() => {
|
||||
void flush();
|
||||
}, remoteDelay);
|
||||
}, [clear, enabled, flush, localDelay, remoteDelay]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled) {
|
||||
return undefined;
|
||||
}
|
||||
const onHide = () => {
|
||||
if (document.visibilityState === 'hidden') {
|
||||
void flush();
|
||||
}
|
||||
};
|
||||
const onBlur = () => {
|
||||
void flush();
|
||||
};
|
||||
document.addEventListener('visibilitychange', onHide);
|
||||
window.addEventListener('blur', onBlur);
|
||||
return () => {
|
||||
document.removeEventListener('visibilitychange', onHide);
|
||||
window.removeEventListener('blur', onBlur);
|
||||
clear();
|
||||
};
|
||||
}, [clear, enabled, flush]);
|
||||
|
||||
return useMemo(() => ({ schedule, flush, cancel: clear }), [clear, flush, schedule]);
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
/**
|
||||
* 本地草稿备份。
|
||||
*
|
||||
* 只保存标题与序列化后的正文,绝不保存 nonce、文件或付费凭据;恢复前由界面
|
||||
* 询问用户,成功保存服务端后才清除。
|
||||
*
|
||||
* @package Jio
|
||||
*/
|
||||
|
||||
import { useCallback, useEffect, useRef } from '@wordpress/element';
|
||||
|
||||
type Snapshot = { title: string; content: string; at: string };
|
||||
|
||||
type Options = {
|
||||
key: string;
|
||||
snapshot: Snapshot;
|
||||
onFound: (savedAt: string) => void;
|
||||
};
|
||||
|
||||
const MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;
|
||||
|
||||
export function useLocalRecovery({ key, snapshot, onFound }: Options) {
|
||||
const latest = useRef(snapshot);
|
||||
latest.current = snapshot;
|
||||
const checked = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (checked.current) {
|
||||
return;
|
||||
}
|
||||
checked.current = true;
|
||||
try {
|
||||
const raw = window.localStorage.getItem(key);
|
||||
if (!raw) {
|
||||
return;
|
||||
}
|
||||
const parsed = JSON.parse(raw);
|
||||
const at = typeof parsed.at === 'string' ? Date.parse(parsed.at) : NaN;
|
||||
if (!Number.isFinite(at) || Date.now() - at > MAX_AGE_MS) {
|
||||
window.localStorage.removeItem(key);
|
||||
return;
|
||||
}
|
||||
if (typeof parsed.content === 'string' && parsed.content !== snapshot.content) {
|
||||
onFound(String(parsed.at));
|
||||
}
|
||||
} catch (error) {
|
||||
window.localStorage.removeItem(key);
|
||||
}
|
||||
}, [key, onFound, snapshot.content]);
|
||||
|
||||
const markLocalSaved = useCallback(() => {
|
||||
try {
|
||||
window.localStorage.setItem(key, JSON.stringify(latest.current));
|
||||
} catch (error) {
|
||||
// 存储配额不足时静默降级:云端自动保存仍然是主路径。
|
||||
}
|
||||
}, [key]);
|
||||
|
||||
const clear = useCallback(() => {
|
||||
try {
|
||||
window.localStorage.removeItem(key);
|
||||
} catch (error) {
|
||||
// ignore
|
||||
}
|
||||
}, [key]);
|
||||
|
||||
return { markLocalSaved, clear };
|
||||
}
|
||||
@@ -0,0 +1,450 @@
|
||||
/**
|
||||
* Jio Creator Studio — 前台沉浸式创作界面。
|
||||
*
|
||||
* Gutenberg 负责区块解析、编辑与序列化;本入口只搭建工作台外壳、发布配置抽屉
|
||||
* 与保存/预览/提交编排。所有写入都走 Jio REST(CreatorRest),服务端负责权限、
|
||||
* 字段清洗、审核状态与私有附件归属。
|
||||
*
|
||||
* @package Jio
|
||||
*/
|
||||
|
||||
import { createRoot, useCallback, useEffect, useMemo, useRef, useState } from '@wordpress/element';
|
||||
import { parse, serialize } from '@wordpress/blocks';
|
||||
import { registerCoreBlocks } from '@wordpress/block-library';
|
||||
import { useSelect } from '@wordpress/data';
|
||||
import { BlockEditorProvider, BlockList, BlockTools, BlockInspector } from '@wordpress/block-editor';
|
||||
import { count as countWords } from '@wordpress/wordcount';
|
||||
import { __ } from '@wordpress/i18n';
|
||||
|
||||
import { apiPost } from './services/api';
|
||||
import { installMediaUploadBridge } from './services/media';
|
||||
import { PublishDrawer } from './panels/publish-drawer';
|
||||
import { SaveState, type SaveStateValue } from './components/save-state';
|
||||
import { useAutosave } from './hooks/use-autosave';
|
||||
import { useLocalRecovery } from './hooks/use-local-recovery';
|
||||
import { normalizePayForRequest } from './utils/pay';
|
||||
import './styles/studio.scss';
|
||||
|
||||
// 核心区块注册只做一次;重复调用会触发 "Block type already registered"。
|
||||
const coreRegistered = (window as any).__jioCoreBlocksRegistered;
|
||||
if (!coreRegistered && typeof registerCoreBlocks === 'function') {
|
||||
registerCoreBlocks();
|
||||
(window as any).__jioCoreBlocksRegistered = true;
|
||||
}
|
||||
|
||||
const bootstrap: Record<string, any> = window['jioCreatorStudio'] || {};
|
||||
const nonce: string = bootstrap.nonce || '';
|
||||
const STORAGE_KEY = `jio-studio-${bootstrap.sourceId || 0}`;
|
||||
|
||||
type Featured = { type: string; data: Record<string, any>; mediaId?: number };
|
||||
type PayState = {
|
||||
enabled: boolean;
|
||||
modo: 'cash' | 'points';
|
||||
price: string;
|
||||
points: number;
|
||||
vip1Price: string;
|
||||
vip2Price: string;
|
||||
payLimit: number;
|
||||
downloads: Array<Record<string, any>>;
|
||||
};
|
||||
|
||||
type Limits = {
|
||||
titleMin?: number;
|
||||
titleMax?: number;
|
||||
titlePlaceholder?: string;
|
||||
priceMin?: number;
|
||||
priceMax?: number;
|
||||
pointsMin?: number;
|
||||
pointsMax?: number;
|
||||
};
|
||||
|
||||
type Draft = {
|
||||
postId: number;
|
||||
versionId: number;
|
||||
rev: number;
|
||||
title: string;
|
||||
excerpt: string;
|
||||
content: string;
|
||||
categories: number[];
|
||||
tags: string[];
|
||||
custom: Record<string, string[]>;
|
||||
featured: Featured;
|
||||
pay: PayState;
|
||||
};
|
||||
|
||||
function initialDraft(): Draft {
|
||||
const pay = bootstrap.pay || {};
|
||||
const selected = (bootstrap.categories && bootstrap.categories.selected) || [];
|
||||
const tags = (bootstrap.tags && bootstrap.tags.items) || [];
|
||||
return {
|
||||
postId: Number(bootstrap.sourceId || 0),
|
||||
versionId: Number(bootstrap.versionId || 0),
|
||||
rev: Number(bootstrap.versionRev || 0),
|
||||
title: String(bootstrap.title || ''),
|
||||
excerpt: String(bootstrap.excerpt || ''),
|
||||
content: String(bootstrap.content || ''),
|
||||
categories: selected.map(Number),
|
||||
tags: tags.slice(),
|
||||
custom: bootstrap.custom || {},
|
||||
featured: bootstrap.featured || { type: '', data: {} },
|
||||
pay: {
|
||||
enabled: !!pay.enabled,
|
||||
modo: pay.payModo === 'points' ? 'points' : 'cash',
|
||||
price: String(pay.price || '0.00'),
|
||||
points: Number(pay.points || 0),
|
||||
vip1Price: String(pay.vip1Price || '0.00'),
|
||||
vip2Price: String(pay.vip2Price || '0.00'),
|
||||
payLimit: Number(pay.payLimit || 0),
|
||||
downloads: Array.isArray(pay.downloads) ? pay.downloads : [],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function Studio(): JSX.Element {
|
||||
const [draft, setDraft] = useState<Draft>(initialDraft);
|
||||
const [blocks, setBlocks] = useState(() => parse(draft.content || ''));
|
||||
const [saveState, setSaveState] = useState<SaveStateValue>({ state: 'ready', at: '' });
|
||||
const [drawerOpen, setDrawerOpen] = useState(false);
|
||||
const [notice, setNotice] = useState<{ tone: 'ok' | 'error'; text: string } | null>(null);
|
||||
const [recovery, setRecovery] = useState<null | { savedAt: string }>(null);
|
||||
const dirtyRef = useRef(false);
|
||||
|
||||
const capabilities = bootstrap.capabilities || {};
|
||||
const limits: Limits = {
|
||||
titleMin: Number(bootstrap.limits?.titleMin || 1),
|
||||
titleMax: Number(bootstrap.limits?.titleMax || 30),
|
||||
titlePlaceholder: String(bootstrap.limits?.titlePlaceholder || __('请输入标题', 'jio')),
|
||||
priceMin: Number(bootstrap.pay?.priceMin || 0),
|
||||
priceMax: Number(bootstrap.pay?.priceMax || 0),
|
||||
pointsMin: Number(bootstrap.pay?.pointsMin || 0),
|
||||
pointsMax: Number(bootstrap.pay?.pointsMax || 0),
|
||||
};
|
||||
const isPublishedEdit = !!bootstrap.isPublished;
|
||||
|
||||
const patchDraft = useCallback((patch: Partial<Draft>) => {
|
||||
dirtyRef.current = true;
|
||||
setDraft((current) => ({ ...current, ...patch }));
|
||||
}, []);
|
||||
|
||||
const onChangeBlocks = useCallback((next: any[]) => {
|
||||
dirtyRef.current = true;
|
||||
setBlocks(next);
|
||||
}, []);
|
||||
|
||||
const serialized = useMemo(() => serialize(blocks), [blocks]);
|
||||
const words = useMemo(() => countWords(serialized.replace(/<[^>]*>/g, ' '), 'words', {}), [serialized]);
|
||||
|
||||
const buildPayload = useCallback(
|
||||
(extra: Record<string, any> = {}) => ({
|
||||
post_id: draft.postId,
|
||||
version_id: draft.versionId,
|
||||
rev: draft.rev,
|
||||
title: draft.title,
|
||||
excerpt: draft.excerpt,
|
||||
content: serialized,
|
||||
categories: draft.categories,
|
||||
tags: draft.tags,
|
||||
custom: draft.custom,
|
||||
featured: draft.featured,
|
||||
pay: normalizePayForRequest(draft.pay),
|
||||
...extra,
|
||||
}),
|
||||
[draft, serialized]
|
||||
);
|
||||
|
||||
const save = useCallback(
|
||||
async (autosave = false): Promise<boolean> => {
|
||||
if (!dirtyRef.current && (draft.postId > 0 || draft.versionId > 0)) {
|
||||
return true;
|
||||
}
|
||||
// 空文档不触发自动保存:服务端会拒绝无标题/无内容的写入,
|
||||
// 保留本地快照即可,避免把“保存失败”当成真的故障。
|
||||
const hasDocument = draft.title.trim() !== '' || serialized.replace(/<[^>]*>/g, '').trim() !== '';
|
||||
if (autosave && !hasDocument) {
|
||||
return true;
|
||||
}
|
||||
setSaveState({ state: 'saving', at: '' });
|
||||
try {
|
||||
const response = await apiPost(bootstrap.creator.saveUrl, buildPayload({ autosave }), nonce);
|
||||
const savedId = Number(response.post_id || draft.postId || 0);
|
||||
const versionId = Number(response.version_id || draft.versionId || 0);
|
||||
const rev = Number(response.rev || response.versionRev || draft.rev || 0);
|
||||
dirtyRef.current = false;
|
||||
setDraft((current) => ({ ...current, postId: savedId, versionId, rev }));
|
||||
setSaveState({ state: 'saved', at: new Date().toLocaleTimeString() });
|
||||
return true;
|
||||
} catch (error: any) {
|
||||
setSaveState({ state: error?.status === 409 ? 'conflict' : 'error', at: '' });
|
||||
return false;
|
||||
}
|
||||
},
|
||||
[buildPayload, draft.postId, draft.versionId, draft.rev]
|
||||
);
|
||||
|
||||
const submit = useCallback(
|
||||
async (publishNow: boolean): Promise<void> => {
|
||||
setSaveState({ state: 'submitting', at: '' });
|
||||
try {
|
||||
// 站点启用「前台投稿」人机验证时,先完成挑战再提交;
|
||||
// 服务端仍会独立校验证明,前端只是把凭证带过去。
|
||||
let captchaProof = '';
|
||||
const captcha = (window as any).JioCaptcha;
|
||||
if (bootstrap.captcha?.enabled && captcha && typeof captcha.run === 'function') {
|
||||
const payload = await captcha.run('front_submit');
|
||||
if (payload === null) {
|
||||
setSaveState({ state: 'ready', at: '' });
|
||||
setNotice({ tone: 'error', text: __('请先完成人机验证', 'jio') });
|
||||
return;
|
||||
}
|
||||
captchaProof = String(payload?.jio_captcha_proof || '');
|
||||
}
|
||||
const response = await apiPost(
|
||||
bootstrap.creator.submitUrl,
|
||||
buildPayload({ publish_now: publishNow, captcha_proof: captchaProof }),
|
||||
nonce
|
||||
);
|
||||
dirtyRef.current = false;
|
||||
setSaveState({ state: 'submitted', at: '' });
|
||||
setNotice({ tone: 'ok', text: String(response.message || __('已提交', 'jio')) });
|
||||
setDrawerOpen(false);
|
||||
const target = response.url || response.goto || bootstrap.urls?.center;
|
||||
if (target) {
|
||||
window.setTimeout(() => {
|
||||
window.location.href = target;
|
||||
}, 900);
|
||||
}
|
||||
} catch (error: any) {
|
||||
setSaveState({ state: 'error', at: '' });
|
||||
setNotice({ tone: 'error', text: String(error?.message || __('提交失败', 'jio')) });
|
||||
}
|
||||
},
|
||||
[buildPayload]
|
||||
);
|
||||
|
||||
const preview = useCallback(async (): Promise<void> => {
|
||||
const saved = await save(false);
|
||||
if (!saved) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const response = await apiPost(
|
||||
bootstrap.creator.previewUrl,
|
||||
{ post_id: draft.postId, version_id: draft.versionId },
|
||||
nonce
|
||||
);
|
||||
if (response.url) {
|
||||
window.open(String(response.url), '_blank', 'noopener');
|
||||
}
|
||||
} catch (error: any) {
|
||||
setNotice({ tone: 'error', text: String(error?.message || __('预览失败', 'jio')) });
|
||||
}
|
||||
}, [draft.postId, draft.versionId, save]);
|
||||
|
||||
const { markLocalSaved, clear } = useLocalRecovery({
|
||||
key: STORAGE_KEY,
|
||||
snapshot: { title: draft.title, content: serialized, at: new Date().toISOString() },
|
||||
onFound: (savedAt: string) => setRecovery({ savedAt }),
|
||||
});
|
||||
|
||||
const autosave = useAutosave({
|
||||
enabled: !!capabilities.isLoggedIn,
|
||||
onSave: async () => {
|
||||
const ok = await save(true);
|
||||
if (ok) {
|
||||
clear();
|
||||
}
|
||||
return ok;
|
||||
},
|
||||
onLocal: markLocalSaved,
|
||||
});
|
||||
|
||||
const autosaveSchedule = autosave.schedule;
|
||||
|
||||
useEffect(() => {
|
||||
if (dirtyRef.current) {
|
||||
autosaveSchedule();
|
||||
}
|
||||
}, [draft, serialized, autosaveSchedule]);
|
||||
|
||||
useEffect(() => {
|
||||
const beforeUnload = (event: BeforeUnloadEvent) => {
|
||||
if (!dirtyRef.current) {
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
event.returnValue = '';
|
||||
};
|
||||
window.addEventListener('beforeunload', beforeUnload);
|
||||
return () => window.removeEventListener('beforeunload', beforeUnload);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const onKey = (event: KeyboardEvent) => {
|
||||
if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === 's') {
|
||||
event.preventDefault();
|
||||
void save(false);
|
||||
}
|
||||
};
|
||||
window.addEventListener('keydown', onKey);
|
||||
return () => window.removeEventListener('keydown', onKey);
|
||||
}, [save]);
|
||||
|
||||
const restore = useCallback(() => {
|
||||
try {
|
||||
const raw = window.localStorage.getItem(STORAGE_KEY);
|
||||
if (raw) {
|
||||
const parsed = JSON.parse(raw);
|
||||
if (typeof parsed.title === 'string') {
|
||||
dirtyRef.current = true;
|
||||
setDraft((current) => ({ ...current, title: parsed.title }));
|
||||
}
|
||||
if (typeof parsed.content === 'string') {
|
||||
dirtyRef.current = true;
|
||||
setBlocks(parse(parsed.content));
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
// 快照损坏时忽略,不影响服务端内容。
|
||||
}
|
||||
setRecovery(null);
|
||||
}, []);
|
||||
|
||||
const selectedBlockCount = useSelect(
|
||||
(select: any) => select('core/block-editor').getBlockCount(),
|
||||
[]
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="jio-creator" data-status={bootstrap.status || ''} data-blocks={selectedBlockCount}>
|
||||
<header className="jio-creator__bar">
|
||||
<a className="jio-creator__back" href={bootstrap.urls?.center || '/'}>
|
||||
<i className="fa fas fa-angle-left" aria-hidden="true" />
|
||||
<span>{__('返回', 'jio')}</span>
|
||||
</a>
|
||||
<div className="jio-creator__brand">Jio Creator Studio</div>
|
||||
<div className="jio-creator__actions">
|
||||
<SaveState value={saveState} />
|
||||
<button type="button" className="jio-creator__ghost" onClick={() => void preview()}>
|
||||
{__('预览', 'jio')}
|
||||
</button>
|
||||
<button type="button" className="jio-creator__primary" onClick={() => setDrawerOpen(true)}>
|
||||
{isPublishedEdit ? __('提交改稿', 'jio') : __('发布', 'jio')}
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{recovery && (
|
||||
<div className="jio-creator__notice" role="status">
|
||||
<span>{__('发现本地未同步的草稿。', 'jio')}</span>
|
||||
<button type="button" onClick={restore}>{__('恢复', 'jio')}</button>
|
||||
<button type="button" onClick={() => setRecovery(null)}>{__('忽略', 'jio')}</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{notice && (
|
||||
<div className={`jio-creator__notice is-${notice.tone}`} role="status">
|
||||
<span>{notice.text}</span>
|
||||
<button type="button" onClick={() => setNotice(null)} aria-label={__('关闭', 'jio')}>
|
||||
<i className="fa fas fa-times" aria-hidden="true" />
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{isPublishedEdit && (
|
||||
<p className="jio-creator__hint">
|
||||
{__('这篇改稿不会立即覆盖线上文章;审核通过后才会替换。', 'jio')}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<main className="jio-creator__canvas">
|
||||
<label className="jio-creator__title">
|
||||
<span className="screen-reader-text">{__('文章标题', 'jio')}</span>
|
||||
<textarea
|
||||
value={draft.title}
|
||||
onChange={(event) => patchDraft({ title: event.target.value })}
|
||||
rows={1}
|
||||
placeholder={limits.titlePlaceholder || __('请输入标题', 'jio')}
|
||||
maxLength={(Number(limits.titleMax) || 30) * 4}
|
||||
/>
|
||||
</label>
|
||||
|
||||
<label className="jio-creator__excerpt">
|
||||
<span>{__('摘要(可选)', 'jio')}</span>
|
||||
<textarea
|
||||
value={draft.excerpt}
|
||||
onChange={(event) => patchDraft({ excerpt: event.target.value })}
|
||||
rows={2}
|
||||
placeholder={__('一句话概括这篇文章', 'jio')}
|
||||
/>
|
||||
</label>
|
||||
|
||||
<div className="jio-creator__editor">
|
||||
<BlockEditorProvider
|
||||
value={blocks}
|
||||
onInput={onChangeBlocks}
|
||||
onChange={onChangeBlocks}
|
||||
settings={{
|
||||
hasFixedToolbar: false,
|
||||
supportsLayout: false,
|
||||
mediaUpload: (window as any).jioCreatorMediaUpload,
|
||||
}}
|
||||
>
|
||||
<BlockTools>
|
||||
<BlockList />
|
||||
</BlockTools>
|
||||
<aside className="jio-creator__inspector" aria-label={__('区块设置', 'jio')}>
|
||||
<BlockInspector />
|
||||
</aside>
|
||||
</BlockEditorProvider>
|
||||
</div>
|
||||
|
||||
<footer className="jio-creator__footer">
|
||||
<span>{__('字数', 'jio')}:{words}</span>
|
||||
<span>
|
||||
{__('约', 'jio')} {Math.max(1, Math.round(words / 400))} {__('分钟阅读', 'jio')}
|
||||
</span>
|
||||
</footer>
|
||||
</main>
|
||||
|
||||
{drawerOpen && (
|
||||
<PublishDrawer
|
||||
draft={draft}
|
||||
setDraft={patchDraft}
|
||||
capabilities={capabilities}
|
||||
limits={limits}
|
||||
taxonomy={{
|
||||
categories: (bootstrap.categories && bootstrap.categories.items) || [],
|
||||
tags: !!bootstrap.tags?.enabled,
|
||||
customDefs: bootstrap.customDefs || [],
|
||||
}}
|
||||
isPublishedEdit={isPublishedEdit}
|
||||
onClose={() => setDrawerOpen(false)}
|
||||
onSaveDraft={() => void save(false)}
|
||||
onSubmit={(publishNow: boolean) => void submit(publishNow)}
|
||||
privateStorage={!!bootstrap.privateStorage}
|
||||
privateUploads={bootstrap.privateUploads || []}
|
||||
captcha={!!bootstrap.captcha?.enabled}
|
||||
saving={saveState.state === 'saving' || saveState.state === 'submitting'}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function mount() {
|
||||
const target = document.getElementById('jio-creator-studio');
|
||||
if (!target) {
|
||||
return;
|
||||
}
|
||||
installMediaUploadBridge(bootstrap, nonce);
|
||||
target.classList.add('is-ready');
|
||||
createRoot(target).render(<Studio />);
|
||||
}
|
||||
|
||||
if (document.readyState === 'loading') {
|
||||
document.addEventListener('DOMContentLoaded', mount);
|
||||
} else {
|
||||
mount();
|
||||
}
|
||||
|
||||
export { Studio };
|
||||
@@ -0,0 +1,512 @@
|
||||
/**
|
||||
* 发布配置抽屉。
|
||||
*
|
||||
* 封面、分类、摘要、付费与资料附件都只在这里出现,正文画布保持干净;
|
||||
* 手机端以全屏面板呈现。所有字段与权限来自服务端 bootstrap,前端不自行放大权限。
|
||||
*
|
||||
* @package Jio
|
||||
*/
|
||||
|
||||
import { useEffect, useMemo, useRef, useState } from '@wordpress/element';
|
||||
import { __, sprintf } from '@wordpress/i18n';
|
||||
|
||||
import { apiUpload } from '../services/api';
|
||||
|
||||
type Featured = { type: string; data: Record<string, any>; mediaId?: number };
|
||||
type PayState = {
|
||||
enabled: boolean;
|
||||
modo: 'cash' | 'points';
|
||||
price: string;
|
||||
points: number;
|
||||
vip1Price: string;
|
||||
vip2Price: string;
|
||||
payLimit: number;
|
||||
downloads: Array<Record<string, any>>;
|
||||
};
|
||||
|
||||
type Draft = {
|
||||
postId: number;
|
||||
title: string;
|
||||
excerpt: string;
|
||||
categories: number[];
|
||||
tags: string[];
|
||||
custom: Record<string, string[]>;
|
||||
featured: Featured;
|
||||
pay: PayState;
|
||||
};
|
||||
|
||||
type Capabilities = Record<string, boolean>;
|
||||
|
||||
type Limits = {
|
||||
titleMin?: number;
|
||||
titleMax?: number;
|
||||
priceMin?: number;
|
||||
priceMax?: number;
|
||||
pointsMin?: number;
|
||||
pointsMax?: number;
|
||||
};
|
||||
|
||||
type Props = {
|
||||
draft: Draft;
|
||||
setDraft: (patch: Partial<Draft>) => void;
|
||||
capabilities: Capabilities;
|
||||
limits: Limits;
|
||||
captcha: boolean;
|
||||
taxonomy: {
|
||||
categories: Array<{ id: number; name: string }>;
|
||||
tags: boolean;
|
||||
customDefs: Array<{ key: string; name: string; values: Array<{ key: string; name: string }> }>;
|
||||
};
|
||||
isPublishedEdit: boolean;
|
||||
onClose: () => void;
|
||||
onSaveDraft: () => void;
|
||||
onSubmit: (publishNow: boolean) => void;
|
||||
privateStorage: boolean;
|
||||
privateUploads: Array<Record<string, any>>;
|
||||
saving: boolean;
|
||||
};
|
||||
|
||||
const bootstrap: Record<string, any> = window['jioCreatorStudio'] || {};
|
||||
const nonce: string = bootstrap.nonce || '';
|
||||
|
||||
export function PublishDrawer(props: Props) {
|
||||
const {
|
||||
draft,
|
||||
setDraft,
|
||||
capabilities,
|
||||
limits,
|
||||
taxonomy,
|
||||
isPublishedEdit,
|
||||
onClose,
|
||||
onSaveDraft,
|
||||
onSubmit,
|
||||
privateStorage,
|
||||
privateUploads,
|
||||
saving,
|
||||
captcha,
|
||||
} = props;
|
||||
|
||||
const [tagInput, setTagInput] = useState('');
|
||||
const [uploadError, setUploadError] = useState('');
|
||||
const [uploading, setUploading] = useState(false);
|
||||
const coverInput = useRef<HTMLInputElement | null>(null);
|
||||
const fileInput = useRef<HTMLInputElement | null>(null);
|
||||
const captchaSlot = useRef<HTMLDivElement | null>(null);
|
||||
|
||||
// 人机验证由 PHP 渲染(脚本在页面加载时按 uid 注册实例),这里只把挂载点
|
||||
// 移进抽屉,保证验证控件在用户提交时可见、可交互。
|
||||
useEffect(() => {
|
||||
const slot = captchaSlot.current;
|
||||
const mount = document.getElementById('jio-creator-captcha');
|
||||
if (!slot || !mount) {
|
||||
return undefined;
|
||||
}
|
||||
const previous = mount.parentElement;
|
||||
slot.appendChild(mount);
|
||||
mount.removeAttribute('hidden');
|
||||
return () => {
|
||||
if (previous) {
|
||||
previous.appendChild(mount);
|
||||
mount.setAttribute('hidden', '');
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
|
||||
const titleLength = useMemo(() => (draft.title || '').trim().length, [draft.title]);
|
||||
const canSubmit = titleLength >= Number(limits.titleMin || 1);
|
||||
|
||||
const toggleCategory = (id: number) => {
|
||||
const has = draft.categories.includes(id);
|
||||
setDraft({
|
||||
categories: has ? draft.categories.filter((value) => value !== id) : [...draft.categories, id],
|
||||
});
|
||||
};
|
||||
|
||||
const addTag = () => {
|
||||
const value = tagInput.trim();
|
||||
if (!value) {
|
||||
return;
|
||||
}
|
||||
const next = value
|
||||
.split(/[,,\n]+/u)
|
||||
.map((item) => item.trim())
|
||||
.filter(Boolean);
|
||||
setDraft({ tags: Array.from(new Set([...draft.tags, ...next])) });
|
||||
setTagInput('');
|
||||
};
|
||||
|
||||
const uploadCover = async () => {
|
||||
const file = coverInput.current?.files?.[0];
|
||||
if (!file || !bootstrap.media?.uploadUrl?.image) {
|
||||
return;
|
||||
}
|
||||
setUploadError('');
|
||||
setUploading(true);
|
||||
try {
|
||||
const response = await apiUpload(bootstrap.media.uploadUrl.image, file, nonce);
|
||||
const id = Number(response.attachment_id || response.id || 0);
|
||||
const url = String(response.url || '');
|
||||
if (!id || !url) {
|
||||
throw new Error(__('上传后无法读取图片。', 'jio'));
|
||||
}
|
||||
setDraft({ featured: { type: 'image', mediaId: id, data: { id, url } } });
|
||||
} catch (error: any) {
|
||||
setUploadError(String(error?.message || __('上传失败', 'jio')));
|
||||
} finally {
|
||||
setUploading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const uploadAttachment = async () => {
|
||||
const file = fileInput.current?.files?.[0];
|
||||
if (!file) {
|
||||
return;
|
||||
}
|
||||
setUploadError('');
|
||||
setUploading(true);
|
||||
try {
|
||||
const response = await apiUpload(bootstrap.creator.privateUrl, file, nonce, {
|
||||
post_id: String(draft.postId || 0),
|
||||
});
|
||||
const next = {
|
||||
type: 'protected',
|
||||
assetKey: String(response.asset_key || ''),
|
||||
fileName: String(response.name || file.name),
|
||||
sizeBytes: Number(response.size || file.size),
|
||||
sizeLabel: String(response.size_label || ''),
|
||||
label: '',
|
||||
};
|
||||
setDraft({
|
||||
pay: { ...draft.pay, enabled: true, downloads: [...draft.pay.downloads, next] },
|
||||
});
|
||||
if (fileInput.current) {
|
||||
fileInput.current.value = '';
|
||||
}
|
||||
} catch (error: any) {
|
||||
setUploadError(String(error?.message || __('资料上传失败', 'jio')));
|
||||
} finally {
|
||||
setUploading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const removeDownload = (index: number) => {
|
||||
setDraft({
|
||||
pay: { ...draft.pay, downloads: draft.pay.downloads.filter((_, i) => i !== index) },
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="jio-creator-drawer" role="dialog" aria-modal="true" aria-labelledby="jio-creator-publish-title">
|
||||
<button type="button" className="jio-creator-drawer__backdrop" aria-label={__('关闭', 'jio')} onClick={onClose} />
|
||||
<div className="jio-creator-drawer__panel">
|
||||
<header className="jio-creator-drawer__head">
|
||||
<h2 id="jio-creator-publish-title">{isPublishedEdit ? __('提交改稿', 'jio') : __('发布文章', 'jio')}</h2>
|
||||
<button type="button" className="jio-creator-drawer__close" onClick={onClose} aria-label={__('关闭', 'jio')}>
|
||||
<i className="fa fas fa-times" aria-hidden="true" />
|
||||
</button>
|
||||
</header>
|
||||
|
||||
<div className="jio-creator-drawer__body">
|
||||
{isPublishedEdit && (
|
||||
<p className="jio-creator-drawer__note">
|
||||
{__('审核通过前,读者看到的仍然是当前线上版本。', 'jio')}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<section className="jio-creator-field">
|
||||
<h3>{__('封面', 'jio')}</h3>
|
||||
{draft.featured?.data?.url ? (
|
||||
<div className="jio-creator-cover">
|
||||
<img src={String(draft.featured.data.url)} alt="" />
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setDraft({ featured: { type: '', data: {} } })}
|
||||
aria-label={__('移除封面', 'jio')}
|
||||
>
|
||||
<i className="fa fas fa-times" aria-hidden="true" />
|
||||
</button>
|
||||
</div>
|
||||
) : capabilities.canUploadImage ? (
|
||||
<label className="jio-creator-cover-empty">
|
||||
<input
|
||||
ref={coverInput}
|
||||
type="file"
|
||||
accept="image/*"
|
||||
onChange={() => void uploadCover()}
|
||||
disabled={uploading}
|
||||
/>
|
||||
<i className="fa fas fa-plus" aria-hidden="true" />
|
||||
<span>{uploading ? __('上传中…', 'jio') : __('上传封面', 'jio')}</span>
|
||||
</label>
|
||||
) : (
|
||||
<p className="jio-creator-muted">{__('当前账号不能设置封面。', 'jio')}</p>
|
||||
)}
|
||||
</section>
|
||||
|
||||
<section className="jio-creator-field">
|
||||
<h3>{__('分类', 'jio')}</h3>
|
||||
<div className="jio-creator-chips">
|
||||
{taxonomy.categories.length === 0 && <span className="jio-creator-muted">{__('暂无可选分类', 'jio')}</span>}
|
||||
{taxonomy.categories.map((category) => (
|
||||
<label
|
||||
key={category.id}
|
||||
className={`jio-creator-chip${draft.categories.includes(category.id) ? ' is-active' : ''}`}
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={draft.categories.includes(category.id)}
|
||||
onChange={() => toggleCategory(category.id)}
|
||||
/>
|
||||
<span>{category.name}</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{taxonomy.tags && (
|
||||
<section className="jio-creator-field">
|
||||
<h3>{__('标签', 'jio')}</h3>
|
||||
<div className="jio-creator-chips">
|
||||
{draft.tags.map((tag) => (
|
||||
<span key={tag} className="jio-creator-chip is-active">
|
||||
<span>{tag}</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setDraft({ tags: draft.tags.filter((value) => value !== tag) })}
|
||||
aria-label={sprintf(__('移除标签 %s', 'jio'), tag)}
|
||||
>
|
||||
<i className="fa fas fa-times" aria-hidden="true" />
|
||||
</button>
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
<div className="jio-creator-inline">
|
||||
<input
|
||||
type="text"
|
||||
value={tagInput}
|
||||
placeholder={__('输入标签,逗号分隔', 'jio')}
|
||||
onChange={(event) => setTagInput(event.target.value)}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === 'Enter') {
|
||||
event.preventDefault();
|
||||
addTag();
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<button type="button" onClick={addTag}>{__('添加', 'jio')}</button>
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
|
||||
{taxonomy.customDefs.map((dimension) => (
|
||||
<section className="jio-creator-field" key={dimension.key}>
|
||||
<h3>{dimension.name}</h3>
|
||||
<div className="jio-creator-chips">
|
||||
{dimension.values.map((value) => {
|
||||
const current = draft.custom[dimension.key] || [];
|
||||
const active = current.includes(value.key);
|
||||
return (
|
||||
<label key={value.key} className={`jio-creator-chip${active ? ' is-active' : ''}`}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={active}
|
||||
onChange={() =>
|
||||
setDraft({
|
||||
custom: {
|
||||
...draft.custom,
|
||||
[dimension.key]: active
|
||||
? current.filter((item) => item !== value.key)
|
||||
: [...current, value.key],
|
||||
},
|
||||
})
|
||||
}
|
||||
/>
|
||||
<span>{value.name}</span>
|
||||
</label>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</section>
|
||||
))}
|
||||
|
||||
{capabilities.canPay && (
|
||||
<section className="jio-creator-field">
|
||||
<div className="jio-creator-switch">
|
||||
<div>
|
||||
<h3>{__('付费内容', 'jio')}</h3>
|
||||
<p className="jio-creator-muted">{__('开启后,未购买读者只能看到免费部分。', 'jio')}</p>
|
||||
</div>
|
||||
<label className="jio-creator-toggle">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={draft.pay.enabled}
|
||||
onChange={(event) => setDraft({ pay: { ...draft.pay, enabled: event.target.checked } })}
|
||||
/>
|
||||
<span aria-hidden="true" />
|
||||
</label>
|
||||
</div>
|
||||
|
||||
{draft.pay.enabled && (
|
||||
<div className="jio-creator-pay">
|
||||
<div className="jio-creator-inline">
|
||||
<label>
|
||||
<input
|
||||
type="radio"
|
||||
checked={draft.pay.modo === 'cash'}
|
||||
onChange={() => setDraft({ pay: { ...draft.pay, modo: 'cash' } })}
|
||||
/>
|
||||
<span>{__('现金', 'jio')}</span>
|
||||
</label>
|
||||
<label>
|
||||
<input
|
||||
type="radio"
|
||||
checked={draft.pay.modo === 'points'}
|
||||
onChange={() => setDraft({ pay: { ...draft.pay, modo: 'points' } })}
|
||||
/>
|
||||
<span>{__('积分', 'jio')}</span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
{draft.pay.modo === 'cash' ? (
|
||||
<label className="jio-creator-input">
|
||||
<span>{__('价格', 'jio')}</span>
|
||||
<input
|
||||
type="number"
|
||||
min={Number(limits.priceMin || 0)}
|
||||
step="0.01"
|
||||
value={draft.pay.price}
|
||||
onChange={(event) => setDraft({ pay: { ...draft.pay, price: event.target.value } })}
|
||||
/>
|
||||
</label>
|
||||
) : (
|
||||
<label className="jio-creator-input">
|
||||
<span>{__('积分价格', 'jio')}</span>
|
||||
<input
|
||||
type="number"
|
||||
min={0}
|
||||
step="1"
|
||||
value={draft.pay.points}
|
||||
onChange={(event) =>
|
||||
setDraft({ pay: { ...draft.pay, points: Number(event.target.value) || 0 } })
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
)}
|
||||
|
||||
{capabilities.canPayDownload && (
|
||||
<div className="jio-creator-attachments">
|
||||
<div className="jio-creator-attachments__head">
|
||||
<h4>{__('资料附件', 'jio')}</h4>
|
||||
{privateStorage ? (
|
||||
<label className="jio-creator-upload">
|
||||
<input
|
||||
ref={fileInput}
|
||||
type="file"
|
||||
onChange={() => void uploadAttachment()}
|
||||
disabled={uploading}
|
||||
/>
|
||||
<span>{uploading ? __('上传中…', 'jio') : __('添加 PDF / ZIP', 'jio')}</span>
|
||||
</label>
|
||||
) : (
|
||||
<p className="jio-creator-muted">
|
||||
{__('私有附件存储尚未配置,暂时不能上传付费资料。', 'jio')}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{uploadError && <p className="jio-creator-error">{uploadError}</p>}
|
||||
|
||||
{draft.pay.downloads.length > 0 && (
|
||||
<ul className="jio-creator-files">
|
||||
{draft.pay.downloads.map((row, index) => (
|
||||
<li key={`${row.assetKey || row.url}-${index}`}>
|
||||
<span className="jio-creator-files__name">
|
||||
{row.assetKey ? (
|
||||
<>
|
||||
<i className="fa fas fa-lock" aria-hidden="true" />
|
||||
{row.fileName || row.label || __('受保护资料', 'jio')}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<i className="fa fas fa-link" aria-hidden="true" />
|
||||
{row.label || row.url}
|
||||
</>
|
||||
)}
|
||||
</span>
|
||||
{row.sizeLabel && <span className="jio-creator-muted">{row.sizeLabel}</span>}
|
||||
<button type="button" onClick={() => removeDownload(index)} aria-label={__('移除', 'jio')}>
|
||||
<i className="fa fas fa-times" aria-hidden="true" />
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
|
||||
{privateUploads.length > 0 && (
|
||||
<details className="jio-creator-reuse">
|
||||
<summary>{__('从已上传资料中选择', 'jio')}</summary>
|
||||
<ul>
|
||||
{privateUploads
|
||||
.filter((item) => !draft.pay.downloads.some((row) => row.assetKey === item.assetKey))
|
||||
.map((item) => (
|
||||
<li key={item.assetKey}>
|
||||
<span>{item.fileName}</span>
|
||||
<span className="jio-creator-muted">{item.sizeLabel}</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() =>
|
||||
setDraft({
|
||||
pay: {
|
||||
...draft.pay,
|
||||
enabled: true,
|
||||
downloads: [...draft.pay.downloads, { ...item, type: 'protected' }],
|
||||
},
|
||||
})
|
||||
}
|
||||
>
|
||||
{__('使用', 'jio')}
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</details>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
)}
|
||||
|
||||
{!capabilities.canPay && capabilities.canSaveDraft && (
|
||||
<p className="jio-creator-muted">{__('当前账号不能设置付费内容。', 'jio')}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<footer className="jio-creator-drawer__foot">
|
||||
{captcha && (
|
||||
<div className="jio-creator-drawer__captcha" ref={captchaSlot} />
|
||||
)}
|
||||
<div className="jio-creator-drawer__actions">
|
||||
<button type="button" className="jio-creator-ghost" onClick={onSaveDraft} disabled={saving}>
|
||||
{__('保存草稿', 'jio')}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="jio-creator-primary"
|
||||
onClick={() => onSubmit(false)}
|
||||
disabled={saving || !canSubmit}
|
||||
>
|
||||
{isPublishedEdit ? __('提交审核', 'jio') : capabilities.canPublishNow ? __('发布', 'jio') : __('提交审核', 'jio')}
|
||||
</button>
|
||||
{capabilities.canPublishNow && (
|
||||
<button type="button" className="jio-creator-link" onClick={() => onSubmit(true)} disabled={saving || !canSubmit}>
|
||||
{__('立即发布', 'jio')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</footer>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
/**
|
||||
* Creator Studio 的 REST 访问层。
|
||||
*
|
||||
* 所有请求都带 `X-WP-Nonce`;服务端仍以 Jio 能力矩阵与文章归属做最终判定。
|
||||
*
|
||||
* @package Jio
|
||||
*/
|
||||
|
||||
export type ApiError = Error & { status?: number; code?: string; data?: unknown };
|
||||
|
||||
function toError(payload: any, status: number): ApiError {
|
||||
const message =
|
||||
(payload && (payload.message || payload.error)) ||
|
||||
(status === 401
|
||||
? '登录状态已失效,请刷新页面重新登录。'
|
||||
: '请求失败,请稍后重试。');
|
||||
const error = new Error(String(message)) as ApiError;
|
||||
error.status = status;
|
||||
error.code = payload && payload.code ? String(payload.code) : '';
|
||||
error.data = payload;
|
||||
return error;
|
||||
}
|
||||
|
||||
async function readJson(response: Response): Promise<any> {
|
||||
try {
|
||||
return await response.json();
|
||||
} catch (error) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function apiGet(url: string, nonce: string): Promise<any> {
|
||||
const response = await fetch(url, {
|
||||
credentials: 'same-origin',
|
||||
headers: { 'X-WP-Nonce': nonce },
|
||||
});
|
||||
const payload = await readJson(response);
|
||||
if (!response.ok) {
|
||||
throw toError(payload, response.status);
|
||||
}
|
||||
return payload;
|
||||
}
|
||||
|
||||
export async function apiPost(url: string, body: Record<string, unknown>, nonce: string): Promise<any> {
|
||||
const response = await fetch(url, {
|
||||
method: 'POST',
|
||||
credentials: 'same-origin',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-WP-Nonce': nonce,
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
const payload = await readJson(response);
|
||||
if (!response.ok) {
|
||||
throw toError(payload, response.status);
|
||||
}
|
||||
return payload;
|
||||
}
|
||||
|
||||
export async function apiUpload(url: string, file: File, nonce: string, fields: Record<string, string> = {}): Promise<any> {
|
||||
const body = new FormData();
|
||||
body.append('file', file);
|
||||
Object.entries(fields).forEach(([key, value]) => body.append(key, value));
|
||||
|
||||
const response = await fetch(url, {
|
||||
method: 'POST',
|
||||
credentials: 'same-origin',
|
||||
headers: { 'X-WP-Nonce': nonce },
|
||||
body,
|
||||
});
|
||||
const payload = await readJson(response);
|
||||
if (!response.ok) {
|
||||
throw toError(payload, response.status);
|
||||
}
|
||||
return payload;
|
||||
}
|
||||
|
||||
export const wpJson = (value: unknown): string => JSON.stringify(value);
|
||||
@@ -0,0 +1,68 @@
|
||||
/**
|
||||
* 编辑器媒体上传桥。
|
||||
*
|
||||
* Gutenberg 核心图片区块通过 block-editor settings.mediaUpload 上传;这里把它接到
|
||||
* Jio 前台上传接口,保留 Jio 的能力校验、文件校验与待认领生命周期,而不是让区块
|
||||
* 直接走 /wp/v2/media。
|
||||
*
|
||||
* @package Jio
|
||||
*/
|
||||
|
||||
export function installMediaUploadBridge(bootstrap: Record<string, any>, nonce: string) {
|
||||
const url = bootstrap?.blocks?.mediaUploadUrl;
|
||||
if (!url) {
|
||||
return;
|
||||
}
|
||||
const maxBytes = Number(bootstrap?.media?.maxBytes || 0);
|
||||
const allowed = bootstrap?.capabilities?.canUploadImage !== false;
|
||||
|
||||
window['jioCreatorMediaUpload'] = (payload: any) => {
|
||||
const { file, onError, onSuccess } = payload || {};
|
||||
if (!file || typeof file === 'object' && !(file instanceof File)) {
|
||||
onError?.('无效的文件');
|
||||
return;
|
||||
}
|
||||
if (!allowed) {
|
||||
onError?.('当前账号不能上传图片');
|
||||
return;
|
||||
}
|
||||
if (maxBytes > 0 && file.size > maxBytes) {
|
||||
onError?.('图片大小超过限制');
|
||||
return;
|
||||
}
|
||||
|
||||
const body = new FormData();
|
||||
body.append('file', file);
|
||||
|
||||
fetch(url, {
|
||||
method: 'POST',
|
||||
credentials: 'same-origin',
|
||||
headers: { 'X-WP-Nonce': nonce },
|
||||
body,
|
||||
})
|
||||
.then((response) =>
|
||||
response.json().then((data) => {
|
||||
if (!response.ok) {
|
||||
throw new Error((data && data.message) || '上传失败');
|
||||
}
|
||||
return data;
|
||||
})
|
||||
)
|
||||
.then((data) => {
|
||||
onSuccess?.({
|
||||
id: Number(data.attachment_id || data.id || 0),
|
||||
url: String(data.url || ''),
|
||||
alt: '',
|
||||
caption: '',
|
||||
title: String(data.title || data.name || ''),
|
||||
width: Number(data.width || 0),
|
||||
height: Number(data.height || 0),
|
||||
sizes: data.sizes || {},
|
||||
mime: String(data.mime || ''),
|
||||
});
|
||||
})
|
||||
.catch((error) => {
|
||||
onError?.(error?.message || '上传失败');
|
||||
});
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,825 @@
|
||||
/**
|
||||
* Jio Creator Studio — 沉浸式写作工作台。
|
||||
*
|
||||
* 视觉方向:纸面写作而不是后台配置。单一深青绿用于“保存/发布”这类推进动作,
|
||||
* 其余保持低对比;发布设置全部收进抽屉,正文区域只有标题、摘要与画布。
|
||||
*/
|
||||
|
||||
$ink: #243330;
|
||||
$ink-soft: #5c6b66;
|
||||
$paper: #fafbfa;
|
||||
$line: #e2e9e5;
|
||||
$accent: #267665;
|
||||
$accent-strong: #1d5f52;
|
||||
$warn: #b4573f;
|
||||
|
||||
/*
|
||||
* 创作页接管整屏:隐藏主题头部/底部与浮动入口,避免与工作台顶栏重复。
|
||||
* 只在投稿模板的 body class 下生效,不影响其他页面。
|
||||
*/
|
||||
.jio-page-submit {
|
||||
background: $paper;
|
||||
}
|
||||
|
||||
.jio-page-submit .header,
|
||||
.jio-page-submit .footer,
|
||||
.jio-page-submit .float-btn,
|
||||
.jio-page-submit .footer-tabbar,
|
||||
.jio-page-submit .jio-float-buttons {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.jio-page-submit #main-content.container {
|
||||
max-width: none;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
#jio-creator-studio.is-ready {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.jio-creator {
|
||||
--jc-ink: #{$ink};
|
||||
--jc-ink-soft: #{$ink-soft};
|
||||
--jc-paper: #{$paper};
|
||||
--jc-line: #{$line};
|
||||
--jc-accent: #{$accent};
|
||||
--jc-accent-strong: #{$accent-strong};
|
||||
--jc-warn: #{$warn};
|
||||
--jc-bar: 60px;
|
||||
|
||||
min-height: 100vh;
|
||||
min-height: 100dvh;
|
||||
background: var(--jc-paper);
|
||||
color: var(--jc-ink);
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Noto Sans SC", "PingFang SC", "Microsoft YaHei", sans-serif;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
|
||||
*,
|
||||
*::before,
|
||||
*::after {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
button {
|
||||
font: inherit;
|
||||
color: inherit;
|
||||
}
|
||||
}
|
||||
|
||||
.jio-creator__bar {
|
||||
position: sticky;
|
||||
z-index: 30;
|
||||
top: 0;
|
||||
display: flex;
|
||||
height: var(--jc-bar);
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
padding: 0 clamp(16px, 4vw, 40px);
|
||||
border-bottom: 1px solid var(--jc-line);
|
||||
background: rgba(250, 251, 250, 0.92);
|
||||
backdrop-filter: blur(10px);
|
||||
}
|
||||
|
||||
.jio-creator__back {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
color: var(--jc-ink-soft);
|
||||
text-decoration: none;
|
||||
|
||||
&:hover,
|
||||
&:focus-visible {
|
||||
color: var(--jc-accent);
|
||||
}
|
||||
}
|
||||
|
||||
.jio-creator__brand {
|
||||
margin-right: auto;
|
||||
color: var(--jc-ink-soft);
|
||||
font-size: 13px;
|
||||
letter-spacing: 0.06em;
|
||||
}
|
||||
|
||||
.jio-creator__actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.jio-creator__save {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
color: var(--jc-ink-soft);
|
||||
font-size: 13px;
|
||||
|
||||
> i {
|
||||
color: var(--jc-line);
|
||||
font-size: 7px;
|
||||
}
|
||||
|
||||
time {
|
||||
opacity: 0.7;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
&.is-saved > i {
|
||||
color: var(--jc-accent);
|
||||
}
|
||||
|
||||
&.is-error > i,
|
||||
&.is-conflict > i {
|
||||
color: var(--jc-warn);
|
||||
}
|
||||
|
||||
&.is-error,
|
||||
&.is-conflict {
|
||||
color: var(--jc-warn);
|
||||
}
|
||||
}
|
||||
|
||||
.jio-creator__ghost,
|
||||
.jio-creator__primary,
|
||||
.jio-creator__btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-height: 36px;
|
||||
padding: 0 16px;
|
||||
border: 1px solid transparent;
|
||||
border-radius: 8px;
|
||||
cursor: pointer;
|
||||
font-size: 14px;
|
||||
transition: background 0.18s ease, border-color 0.18s ease, color 0.18s ease;
|
||||
}
|
||||
|
||||
.jio-creator__ghost {
|
||||
border-color: var(--jc-line);
|
||||
background: transparent;
|
||||
|
||||
&:hover,
|
||||
&:focus-visible {
|
||||
border-color: var(--jc-accent);
|
||||
color: var(--jc-accent);
|
||||
}
|
||||
}
|
||||
|
||||
.jio-creator__primary {
|
||||
background: var(--jc-accent);
|
||||
color: #fff;
|
||||
|
||||
&:hover,
|
||||
&:focus-visible {
|
||||
background: var(--jc-accent-strong);
|
||||
}
|
||||
|
||||
&:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
}
|
||||
|
||||
.jio-creator__notice {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
margin: 0 auto;
|
||||
max-width: 820px;
|
||||
padding: 10px 16px;
|
||||
border-bottom: 1px solid var(--jc-line);
|
||||
background: #f1f5f2;
|
||||
color: var(--jc-ink-soft);
|
||||
font-size: 13px;
|
||||
|
||||
> span {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
button {
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: var(--jc-accent);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
&.is-error {
|
||||
background: #fdf2ee;
|
||||
color: var(--jc-warn);
|
||||
}
|
||||
}
|
||||
|
||||
.jio-creator__hint {
|
||||
max-width: 820px;
|
||||
margin: 18px auto 0;
|
||||
padding: 0 clamp(16px, 4vw, 40px);
|
||||
color: var(--jc-ink-soft);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.jio-creator__canvas {
|
||||
width: min(820px, 100%);
|
||||
margin: 0 auto;
|
||||
padding: clamp(24px, 5vw, 56px) clamp(16px, 4vw, 40px) 120px;
|
||||
}
|
||||
|
||||
.jio-creator__title {
|
||||
display: block;
|
||||
margin-bottom: 8px;
|
||||
|
||||
textarea {
|
||||
width: 100%;
|
||||
min-height: 56px;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: var(--jc-ink);
|
||||
font-family: "Songti SC", "Noto Serif SC", "Source Han Serif SC", serif;
|
||||
font-size: clamp(26px, 3.4vw, 34px);
|
||||
font-weight: 600;
|
||||
line-height: 1.35;
|
||||
resize: none;
|
||||
|
||||
&:focus {
|
||||
outline: 0;
|
||||
}
|
||||
|
||||
&::placeholder {
|
||||
color: #b7c2bd;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.jio-creator__excerpt {
|
||||
display: block;
|
||||
margin-bottom: 28px;
|
||||
|
||||
> span {
|
||||
display: block;
|
||||
margin-bottom: 6px;
|
||||
color: var(--jc-ink-soft);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
textarea {
|
||||
width: 100%;
|
||||
padding: 8px 0;
|
||||
border: 0;
|
||||
border-bottom: 1px solid var(--jc-line);
|
||||
background: transparent;
|
||||
color: var(--jc-ink-soft);
|
||||
font-family: inherit;
|
||||
font-size: 15px;
|
||||
line-height: 1.7;
|
||||
resize: none;
|
||||
|
||||
&:focus {
|
||||
border-color: var(--jc-accent);
|
||||
outline: 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.jio-creator__editor {
|
||||
position: relative;
|
||||
|
||||
.block-editor-writing-flow {
|
||||
font-size: 17px;
|
||||
line-height: 1.85;
|
||||
}
|
||||
|
||||
.block-editor-default-block-appender textarea.block-editor-default-block-appender__content {
|
||||
color: #b7c2bd;
|
||||
}
|
||||
|
||||
.block-editor-block-list__layout {
|
||||
padding-bottom: 80px;
|
||||
}
|
||||
|
||||
.wp-block {
|
||||
max-width: none;
|
||||
}
|
||||
}
|
||||
|
||||
.jio-creator__inspector {
|
||||
margin-top: 24px;
|
||||
|
||||
.block-editor-block-inspector {
|
||||
border-top: 1px solid var(--jc-line);
|
||||
padding-top: 16px;
|
||||
}
|
||||
|
||||
.block-editor-block-inspector:empty {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.components-panel__body {
|
||||
border: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.jio-creator__footer {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
padding-top: 20px;
|
||||
border-top: 1px solid var(--jc-line);
|
||||
color: var(--jc-ink-soft);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
/* ---------- 发布抽屉 ---------- */
|
||||
|
||||
.jio-creator-drawer {
|
||||
position: fixed;
|
||||
z-index: 500;
|
||||
inset: 0;
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
.jio-creator-drawer__backdrop {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
border: 0;
|
||||
background: rgba(23, 34, 31, 0.32);
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.jio-creator-drawer__panel {
|
||||
position: relative;
|
||||
display: flex;
|
||||
width: min(460px, 100%);
|
||||
height: 100%;
|
||||
flex-direction: column;
|
||||
background: #fff;
|
||||
box-shadow: -20px 0 60px rgba(20, 32, 28, 0.16);
|
||||
}
|
||||
|
||||
.jio-creator-drawer__head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 20px 24px;
|
||||
border-bottom: 1px solid $line;
|
||||
|
||||
h2 {
|
||||
margin: 0;
|
||||
font-size: 17px;
|
||||
font-weight: 600;
|
||||
}
|
||||
}
|
||||
|
||||
.jio-creator-drawer__close {
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: $ink-soft;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.jio-creator-drawer__body {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
padding: 20px 24px 32px;
|
||||
}
|
||||
|
||||
.jio-creator-drawer__note {
|
||||
margin: 0 0 20px;
|
||||
padding: 12px 14px;
|
||||
border-left: 3px solid $accent;
|
||||
background: #f2f7f4;
|
||||
color: $ink-soft;
|
||||
font-size: 13px;
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.jio-creator-drawer__foot {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
padding: 16px 24px calc(16px + env(safe-area-inset-bottom));
|
||||
border-top: 1px solid $line;
|
||||
background: #fff;
|
||||
|
||||
.jio-creator-primary {
|
||||
flex: 1;
|
||||
}
|
||||
}
|
||||
|
||||
.jio-creator-drawer__actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.jio-creator-drawer__captcha {
|
||||
min-height: 40px;
|
||||
}
|
||||
|
||||
.jio-creator-field {
|
||||
margin-bottom: 26px;
|
||||
|
||||
> h3 {
|
||||
margin: 0 0 10px;
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
color: $ink;
|
||||
}
|
||||
}
|
||||
|
||||
.jio-creator-muted {
|
||||
margin: 0;
|
||||
color: $ink-soft;
|
||||
font-size: 12px;
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.jio-creator-error {
|
||||
margin: 8px 0 0;
|
||||
color: $warn;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.jio-creator-chips {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.jio-creator-chip {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 5px 12px;
|
||||
border: 1px solid $line;
|
||||
border-radius: 999px;
|
||||
color: $ink-soft;
|
||||
font-size: 13px;
|
||||
cursor: pointer;
|
||||
|
||||
input {
|
||||
position: absolute;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
overflow: hidden;
|
||||
clip: rect(0, 0, 0, 0);
|
||||
}
|
||||
|
||||
&.is-active {
|
||||
border-color: $accent;
|
||||
background: #eef5f2;
|
||||
color: $accent-strong;
|
||||
}
|
||||
|
||||
button {
|
||||
border: 0;
|
||||
background: transparent;
|
||||
cursor: pointer;
|
||||
color: inherit;
|
||||
}
|
||||
}
|
||||
|
||||
.jio-creator-inline {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
margin-top: 10px;
|
||||
|
||||
input[type="text"],
|
||||
input:not([type]) {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
input[type="text"],
|
||||
input:not([type]) {
|
||||
height: 36px;
|
||||
padding: 0 12px;
|
||||
border: 1px solid $line;
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
label {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 13px;
|
||||
}
|
||||
}
|
||||
|
||||
.jio-creator-switch {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
|
||||
h3 {
|
||||
margin: 0 0 4px;
|
||||
font-size: 13px;
|
||||
}
|
||||
}
|
||||
|
||||
.jio-creator-toggle {
|
||||
position: relative;
|
||||
flex: 0 0 auto;
|
||||
|
||||
input {
|
||||
position: absolute;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
opacity: 0;
|
||||
}
|
||||
|
||||
span {
|
||||
display: block;
|
||||
width: 42px;
|
||||
height: 24px;
|
||||
border-radius: 999px;
|
||||
background: #d6dfda;
|
||||
transition: background 0.18s ease;
|
||||
|
||||
&::after {
|
||||
display: block;
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
margin: 3px;
|
||||
border-radius: 50%;
|
||||
background: #fff;
|
||||
content: "";
|
||||
transition: transform 0.18s ease;
|
||||
}
|
||||
}
|
||||
|
||||
input:checked + span {
|
||||
background: $accent;
|
||||
}
|
||||
|
||||
input:checked + span::after {
|
||||
transform: translateX(18px);
|
||||
}
|
||||
|
||||
input:focus-visible + span {
|
||||
outline: 2px solid $accent;
|
||||
outline-offset: 2px;
|
||||
}
|
||||
}
|
||||
|
||||
.jio-creator-pay {
|
||||
margin-top: 16px;
|
||||
padding: 16px;
|
||||
border: 1px solid $line;
|
||||
border-radius: 10px;
|
||||
background: #fcfdfc;
|
||||
}
|
||||
|
||||
.jio-creator-input {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
margin-top: 12px;
|
||||
font-size: 13px;
|
||||
|
||||
input {
|
||||
width: 140px;
|
||||
height: 36px;
|
||||
padding: 0 12px;
|
||||
border: 1px solid $line;
|
||||
border-radius: 8px;
|
||||
text-align: right;
|
||||
}
|
||||
}
|
||||
|
||||
.jio-creator-cover {
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
border-radius: 10px;
|
||||
|
||||
img {
|
||||
display: block;
|
||||
width: 100%;
|
||||
aspect-ratio: 2 / 1;
|
||||
object-fit: cover;
|
||||
}
|
||||
|
||||
button {
|
||||
position: absolute;
|
||||
top: 8px;
|
||||
right: 8px;
|
||||
width: 30px;
|
||||
height: 30px;
|
||||
border: 0;
|
||||
border-radius: 50%;
|
||||
background: rgba(0, 0, 0, 0.55);
|
||||
color: #fff;
|
||||
cursor: pointer;
|
||||
}
|
||||
}
|
||||
|
||||
.jio-creator-cover-empty {
|
||||
display: flex;
|
||||
min-height: 120px;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
border: 1px dashed $line;
|
||||
border-radius: 10px;
|
||||
background: #fafcfb;
|
||||
color: $ink-soft;
|
||||
font-size: 13px;
|
||||
cursor: pointer;
|
||||
|
||||
input {
|
||||
position: absolute;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
opacity: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.jio-creator-attachments {
|
||||
margin-top: 18px;
|
||||
padding-top: 16px;
|
||||
border-top: 1px solid $line;
|
||||
}
|
||||
|
||||
.jio-creator-attachments__head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
|
||||
h4 {
|
||||
margin: 0;
|
||||
font-size: 13px;
|
||||
}
|
||||
}
|
||||
|
||||
.jio-creator-upload {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
min-height: 32px;
|
||||
padding: 0 12px;
|
||||
border: 1px solid $line;
|
||||
border-radius: 8px;
|
||||
color: $accent-strong;
|
||||
font-size: 12px;
|
||||
cursor: pointer;
|
||||
|
||||
input {
|
||||
position: absolute;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
opacity: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.jio-creator-files {
|
||||
margin: 12px 0 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
|
||||
li {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 8px 0;
|
||||
border-bottom: 1px solid #f0f4f1;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
button {
|
||||
margin-left: auto;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: $ink-soft;
|
||||
cursor: pointer;
|
||||
}
|
||||
}
|
||||
|
||||
.jio-creator-files__name {
|
||||
display: inline-flex;
|
||||
min-width: 0;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
|
||||
i {
|
||||
color: $accent;
|
||||
}
|
||||
}
|
||||
|
||||
.jio-creator-reuse {
|
||||
margin-top: 14px;
|
||||
font-size: 13px;
|
||||
|
||||
summary {
|
||||
cursor: pointer;
|
||||
color: $ink-soft;
|
||||
}
|
||||
|
||||
ul {
|
||||
margin: 10px 0 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
li {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 6px 0;
|
||||
}
|
||||
|
||||
button {
|
||||
margin-left: auto;
|
||||
border: 1px solid $line;
|
||||
border-radius: 6px;
|
||||
background: #fff;
|
||||
cursor: pointer;
|
||||
}
|
||||
}
|
||||
|
||||
.jio-creator-link {
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: var(--jc-ink-soft, #{$ink-soft});
|
||||
font-size: 13px;
|
||||
text-decoration: underline;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
/* ---------- 手机 / 平板 ---------- */
|
||||
|
||||
@media (max-width: 767px) {
|
||||
.jio-creator {
|
||||
--jc-bar: 54px;
|
||||
}
|
||||
|
||||
.jio-creator__brand {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.jio-creator__bar {
|
||||
gap: 10px;
|
||||
padding: 0 12px;
|
||||
}
|
||||
|
||||
.jio-creator__save time {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.jio-creator__ghost {
|
||||
padding: 0 10px;
|
||||
}
|
||||
|
||||
.jio-creator__primary {
|
||||
padding: 0 14px;
|
||||
}
|
||||
|
||||
.jio-creator__canvas {
|
||||
padding: 20px 16px calc(120px + env(safe-area-inset-bottom));
|
||||
}
|
||||
|
||||
.jio-creator__title textarea {
|
||||
font-size: 24px;
|
||||
}
|
||||
|
||||
.jio-creator__editor .block-editor-writing-flow {
|
||||
font-size: 16px;
|
||||
line-height: 1.8;
|
||||
}
|
||||
|
||||
.jio-creator__inspector {
|
||||
margin-top: 16px;
|
||||
}
|
||||
|
||||
.jio-creator-drawer {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.jio-creator-drawer__backdrop {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.jio-creator-drawer__panel {
|
||||
width: 100%;
|
||||
height: 100dvh;
|
||||
border-radius: 0;
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
.jio-creator-drawer__foot {
|
||||
position: sticky;
|
||||
bottom: 0;
|
||||
background: #fff;
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.jio-creator * {
|
||||
transition: none !important;
|
||||
animation: none !important;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
/**
|
||||
* 付费配置 → 请求体。
|
||||
*
|
||||
* 受保护附件只提交 asset_key,不提交任何文件路径或公开 URL;服务端会再次
|
||||
* 校验附件归属并重新清洗。
|
||||
*
|
||||
* @package Jio
|
||||
*/
|
||||
|
||||
type PayState = {
|
||||
enabled: boolean;
|
||||
modo: 'cash' | 'points';
|
||||
price: string;
|
||||
points: number;
|
||||
vip1Price: string;
|
||||
vip2Price: string;
|
||||
payLimit: number;
|
||||
downloads: Array<Record<string, any>>;
|
||||
};
|
||||
|
||||
export function normalizePayForRequest(pay: PayState) {
|
||||
const downloads = (pay.downloads || [])
|
||||
.map((row) => {
|
||||
const assetKey = typeof row.assetKey === 'string' ? row.assetKey : '';
|
||||
if (assetKey) {
|
||||
return {
|
||||
type: 'protected',
|
||||
asset_key: assetKey,
|
||||
label: typeof row.label === 'string' ? row.label : '',
|
||||
};
|
||||
}
|
||||
const url = typeof row.url === 'string' ? row.url.trim() : '';
|
||||
if (!url) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
type: 'direct',
|
||||
url,
|
||||
label: typeof row.label === 'string' ? row.label : '',
|
||||
extract_code: typeof row.extractCode === 'string' ? row.extractCode : '',
|
||||
};
|
||||
})
|
||||
.filter(Boolean);
|
||||
|
||||
return {
|
||||
enabled: !!pay.enabled,
|
||||
fields: {
|
||||
pay_type: pay.enabled ? (downloads.length > 0 ? 'download' : 'reading') : 'no',
|
||||
pay_modo: pay.modo === 'points' ? 'points' : '0',
|
||||
price: pay.modo === 'points' ? '0.00' : String(pay.price || '0.00'),
|
||||
points_price: pay.modo === 'points' ? Math.max(0, Number(pay.points) || 0) : 0,
|
||||
vip1_price: pay.modo === 'points' ? '0.00' : String(pay.vip1Price || '0.00'),
|
||||
vip2_price: pay.modo === 'points' ? '0.00' : String(pay.vip2Price || '0.00'),
|
||||
pay_limit: Number(pay.payLimit) || 0,
|
||||
downloads,
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2020",
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "node",
|
||||
"jsx": "react-jsx",
|
||||
"strict": true,
|
||||
"strictNullChecks": false,
|
||||
"noImplicitAny": false,
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"esModuleInterop": true,
|
||||
"skipLibCheck": true,
|
||||
"resolveJsonModule": true,
|
||||
"types": ["react", "react-dom"]
|
||||
},
|
||||
"include": ["src/**/*.ts", "src/**/*.tsx"]
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
/**
|
||||
* 受保护下载按钮:先换取短期令牌,再用令牌地址下载。
|
||||
*
|
||||
* 按钮由下载区模板输出,只携带随机 asset_key,不携带文件路径或公开 URL。
|
||||
*
|
||||
* @package Jio
|
||||
*/
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
var i18n = (window.jioData && window.jioData.protectedDownload) || {};
|
||||
var tokenUrl = i18n.tokenUrl || '';
|
||||
|
||||
function toast(message, type) {
|
||||
if (typeof window.notyf === 'function') {
|
||||
window.notyf(message, type || 'danger');
|
||||
}
|
||||
}
|
||||
|
||||
function message(data) {
|
||||
if (data && typeof data.message === 'string' && data.message !== '') {
|
||||
return data.message;
|
||||
}
|
||||
return i18n.error || '下载失败,请稍后重试';
|
||||
}
|
||||
|
||||
function download(button) {
|
||||
var assetKey = button.getAttribute('data-jio-protected-asset') || '';
|
||||
var postId = button.getAttribute('data-jio-protected-post') || '';
|
||||
if (!assetKey || !postId || !tokenUrl) {
|
||||
return;
|
||||
}
|
||||
if (button.getAttribute('aria-busy') === 'true') {
|
||||
return;
|
||||
}
|
||||
button.setAttribute('aria-busy', 'true');
|
||||
|
||||
var body = new URLSearchParams();
|
||||
body.set('post_id', postId);
|
||||
body.set('asset_key', assetKey);
|
||||
|
||||
fetch(tokenUrl, {
|
||||
method: 'POST',
|
||||
credentials: 'same-origin',
|
||||
headers: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
|
||||
'X-WP-Nonce': (window.jioData && window.jioData.restNonce) || ''
|
||||
},
|
||||
body: body.toString()
|
||||
})
|
||||
.then(function (response) {
|
||||
return response.json().then(function (data) {
|
||||
return { ok: response.ok, data: data };
|
||||
});
|
||||
})
|
||||
.then(function (result) {
|
||||
if (!result.ok || !result.data || !result.data.url) {
|
||||
throw new Error(message(result.data));
|
||||
}
|
||||
window.location.href = result.data.url;
|
||||
})
|
||||
.catch(function (error) {
|
||||
toast(error && error.message ? error.message : (i18n.error || '下载失败,请稍后重试'));
|
||||
})
|
||||
.finally(function () {
|
||||
button.removeAttribute('aria-busy');
|
||||
});
|
||||
}
|
||||
|
||||
document.addEventListener('click', function (event) {
|
||||
var button = event.target.closest('[data-jio-protected-asset]');
|
||||
if (!button) {
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
download(button);
|
||||
});
|
||||
})();
|
||||
Vendored
+1
-1
@@ -1 +1 @@
|
||||
(function($,window2,document2){"use strict";function closeNotyf($element){$element.addClass("notyn-out"),window2.setTimeout(function(){$element.remove()},1e3)}function notyf2(message,type,time,id){var $body=jQuery(document2.body);jQuery(".notyn").length||$body.append('<div class="notyn"></div>'),type=type||"success",type==="error"&&(type="danger"),time=time||5e3,time=time<100?time*1e3:time;var idAttribute=id?' id="'+id+'"':"",$notification=jQuery('<div class="noty1"'+idAttribute+'><div class="notyf '+type+'">'+message+"</div></div>"),shouldClose=!id;id&&jQuery("#"+id).length?(jQuery("#"+id).find(".notyf").removeClass().addClass("notyf "+type).html(message),$notification=jQuery("#"+id),shouldClose=!0):jQuery(".notyn").append($notification),shouldClose&&window2.setTimeout(function(){closeNotyf($notification)},time)}jQuery(document2.body).on("click",".noty1",function(){closeNotyf(jQuery(this))}),window2.notyf=notyf2})(jQuery,window,document),(function(window2){"use strict";var allowedKinds={identity:!0,badges:!0,orders:!0,vip:!0},allowedEvents={click:!0,shell:!0,"first-content":!0,ready:!0,"action-start":!0,"action-end":!0,unauthorized:!0,error:!0},sessions=Object.create(null),sequence=0,maxSessions=100;function normalize(value,fallback){var normalized=String(value||fallback||"").toLowerCase().replace(/[^a-z0-9-]/g,"");return normalized||fallback}function now(){return window2.performance&&typeof window2.performance.now=="function"?window2.performance.now():0}function markName(session,event){return"jio-modal-"+session.kind+"-"+session.id+"-"+event}function emit(session,event){if(!(!window2.performance||typeof window2.performance.mark!="function")){var name=markName(session,event);if(window2.performance.mark(name),session.marks[event]=name,typeof window2.performance.measure=="function"&&session.marks.click&&event!=="click")try{window2.performance.measure("jio-modal-"+session.kind+"-"+session.id+"-click-to-"+event,session.marks.click,name)}catch{}}}function start(kind){var safeKind=normalize(kind,"unknown");allowedKinds[safeKind]||(safeKind="unknown"),sequence+=1;var id=String(sequence),session={id,kind:safeKind,startedAt:now(),marks:Object.create(null)};sessions[id]=session,emit(session,"click");for(var ids=Object.keys(sessions);ids.length>maxSessions;)delete sessions[ids.shift()];return id}function mark(id,event){var session=sessions[String(id||"")],safeEvent=normalize(event,"error");!session||!allowedEvents[safeEvent]||emit(session,safeEvent)}function finish(id){mark(id,"ready")}function fail(id){mark(id,"error")}window2.JioModalTelemetry={start,mark,finish,error:fail}})(window),(function(window2){"use strict";function data(){return window2.jioData||window2.jio||{}}function createIdempotencyKey(){if(window2.crypto&&typeof window2.crypto.randomUUID=="function")return window2.crypto.randomUUID();if(!window2.crypto||typeof window2.crypto.getRandomValues!="function")throw new Error("当前浏览器无法生成安全的操作标识");var bytes=new Uint8Array(16);window2.crypto.getRandomValues(bytes),bytes[6]=bytes[6]&15|64,bytes[8]=bytes[8]&63|128;var hex=Array.prototype.map.call(bytes,function(value){return value.toString(16).padStart(2,"0")}).join("");return hex.slice(0,8)+"-"+hex.slice(8,12)+"-"+hex.slice(12,16)+"-"+hex.slice(16,20)+"-"+hex.slice(20)}function restBase(){var config=data(),raw=config.restUrl||config.apiUrl||config.rest_url||"",siteUrl=config.siteUrl||config.homeUrl||window2.location.origin+"/";return window2.location.protocol==="https:"&&siteUrl.substring(0,5)==="http:"&&(siteUrl="https:"+siteUrl.substring(5)),raw?String(raw).replace(/\/$/,""):String(siteUrl).replace(/\/$/,"")+"/index.php?rest_route=/jio/v1"}function appendQuery(url2,query){if(!query)return url2;var parts=[];return typeof query=="string"?parts=query.replace(/^\?/,"").split("&").filter(Boolean):typeof query=="object"&&Object.keys(query).forEach(function(key){query[key]===void 0||query[key]===null||parts.push(encodeURIComponent(key)+"="+encodeURIComponent(String(query[key])))}),parts.length?url2+(url2.indexOf("?")>=0?"&":"?")+parts.join("&"):url2}function url(path,query){path=String(path||"");var inlineQuery="",queryIndex=path.indexOf("?");if(queryIndex>=0&&(inlineQuery=path.slice(queryIndex+1),path=path.slice(0,queryIndex)),/^https?:\/\//i.test(path))return appendQuery(path,query||inlineQuery);path.charAt(0)!=="/"&&(path="/"+path);var base=restBase(),result=(base.indexOf("rest_route=")>=0,base+path);return appendQuery(result,query||inlineQuery)}function headers(options){var config=data(),source=options&&options.headers||{},result={},nonce=config.restNonce||config.nonce||"";return Object.keys(source).forEach(function(key){result[key]=source[key]}),result.Accept||(result.Accept="application/json, text/html;q=0.9, */*;q=0.8"),nonce&&!result["X-WP-Nonce"]&&(result["X-WP-Nonce"]=nonce),options&&options.body!==void 0&&options.body!==null&&!(window2.FormData&&options.body instanceof window2.FormData)&&!result["Content-Type"]&&(result["CoLine truncated
|
||||
(function($,window2,document2){"use strict";function closeNotyf($element){$element.addClass("notyn-out"),window2.setTimeout(function(){$element.remove()},1e3)}function notyf2(message,type,time,id){var $body=jQuery(document2.body);jQuery(".notyn").length||$body.append('<div class="notyn"></div>'),type=type||"success",type==="error"&&(type="danger"),time=time||5e3,time=time<100?time*1e3:time;var idAttribute=id?' id="'+id+'"':"",$notification=jQuery('<div class="noty1"'+idAttribute+'><div class="notyf '+type+'">'+message+"</div></div>"),shouldClose=!id;id&&jQuery("#"+id).length?(jQuery("#"+id).find(".notyf").removeClass().addClass("notyf "+type).html(message),$notification=jQuery("#"+id),shouldClose=!0):jQuery(".notyn").append($notification),shouldClose&&window2.setTimeout(function(){closeNotyf($notification)},time)}jQuery(document2.body).on("click",".noty1",function(){closeNotyf(jQuery(this))}),window2.notyf=notyf2})(jQuery,window,document),(function(window2){"use strict";var allowedKinds={identity:!0,badges:!0,orders:!0,vip:!0},allowedEvents={click:!0,shell:!0,"first-content":!0,ready:!0,"action-start":!0,"action-end":!0,unauthorized:!0,error:!0},sessions=Object.create(null),sequence=0,maxSessions=100;function normalize(value,fallback){var normalized=String(value||fallback||"").toLowerCase().replace(/[^a-z0-9-]/g,"");return normalized||fallback}function now(){return window2.performance&&typeof window2.performance.now=="function"?window2.performance.now():0}function markName(session,event){return"jio-modal-"+session.kind+"-"+session.id+"-"+event}function emit(session,event){if(!(!window2.performance||typeof window2.performance.mark!="function")){var name=markName(session,event);if(window2.performance.mark(name),session.marks[event]=name,typeof window2.performance.measure=="function"&&session.marks.click&&event!=="click")try{window2.performance.measure("jio-modal-"+session.kind+"-"+session.id+"-click-to-"+event,session.marks.click,name)}catch{}}}function start(kind){var safeKind=normalize(kind,"unknown");allowedKinds[safeKind]||(safeKind="unknown"),sequence+=1;var id=String(sequence),session={id,kind:safeKind,startedAt:now(),marks:Object.create(null)};sessions[id]=session,emit(session,"click");for(var ids=Object.keys(sessions);ids.length>maxSessions;)delete sessions[ids.shift()];return id}function mark(id,event){var session=sessions[String(id||"")],safeEvent=normalize(event,"error");!session||!allowedEvents[safeEvent]||emit(session,safeEvent)}function finish(id){mark(id,"ready")}function fail(id){mark(id,"error")}window2.JioModalTelemetry={start,mark,finish,error:fail}})(window),(function(window2){"use strict";function data(){return window2.jioData||window2.jio||{}}function createIdempotencyKey(){if(window2.crypto&&typeof window2.crypto.randomUUID=="function")return window2.crypto.randomUUID();if(!window2.crypto||typeof window2.crypto.getRandomValues!="function")throw new Error("当前浏览器无法生成安全的操作标识");var bytes=new Uint8Array(16);window2.crypto.getRandomValues(bytes),bytes[6]=bytes[6]&15|64,bytes[8]=bytes[8]&63|128;var hex=Array.prototype.map.call(bytes,function(value){return value.toString(16).padStart(2,"0")}).join("");return hex.slice(0,8)+"-"+hex.slice(8,12)+"-"+hex.slice(12,16)+"-"+hex.slice(16,20)+"-"+hex.slice(20)}function restBase(){var config=data(),raw=config.restUrl||config.apiUrl||config.rest_url||"",siteUrl=config.siteUrl||config.homeUrl||window2.location.origin+"/";return window2.location.protocol==="https:"&&siteUrl.substring(0,5)==="http:"&&(siteUrl="https:"+siteUrl.substring(5)),raw?String(raw).replace(/\/$/,""):String(siteUrl).replace(/\/$/,"")+"/index.php?rest_route=/jio/v1"}function appendQuery(url2,query){if(!query)return url2;var parts=[];return typeof query=="string"?parts=query.replace(/^\?/,"").split("&").filter(Boolean):typeof query=="object"&&Object.keys(query).forEach(function(key){query[key]===void 0||query[key]===null||parts.push(encodeURIComponent(key)+"="+encodeURIComponent(String(query[key])))}),parts.length?url2+(url2.indexOf("?")>=0?"&":"?")+parts.join("&"):url2}function url(path,query){path=String(path||"");var inlineQuery="",queryIndex=path.indexOf("?");if(queryIndex>=0&&(inlineQuery=path.slice(queryIndex+1),path=path.slice(0,queryIndex)),/^https?:\/\//i.test(path))return appendQuery(path,query||inlineQuery);path.charAt(0)!=="/"&&(path="/"+path);var base=restBase(),result=(base.indexOf("rest_route=")>=0,base+path);return appendQuery(result,query||inlineQuery)}function headers(options){var config=data(),source=options&&options.headers||{},result={},nonce=config.restNonce||config.nonce||"";return Object.keys(source).forEach(function(key){result[key]=source[key]}),result.Accept||(result.Accept="application/json, text/html;q=0.9, */*;q=0.8"),nonce&&!result["X-WP-Nonce"]&&(result["X-WP-Nonce"]=nonce),options&&options.body!==void 0&&options.body!==null&&!(window2.FormData&&options.body instanceof window2.FormData)&&!result["Content-Type"]&&(result["CoLine truncated
|
||||
Reference in new issue
Block a user