@andares/pdeditor 0.4.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +359 -79
- package/dist/core.d.ts +68 -13
- package/dist/element-auto.cjs +46 -0
- package/dist/element-auto.d.ts +1 -0
- package/dist/element-auto.js +868 -0
- package/dist/element.cjs +46 -0
- package/dist/element.d.ts +43 -0
- package/dist/element.js +867 -0
- package/dist/highlighters.d.ts +1 -1
- package/dist/index.cjs +16 -16
- package/dist/index.d.ts +9 -2
- package/dist/index.js +864 -774
- package/dist/inline.d.ts +4 -23
- package/dist/pd-highlight.d.ts +1 -1
- package/dist/pd.cjs +14 -14
- package/dist/pd.d.ts +2 -2
- package/dist/pd.js +436 -352
- package/dist/plugins.d.ts +14 -2
- package/dist/react.cjs +46 -0
- package/dist/react.d.ts +30 -0
- package/dist/react.js +937 -0
- package/package.json +52 -12
- package/dist/index.cjs.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/pd.cjs.map +0 -1
- package/dist/pd.js.map +0 -1
package/dist/plugins.d.ts
CHANGED
|
@@ -1,8 +1,20 @@
|
|
|
1
|
-
|
|
1
|
+
/**
|
|
2
|
+
* pd 语义编辑插件(keydown 时返回新的 props)。
|
|
3
|
+
* 与主包 VSCode 扩展的编辑行为对齐:续行补 `- `、序列项行 Tab 整行缩进/Shift+Tab 缩出。
|
|
4
|
+
*
|
|
5
|
+
* 插件管线是 reduce(依次执行、后者覆盖前者)——同一按键只应由一个插件处理,
|
|
6
|
+
* enter 全部由 pdListItem 处理(含非序列行缩进保留),不要再叠加新的 preserveIndent。
|
|
7
|
+
*/
|
|
8
|
+
export interface PluginProps {
|
|
9
|
+
value: string;
|
|
10
|
+
selectionStart: number;
|
|
11
|
+
selectionEnd: number;
|
|
12
|
+
}
|
|
13
|
+
export type Plugin = (props: PluginProps, event: Event) => Partial<PluginProps> | void;
|
|
2
14
|
/**
|
|
3
15
|
* 回车续行:
|
|
4
16
|
* - 序列项行(`- ` 或 `-`,允许缩进)→ 新行 = 缩进 + `- `(自动续列表)
|
|
5
|
-
* - 其他行 →
|
|
17
|
+
* - 其他行 → 新行保留行首缩进(原 preserveIndent 行为,合并于此避免插件管线双重处理)
|
|
6
18
|
* `-x` / `---`(`-` 后无空白)不是列表项,只保留缩进。
|
|
7
19
|
*/
|
|
8
20
|
export declare function pdListItem(): Plugin;
|
package/dist/react.cjs
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"use strict";var ze=Object.defineProperty;var Ie=(r,i,s)=>i in r?ze(r,i,{enumerable:!0,configurable:!0,writable:!0,value:s}):r[i]=s;var w=(r,i,s)=>Ie(r,typeof i!="symbol"?i+"":i,s);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const R=require("react"),O=require("@andares/pdfoundation");function He(r,i,{signal:s,edges:t}={}){let a,e=null;const l=t!=null&&t.includes("leading"),c=t==null||t.includes("trailing"),d=()=>{e!==null&&(r.apply(a,e),a=void 0,e=null)},L=()=>{c&&d(),$()};let m=null;const S=()=>{m!=null&&clearTimeout(m),m=setTimeout(()=>{m=null,L()},i)},E=()=>{m!==null&&(clearTimeout(m),m=null)},$=()=>{E(),a=void 0,e=null},x=()=>{d()},k=function(...f){if(s!=null&&s.aborted)return;a=this,e=f;const g=m==null;S(),l&&g&&d()};return k.schedule=S,k.cancel=$,k.flush=x,s==null||s.addEventListener("abort",$,{once:!0}),k}function oe(r,i){const s=r,t=s.key.toLowerCase(),a=i.split("+"),e=a.slice(0,-1),l=a[a.length-1];return!(t!==l||e.includes("shift")!==s.shiftKey||e.includes("ctrl")!==s.ctrlKey||e.includes("alt")!==s.altKey||e.includes("meta")!==s.metaKey)}function ke(r,i){var a;const t=r.slice(0,i).split(`
|
|
2
|
+
`);return{line:t.length-1,col:((a=t[t.length-1])==null?void 0:a.length)??0}}function Y(r,i,s){var a;let t=0;for(let e=0;e<i;e++)t+=(((a=r[e])==null?void 0:a.length)??0)+1;return t+s}function _e(){return(r,i)=>{var L;if(i.type!=="keydown"||!oe(i,"enter"))return;const{value:s,selectionStart:t,selectionEnd:a}=r,e=s.slice(0,t).split(`
|
|
3
|
+
`).pop()??"",l=((L=/^\s*/.exec(e))==null?void 0:L[0])??"";i.preventDefault();const c=/^(\s*)-(?=[ ]|$)/.test(e),d=`
|
|
4
|
+
${l}${c?"- ":""}`;return{value:s.slice(0,t)+d+s.slice(a),selectionStart:t+d.length,selectionEnd:t+d.length}}}function Ke(r){return/^(\s*)-(?=[ ]|$)/.test(r)}function Se(r,i){return r.startsWith(i)?i.length:r.startsWith(" ")?1:0}function Le(r){return(i,s)=>{if(s.type!=="keydown")return;const{value:t,selectionStart:a,selectionEnd:e}=i,l=t.split(`
|
|
5
|
+
`),c=t.slice(0,a).split(`
|
|
6
|
+
`).length-1,d=t.slice(0,e).split(`
|
|
7
|
+
`).length-1,L=ke(t,a),m=ke(t,e);if(oe(s,"shift+tab")){s.preventDefault();const S=l.map((f,g)=>g>=c&&g<=d?f.slice(Se(f,r)):f),E=S.join(`
|
|
8
|
+
`);if(E===t)return;const $=f=>{const g=Se(l[f.line]??"",r);return{line:f.line,col:Math.max(0,f.col-g)}},x=$(L),k=$(m);return{value:E,selectionStart:Y(S,x.line,x.col),selectionEnd:Y(S,k.line,k.col)}}if(oe(s,"tab")){s.preventDefault();const S=l.map((x,k)=>({l:x,i:k})).filter(({i:x})=>x>=c&&x<=d);if(S.length>0&&S.every(({l:x})=>Ke(x))||a!==e){const x=l.map((_,b)=>b>=c&&b<=d&&_!==""?r+_:_),k=x.join(`
|
|
9
|
+
`),f=_=>{const b=l[_.line]??"",M=_.line>=c&&_.line<=d;return{line:_.line,col:M&&b!==""?_.col+r.length:_.col}},g=f(L),o=f(m);return{value:k,selectionStart:Y(x,g.line,g.col),selectionEnd:Y(x,o.line,o.col)}}const $=a+r.length;return{value:t.slice(0,a)+r+t.slice(e),selectionStart:$,selectionEnd:$}}}}function Be(r){return r.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function j(r){return r.replace(/\r\n?/g,`
|
|
10
|
+
`)}function je(r,i){const s=document.createRange();s.selectNodeContents(r),r.replaceChildren(s.createContextualFragment(i))}function qe(r,i){const s=Math.min(r.length,i.length);let t=0;for(;t<s&&r.charCodeAt(t)===i.charCodeAt(t);)t++;return t}const Ue=new Set(["padding","paddingTop","paddingRight","paddingBottom","paddingLeft"]);function Ee(r){var t;const i={top:"0px",right:"0px",bottom:"0px",left:"0px"},s=(t=r.padding)==null?void 0:t.trim();if(s){const a=s.split(/\s+/);if(a.length===1){const e=a[0]??"0px";i.top=i.right=i.bottom=i.left=e}else a.length===2?(i.top=i.bottom=a[0]??"0px",i.right=i.left=a[1]??"0px"):a.length===3?(i.top=a[0]??"0px",i.right=i.left=a[1]??"0px",i.bottom=a[2]??"0px"):(i.top=a[0]??"0px",i.right=a[1]??"0px",i.bottom=a[2]??"0px",i.left=a[3]??"0px")}return r.paddingTop&&(i.top=r.paddingTop),r.paddingRight&&(i.right=r.paddingRight),r.paddingBottom&&(i.bottom=r.paddingBottom),r.paddingLeft&&(i.left=r.paddingLeft),i}function We(r){return r.startsWith("--")?r:r.replace(/[A-Z]/g,i=>`-${i.toLowerCase()}`)}const $e="position:relative;display:block;box-sizing:border-box;width:100%;height:auto;max-height:inherit;overflow:hidden;text-align:start;margin:0;border:0;font-family:var(--pd-font-family,inherit);font-size:var(--pd-font-size,inherit);line-height:var(--pd-line-height,1.5);letter-spacing:var(--pd-letter-spacing,inherit);color:var(--pd-color,inherit);background:var(--pd-background,transparent);tab-size:4;font-variant-ligatures:none;font-kerning:normal;",Ce="position:absolute;left:0;top:0;width:100%;height:100%;box-sizing:border-box;margin:0;border:0;outline:none;resize:none;background:transparent;-webkit-text-fill-color:transparent;caret-color:var(--pd-caret-color,currentColor);overflow:auto;scrollbar-gutter:stable;white-space:pre-wrap;overflow-wrap:break-word;word-break:normal;font:inherit;line-height:inherit;letter-spacing:inherit;tab-size:inherit;z-index:2;",Ae="position:relative;left:auto;top:auto;width:100%;height:auto;box-sizing:border-box;margin:0;border:0;overflow:hidden;scrollbar-gutter:stable;pointer-events:none;user-select:none;white-space:pre-wrap;overflow-wrap:break-word;word-break:normal;font:inherit;line-height:inherit;letter-spacing:inherit;tab-size:inherit;color:inherit;z-index:1;",Ge="position:absolute;left:0;top:0;width:100%;height:100%;box-sizing:border-box;margin:0;border:0;overflow:hidden;scrollbar-gutter:stable;pointer-events:none;user-select:none;white-space:pre-wrap;overflow-wrap:break-word;word-break:normal;font:inherit;line-height:inherit;letter-spacing:inherit;tab-size:inherit;color:inherit;z-index:0;",we="position:absolute;left:0;top:0;width:100%;height:100%;box-sizing:border-box;margin:0;border:0;overflow:hidden;scrollbar-gutter:stable;pointer-events:none;user-select:none;white-space:pre-wrap;overflow-wrap:break-word;word-break:normal;font:inherit;line-height:inherit;letter-spacing:inherit;tab-size:inherit;color:inherit;opacity:var(--pd-placeholder-opacity,0.5);z-index:1;";function Z(r,i,s,t,a={}){const e=document.createElement(r);e.className=i,e.setAttribute("part",s),e.style.cssText=t;for(const[l,c]of Object.entries(a))e.setAttribute(l,c);return e}function Je(r,i,s){let t={...i},a=t.language??"pd",e=j(t.value??""),l=e,c=!1,d=!1,L=!1,m=t.lineNumbers??!1,S=ee(),E="",$=!1,x=0,k=null;const f=Z("div","pd-root","root",$e),g=Z("pre","pd-highlight","highlight",Ae,{"aria-hidden":"true"}),o=Z("textarea","pd-input","input",Ce),_=Z("div","pd-placeholder","placeholder",we,{"aria-hidden":"true"});let b=null;o.spellcheck=t.spellcheck??!1,o.setAttribute("autocapitalize","off"),o.setAttribute("autocorrect","off"),o.setAttribute("autocomplete","off"),o.setAttribute("wrap","soft"),o.value=e,o.readOnly=t.readOnly??!1,o.disabled=t.disabled??!1,(n=>{n!==void 0&&n>=0?o.maxLength=n:o.removeAttribute("maxlength")})(t.maxLength),t.dir&&(o.dir=t.dir),J(),f.appendChild(g),f.appendChild(_),f.appendChild(o),r.appendChild(f),G(),te(),V(),I();function p(){c||(g.scrollTop=o.scrollTop,g.scrollLeft=o.scrollLeft,b&&(b.scrollTop=o.scrollTop,b.scrollLeft=o.scrollLeft))}function N(){if(typeof getComputedStyle!="function")return 0;const n=getComputedStyle(r),u=Number.parseFloat(n.paddingTop)||0,h=Number.parseFloat(n.paddingBottom)||0;return Math.max(0,r.clientHeight-u-h)}function z(){$?(g.style.position="absolute",g.style.left="0",g.style.top="0",g.style.height="100%"):(g.style.position="relative",g.style.left="auto",g.style.top="auto",g.style.height="auto")}function I(){if(c)return;const n=N(),u=g.scrollHeight;if(!$){n>0&&u>n+1&&($=!0,z(),f.style.height=`${n}px`,p());return}if(n<=0||u<=n+1){$=!1,z(),f.style.height="",o.scrollTop=0;return}const h=Number.parseFloat(f.style.height)||0;Math.abs(h-n)>.5&&(f.style.height=`${n}px`),p()}function P(){if(!x){if(typeof requestAnimationFrame!="function"){I();return}x=requestAnimationFrame(()=>{x=0,I()})}}typeof ResizeObserver<"u"&&(k=new ResizeObserver(()=>P()),k.observe(r),k.observe(f));const H=()=>p(),W=(n,u,h)=>{var v;e=n,l=n,Q({value:n,selStart:u,selEnd:h}),(v=t.onValueChange)==null||v.call(t,n)},le=n=>{if(c)return;const u=j(o.value);if(d||n!=null&&n.isComposing){e=u,V();return}u!==e&&(e=u,V()),u!==l&&W(u,o.selectionStart,o.selectionEnd)},se=()=>{d=!0},ae=()=>{d=!1;const n=j(o.value);n!==e&&(e=n,V())},Me=Math.max(0,t.historyLimit??5),ce=Math.max(0,t.historyDebounce??1e3),A=[{value:e,selStart:-1,selEnd:-1}],K=[],ue=()=>{A.length>Me+1&&A.splice(1,1)},de=n=>{const u=A[0];if(u!==void 0&&u.selStart<0&&u.value!==n.value){const v=qe(u.value,n.value);u.selStart=v,u.selEnd=v}const h=A.at(-1);h!==void 0&&h.value===n.value||(K.length=0,A.push(n),ue())},q=He(de,ce),Q=n=>{ce===0?de(n):q(n)},he=n=>{var v;const u=n.selStart>=0?n.selStart:Math.min(n.value.length,o.selectionStart),h=n.selEnd>=0?n.selEnd:u;e=n.value,l=n.value,o.value=n.value,o.setSelectionRange(Math.max(0,Math.min(u,n.value.length)),Math.max(0,Math.min(h,n.value.length))),V(),p(),(v=t.onValueChange)==null||v.call(t,n.value)},pe=()=>{if(q.flush(),A.length<=1)return!1;const n=A.pop();n!==void 0&&K.push(n);const u=A.at(-1);return u!==void 0&&he(u),!0},fe=()=>{if(q.flush(),K.length===0)return!1;const n=K.pop();return n===void 0?!1:(A.push(n),ue(),he(n),!0)},ge=n=>{var T;if(c||n.isComposing||d||o.readOnly||o.disabled)return;const u=n.ctrlKey||n.metaKey,h=n.key.toLowerCase();if(u&&(h==="z"||h==="y")){n.preventDefault(),h==="y"||h==="z"&&n.shiftKey?fe():pe();return}if(h==="escape"){(t.tabBehavior??"indent")==="indent"&&(L=!0);return}if(h==="tab"&&(t.tabBehavior??"indent")==="focus")return;if(h==="tab"&&L){L=!1;return}const v={value:e,selectionStart:o.selectionStart,selectionEnd:o.selectionEnd};let y=v;for(const D of ie){const B=D(y,n);B&&(y={...y,...B})}(y.value!==v.value||y.selectionStart!==v.selectionStart||y.selectionEnd!==v.selectionEnd)&&(n.preventDefault(),e=y.value,o.value=y.value,o.setSelectionRange(y.selectionStart,y.selectionEnd),l=y.value,V(),Q({value:y.value,selStart:y.selectionStart,selEnd:y.selectionEnd}),(T=t.onValueChange)==null||T.call(t,y.value),p())},be=()=>f.classList.add("pd-focused"),me=()=>f.classList.remove("pd-focused");o.addEventListener("input",le),o.addEventListener("compositionstart",se),o.addEventListener("compositionend",ae),o.addEventListener("scroll",H,{passive:!0}),o.addEventListener("keydown",ge),o.addEventListener("focus",be),o.addEventListener("blur",me);function ee(){return t.highlight?n=>{var u;return((u=t.highlight)==null?void 0:u.call(t,n,a))??""}:s(a)}function V(){if(c)return;const n=t.highlightThreshold??1e5,u=e.length>n?Be(e):S(e);je(g,`${u}<br/>`),m&&ve(),te(),k||P()}function ve(){if(!m)return;b||(b=document.createElement("pre"),b.className="pd-lines",b.setAttribute("part","gutter"),b.setAttribute("aria-hidden","true"),f.insertBefore(b,_));const n=e.split(`
|
|
11
|
+
`),h=`${String(n.length).length+1}ch`,v=Ee(t.styles??{}),y=`position:absolute;inset-inline-start:${v.left};width:${h};text-align:end;opacity:var(--pd-gutter-opacity,0.35);color:var(--pd-gutter-color,inherit)`,T=document.createDocumentFragment();n.forEach((D,B)=>{const X=document.createElement("span");X.className="pd-ln",X.style.cssText=y,X.textContent=String(B+1);const re=document.createElement("span");re.style.color="transparent",re.textContent=D,T.append(X,re),B<n.length-1&&T.append(document.createTextNode(`
|
|
12
|
+
`))}),T.append(document.createElement("br")),b.replaceChildren(T),h!==E&&(E=h,G(),b.style.cssText=xe(v))}function te(){const n=t.placeholder??"";_.textContent=n,_.style.display=n&&e.length===0?"block":"none",n?o.setAttribute("aria-placeholder",n):o.removeAttribute("aria-placeholder")}function ye(n){const u=E?`calc(${n.left} + ${E})`:n.left;return`padding:${n.top} ${n.right} ${n.bottom} ${u};`}function ne(n,u){return u+ye(n)}function xe(n){return Ge+ye(n)}function G(){const n=t.styles??{},u=Ee(n),h=Object.entries(n).filter(([v])=>!Ue.has(v)).map(([v,y])=>`${We(v)}:${y};`).join("");f.style.cssText=$e+h,g.style.cssText=ne(u,Ae),o.style.cssText=ne(u,Ce),_.style.cssText=ne(u,we),b&&(b.style.cssText=xe(u)),z(),t.dir&&(f.dir=t.dir,o.dir=t.dir,g.dir=t.dir,_.dir=t.dir,b&&(b.dir=t.dir))}function J(){t.ariaLabel?o.setAttribute("aria-label",t.ariaLabel):o.removeAttribute("aria-label"),t.ariaLabelledby?o.setAttribute("aria-labelledby",t.ariaLabelledby):o.removeAttribute("aria-labelledby"),t.ariaDescribedby?o.setAttribute("aria-describedby",t.ariaDescribedby):o.removeAttribute("aria-describedby"),t.readOnly?o.setAttribute("aria-readonly","true"):o.removeAttribute("aria-readonly"),t.disabled?o.setAttribute("aria-disabled","true"):o.removeAttribute("aria-disabled")}m&&ve();const ie=[_e(),Le(t.indentUnit??" ")];return{setValue(n,u){if(c||d)return;let h=j(n);t.maxLength!==void 0&&t.maxLength>=0&&(h=h.slice(0,t.maxLength)),q.cancel(),e=h,l=h,o.value=h,o.setSelectionRange(h.length,h.length),((u==null?void 0:u.resetHistory)??!0)&&(A.length=0,A.push({value:h,selStart:-1,selEnd:-1}),K.length=0),V(),p()},getValue(){return e},setLanguage(n){a=n,t={...t,language:n},S=ee(),V()},setPlaceholder(n){t={...t,placeholder:n},te()},setReadOnly(n){t={...t,readOnly:n},o.readOnly=n,J()},setDisabled(n){t={...t,disabled:n},o.disabled=n,J()},setLineNumbers(n){m!==n&&(m=n,!n&&b&&(b.remove(),b=null,E=""),G(),V())},update(n){c||(t={...t,...n},n.indentUnit!==void 0&&ie.splice(0,ie.length,_e(),Le(n.indentUnit)),n.language!==void 0&&(a=n.language),("highlight"in n||n.language!==void 0)&&(S=ee()),n.lineNumbers!==void 0&&(m=n.lineNumbers,!m&&b&&(b.remove(),b=null,E="")),n.value!==void 0&&(e=j(n.value),l=e,o.value=e,A.length=0,A.push({value:e,selStart:-1,selEnd:-1}),K.length=0),n.readOnly!==void 0&&(o.readOnly=n.readOnly),n.disabled!==void 0&&(o.disabled=n.disabled),n.maxLength!==void 0&&(n.maxLength>=0?o.maxLength=n.maxLength:o.removeAttribute("maxlength")),n.spellcheck!==void 0&&(o.spellcheck=n.spellcheck),n.dir!==void 0&&(o.dir=n.dir),J(),G(),V(),p())},focus(){o.focus()},blur(){o.blur()},undo(){pe()},redo(){fe()},insertText(n){var D;if(c||o.readOnly||o.disabled)return;const u=o.selectionStart,h=o.selectionEnd;let v=j(n);if(t.maxLength!==void 0&&t.maxLength>=0){const B=t.maxLength-(e.length-(h-u));if(B<=0)return;v.length>B&&(v=v.slice(0,B))}const y=e.slice(0,u)+v+e.slice(h);e=y,l=y,o.value=y;const T=u+v.length;o.setSelectionRange(T,T),V(),Q({value:y,selStart:T,selEnd:T}),(D=t.onValueChange)==null||D.call(t,y),p()},getSelection(){return{start:o.selectionStart,end:o.selectionEnd}},setSelection(n,u=n){const h=v=>Math.max(0,Math.min(e.length,Number.isFinite(v)?v:0));o.setSelectionRange(h(n),h(u))},destroy(){c||(c=!0,q.cancel(),k==null||k.disconnect(),x&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(x),o.removeEventListener("input",le),o.removeEventListener("compositionstart",se),o.removeEventListener("compositionend",ae),o.removeEventListener("scroll",H),o.removeEventListener("keydown",ge),o.removeEventListener("focus",be),o.removeEventListener("blur",me),f.remove())},textarea:o,root:f,pre:g}}function C(r){return r.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}const F={key:"pd-key",keyPunct:"pd-key-punct",item:"pd-item",section:"pd-section",sep:"pd-sep",ref:"pd-ref",inlineCode:"pd-inline-code",fence:"pd-fence"};function Xe(r){return`<span class="${F.inlineCode}">${C(r)}</span>`}const Te=/(?:^|\s):([^\s-][^\s]*)(?=\s|$)/g;function Ye(r){let i="",s=0;Te.lastIndex=0;let t;for(;(t=Te.exec(r))!==null;){const a=/^\s/.test(t[0])?1:0,e=t.index+a;i+=C(r.slice(s,e)),i+=`<span class="${F.ref}">${C(r.slice(e,t.index+t[0].length))}</span>`,s=t.index+t[0].length}return i+=C(r.slice(s)),i}function U(r){let i="";for(const{code:s,seg:t}of O.splitInlineCode(r))i+=s?Xe(t):Ye(t);return i}function Ve(r,i,s,t){const a=`<span class="${F.key}">${U(s)}</span>`,e=`<span class="${F.keyPunct}">:</span>`;return`${r}${i}${a}${e}${U(t)}`}function Ze(r){const i=r.trim();if(/^\/\/!pd(?:\s+[^\s]+)?$/.test(i)){const t=/^(\s*)(\/\/!pd)(\s*.*)$/.exec(r),a=(t==null?void 0:t[1])??"",e=(t==null?void 0:t[2])??"//!pd",l=(t==null?void 0:t[3])??"";return`${C(a)}<span class="${F.section}">${C(e)}</span>${U(l)}`}if(i==="---")return`<span class="${F.sep}">${C(r)}</span>`;const s=/^(\s*)(-)(?=[ ]|$)/.exec(r);if(s){const t=C(s[1]??""),a=(s[1]??"").length+1,e=r.slice(a),l=e.trimStart(),c=e.slice(0,e.length-l.length),d=`<span class="${F.item}">-</span>`;if(!O.hasLiteralColon(l)&&O.matchKeyValue(l)){const m=O.findKeyValueSeparator(l),S=l.slice(0,m),E=l.slice(m+1);return`${t}${d}${C(c)}${Ve("","",S,E)}`}return`${t}${d}${C(c)}${U(l)}`}if(!O.hasLiteralColon(i)&&O.matchKeyValue(i)){const a=r.length-r.trimStart().length,e=r.slice(a),l=O.findKeyValueSeparator(e),c=e.slice(0,l).trim(),d=e.slice(l+1);return Ve(C(r.slice(0,a)),"",c,d)}return U(r)}function Fe(r){const i=r.split(`
|
|
13
|
+
`);let s=!1;const t=[];for(const a of i){const e=a.trimStart();if(s){e.startsWith("```")?(s=!1,t.push(`<span class="${F.fence}">${C(a)}</span>`)):t.push(C(a));continue}if(e.startsWith("```")){s=!0,t.push(`<span class="${F.fence}">${C(a)}</span>`);continue}t.push(Ze(a))}return t.join(`
|
|
14
|
+
`)}function Qe(r){return i=>r==="pd"?Fe(i):Be(i)}function Ne(r){const i=r;return`
|
|
15
|
+
${i}.pd-key{color:var(--pd-token-key,color-mix(in oklab,currentColor 66%,transparent))}
|
|
16
|
+
${i}.pd-key-punct{color:var(--pd-token-punct,color-mix(in oklab,currentColor 45%,transparent))}
|
|
17
|
+
${i}.pd-item{color:var(--pd-token-item,color-mix(in oklab,currentColor 78%,transparent))}
|
|
18
|
+
${i}.pd-section{color:var(--pd-token-section,color-mix(in oklab,currentColor 62%,transparent))}
|
|
19
|
+
${i}.pd-sep{color:var(--pd-token-sep,color-mix(in oklab,currentColor 45%,transparent))}
|
|
20
|
+
${i}.pd-ref{color:var(--pd-token-ref,color-mix(in oklab,currentColor 74%,transparent))}
|
|
21
|
+
${i}.pd-inline-code{color:var(--pd-token-code,color-mix(in oklab,currentColor 84%,transparent))}
|
|
22
|
+
${i}.pd-fence{color:var(--pd-token-fence,color-mix(in oklab,currentColor 55%,transparent))}
|
|
23
|
+
${i}.token.comment,${i}.token.prolog,${i}.token.doctype,${i}.token.cdata{color:var(--pd-token-comment,color-mix(in oklab,currentColor 52%,transparent))}
|
|
24
|
+
${i}.token.string,${i}.token.attr-value{color:var(--pd-token-string,color-mix(in oklab,currentColor 78%,transparent))}
|
|
25
|
+
${i}.token.keyword,${i}.token.tag,${i}.token.operator{color:var(--pd-token-keyword,color-mix(in oklab,currentColor 64%,transparent))}
|
|
26
|
+
${i}.token.number,${i}.token.boolean{color:var(--pd-token-number,color-mix(in oklab,currentColor 72%,transparent))}
|
|
27
|
+
${i}.token.property,${i}.token.function{color:var(--pd-token-property,color-mix(in oklab,currentColor 68%,transparent))}
|
|
28
|
+
${i}.token.punctuation{color:var(--pd-token-punctuation,color-mix(in oklab,currentColor 50%,transparent))}
|
|
29
|
+
`}function Pe(r){const i=r;return`
|
|
30
|
+
@supports not (color: color-mix(in oklab, red, blue)){
|
|
31
|
+
${i}.pd-key{opacity:.72}${i}.pd-key-punct{opacity:.5}${i}.pd-item{opacity:.8}
|
|
32
|
+
${i}.pd-section{opacity:.65}${i}.pd-sep{opacity:.5}${i}.pd-ref{opacity:.78}
|
|
33
|
+
${i}.pd-inline-code{opacity:.88}${i}.pd-fence{opacity:.6}
|
|
34
|
+
}`}const Re=`
|
|
35
|
+
:host{display:block;min-width:0;max-width:100%;height:auto;max-height:inherit;font:inherit;color:inherit;background:transparent}
|
|
36
|
+
:host([disabled]){opacity:var(--pd-disabled-opacity,.6)}
|
|
37
|
+
:host(:focus-within){outline:var(--pd-focus-ring,2px solid color-mix(in oklab,currentColor 32%,transparent));outline-offset:var(--pd-focus-ring-offset,2px);border-radius:var(--pd-focus-radius,2px)}
|
|
38
|
+
${Ne("")}
|
|
39
|
+
${Pe("")}
|
|
40
|
+
`;function et(){const r="pd-editor ";return`
|
|
41
|
+
pd-editor{display:block;min-width:0;max-width:100%;height:auto;max-height:inherit;font:inherit;color:inherit;background:transparent}
|
|
42
|
+
pd-editor[disabled]{opacity:var(--pd-disabled-opacity,.6)}
|
|
43
|
+
pd-editor:focus-within{outline:var(--pd-focus-ring,2px solid color-mix(in oklab,currentColor 32%,transparent));outline-offset:var(--pd-focus-ring-offset,2px);border-radius:var(--pd-focus-radius,2px)}
|
|
44
|
+
${Ne(r)}
|
|
45
|
+
${Pe(r)}
|
|
46
|
+
`}const Oe=new WeakSet;function tt(r){if(Oe.has(r))return;Oe.add(r);const i=r.createElement("style");i.setAttribute("data-pd-editor",""),i.textContent=et(),(r.head??r.documentElement).appendChild(i)}function nt(r){if(r.querySelector("style[data-pd-editor]"))return;try{if(typeof CSSStyleSheet<"u"&&"replaceSync"in CSSStyleSheet.prototype){const s=new CSSStyleSheet;s.replaceSync(Re),r.adoptedStyleSheets=[...r.adoptedStyleSheets,s];return}}catch{}const i=document.createElement("style");i.setAttribute("data-pd-editor",""),i.textContent=Re,r.appendChild(i)}const it=["value","language","placeholder","indent-unit","line-numbers","tab-behavior","readonly","disabled","maxlength","name","spellcheck","inputmode","enterkeyhint","dir","aria-label","aria-labelledby","aria-describedby","shadow"];function De(r="pd-editor"){if(typeof HTMLElement>"u"||typeof customElements>"u")return null;const i=customElements.get(r);if(i)return i;class s extends HTMLElement{constructor(){super();w(this,"_editor",null);w(this,"_internals",null);w(this,"_container",null);w(this,"_shadow",null);w(this,"_value","");w(this,"_defaultValue",null);w(this,"_highlight",null);w(this,"_formDisabled",!1);w(this,"_focusValue","");w(this,"_onFocus",()=>{this._focusValue=this._value,this._emit("pd-focus",{value:this._value})});w(this,"_onBlur",()=>{this._value!==this._focusValue&&this._emit("pd-change",{value:this._value}),this._emit("pd-blur",{value:this._value})});try{this._internals=typeof this.attachInternals=="function"?this.attachInternals():null}catch{this._internals=null}}static get observedAttributes(){return it}get value(){return this._editor?this._editor.getValue():this._value}set value(e){var c;const l=e==null?"":String(e);this._value=l,(c=this._editor)==null||c.setValue(l),this._syncFormValue()}get language(){return this.getAttribute("language")??"pd"}set language(e){this.setAttribute("language",String(e))}get placeholder(){return this.getAttribute("placeholder")??""}set placeholder(e){this.setAttribute("placeholder",String(e))}get readOnly(){return this.hasAttribute("readonly")}set readOnly(e){this.toggleAttribute("readonly",!!e)}get disabled(){return this.hasAttribute("disabled")}set disabled(e){this.toggleAttribute("disabled",!!e)}get lineNumbers(){return this.hasAttribute("line-numbers")}set lineNumbers(e){this.toggleAttribute("line-numbers",!!e)}get indentUnit(){return this.getAttribute("indent-unit")??" "}set indentUnit(e){this.setAttribute("indent-unit",String(e))}get tabBehavior(){return this.getAttribute("tab-behavior")==="focus"?"focus":"indent"}set tabBehavior(e){this.setAttribute("tab-behavior",e==="focus"?"focus":"indent")}get maxLength(){const e=this.getAttribute("maxlength");if(e===null||e==="")return-1;const l=Number.parseInt(e,10);return Number.isFinite(l)?l:-1}set maxLength(e){!Number.isFinite(e)||e<0?this.removeAttribute("maxlength"):this.setAttribute("maxlength",String(Math.floor(e)))}get name(){return this.getAttribute("name")??""}set name(e){this.setAttribute("name",String(e))}get highlight(){return this._highlight}set highlight(e){this._highlight=typeof e=="function"?e:null,this._syncOptions()}get editor(){return this._editor}get textarea(){var e;return((e=this._editor)==null?void 0:e.textarea)??null}connectedCallback(){this._upgradeProperties();const e=this.getAttribute("value");if(e!==null&&this._value===""&&(this._value=e),this._defaultValue===null&&(this._defaultValue=this._value),this._editor)return;const l=this.getAttribute("shadow")==="false";l?tt(this.ownerDocument):(this._shadow??(this._shadow=this.attachShadow({mode:"open",delegatesFocus:!0})),nt(this._shadow));const c=l?this:this._shadow,d=document.createElement("div");d.className="pd-container",d.setAttribute("part","container"),d.style.cssText="display:block;height:100%;max-height:inherit;min-width:0",c.appendChild(d),this._container=d;const L={value:this._value,language:this.language,placeholder:this.placeholder,readOnly:this.readOnly,disabled:this.disabled||this._formDisabled,lineNumbers:this.lineNumbers,indentUnit:this.indentUnit,tabBehavior:this.tabBehavior,maxLength:this.maxLength,spellcheck:this.getAttribute("spellcheck")==="true",dir:this.getAttribute("dir")??"",ariaLabel:this.getAttribute("aria-label")??void 0,ariaLabelledby:this.getAttribute("aria-labelledby")??void 0,ariaDescribedby:this.getAttribute("aria-describedby")??void 0,highlight:this._highlight??void 0,onValueChange:m=>this._handleValueChange(m)};this._editor=Je(d,L,Qe),this._editor.textarea.addEventListener("focus",this._onFocus),this._editor.textarea.addEventListener("blur",this._onBlur),this._focusValue=this._value,this._applyInputHints(),this._syncFormValue(),queueMicrotask(()=>{this._editor&&this._emit("pd-ready",{editor:this._editor})})}disconnectedCallback(){var e,l,c,d;this._editor&&(this._value=this._editor.getValue()),(e=this._editor)==null||e.textarea.removeEventListener("focus",this._onFocus),(l=this._editor)==null||l.textarea.removeEventListener("blur",this._onBlur),(c=this._editor)==null||c.destroy(),this._editor=null,(d=this._container)==null||d.remove(),this._container=null}attributeChangedCallback(e,l,c){var d;if(l!==c){if(e==="value"){this._value=c??"",(d=this._editor)==null||d.setValue(this._value),this._syncFormValue();return}e!=="shadow"&&this._editor&&(this._syncOptions(),e==="language"&&this._emit("pd-language-change",{value:this.language}))}}formResetCallback(){this.value=this._defaultValue??""}formDisabledCallback(e){var l;this._formDisabled=e,(l=this._editor)==null||l.setDisabled(e||this.disabled)}formStateRestoreCallback(e){typeof e=="string"&&(this.value=e)}setValue(e){this.value=e}getValue(){return this.value}setLanguage(e){this.language=e}insertText(e){var l;(l=this._editor)==null||l.insertText(e)}getSelection(){var e;return((e=this._editor)==null?void 0:e.getSelection())??null}setSelection(e,l){var c;(c=this._editor)==null||c.setSelection(e,l)}undo(){var e;(e=this._editor)==null||e.undo()}redo(){var e;(e=this._editor)==null||e.redo()}focus(){var e;(e=this._editor)==null||e.focus()}blur(){var e;(e=this._editor)==null||e.blur()}_upgradeProperties(){const e=["value","language","placeholder","readOnly","disabled","lineNumbers","indentUnit","tabBehavior","maxLength","name","highlight"];for(const l of e)if(Object.prototype.hasOwnProperty.call(this,l)){const c=this,d=c[l];delete c[l],c[l]=d}}_syncOptions(){var e;(e=this._editor)==null||e.update({language:this.language,placeholder:this.placeholder,readOnly:this.readOnly,disabled:this.disabled||this._formDisabled,lineNumbers:this.lineNumbers,indentUnit:this.indentUnit,tabBehavior:this.tabBehavior,maxLength:this.maxLength,spellcheck:this.getAttribute("spellcheck")==="true",dir:this.getAttribute("dir")??"",ariaLabel:this.getAttribute("aria-label")??void 0,ariaLabelledby:this.getAttribute("aria-labelledby")??void 0,ariaDescribedby:this.getAttribute("aria-describedby")??void 0,highlight:this._highlight??void 0}),this._applyInputHints()}_applyInputHints(){var l;const e=(l=this._editor)==null?void 0:l.textarea;if(e)for(const c of["inputmode","enterkeyhint"]){const d=this.getAttribute(c);d?e.setAttribute(c,d):e.removeAttribute(c)}}_handleValueChange(e){this._value=e,this._syncFormValue(),this._emit("pd-input",{value:e})}_syncFormValue(){var e;typeof((e=this._internals)==null?void 0:e.setFormValue)=="function"&&this._internals.setFormValue(this._value)}_emit(e,l){this.dispatchEvent(new CustomEvent(e,{detail:l,bubbles:!0,composed:!0}))}}return w(s,"formAssociated",!0),customElements.define(r,s),s}const rt=typeof window>"u"?R.useEffect:R.useLayoutEffect,ot=R.forwardRef(function(i,s){const{value:t,defaultValue:a,language:e,placeholder:l,readOnly:c,disabled:d,lineNumbers:L,indentUnit:m,tabBehavior:S,maxLength:E,highlight:$,onValueChange:x,onReady:k,...f}=i,g=R.useRef(null),o=R.useRef(!0),_=R.useRef(x);_.current=x;const b=R.useRef(k);b.current=k;const M=R.useRef(!1);return R.useImperativeHandle(s,()=>g.current,[]),rt(()=>{De();const p=g.current;if(p){if(o.current){o.current=!1;const N=t??a;N!==void 0&&p.value!==N&&(p.value=N)}else t!==void 0&&p.value!==t&&(p.value=t);e!==void 0&&p.language!==e&&(p.language=e),l!==void 0&&p.placeholder!==l&&(p.placeholder=l),c!==void 0&&(p.readOnly=c),d!==void 0&&(p.disabled=d),L!==void 0&&(p.lineNumbers=L),m!==void 0&&p.indentUnit!==m&&(p.indentUnit=m),S!==void 0&&(p.tabBehavior=S),E!==void 0&&(p.maxLength=E),$!==void 0&&(p.highlight=$)}},[t,a,e,l,c,d,L,m,S,E,$]),R.useEffect(()=>{const p=g.current;if(!p)return;const N=P=>{var W;const H=P.detail;(W=_.current)==null||W.call(_,(H==null?void 0:H.value)??p.value)},z=()=>{var P;M.current||(M.current=!0,(P=b.current)==null||P.call(b,p))},I=()=>z();return p.addEventListener("pd-input",N),p.addEventListener("pd-ready",I),queueMicrotask(()=>{p.editor&&z()}),()=>{p.removeEventListener("pd-input",N),p.removeEventListener("pd-ready",I),M.current=!1}},[]),R.createElement("pd-editor",{...f,ref:g})});Object.defineProperty(exports,"format",{enumerable:!0,get:()=>O.format});Object.defineProperty(exports,"jsonToPdText",{enumerable:!0,get:()=>O.jsonToPdText});Object.defineProperty(exports,"pdToJsonText",{enumerable:!0,get:()=>O.pdToJsonText});exports.PdEditor=ot;exports.definePdEditor=De;exports.highlightPd=Fe;
|
package/dist/react.d.ts
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { type HTMLAttributes } from "react";
|
|
2
|
+
import { type PdEditorElement, type PdHighlighter } from "./element";
|
|
3
|
+
export type { PdEditorElement, PdHighlighter } from "./element";
|
|
4
|
+
export { definePdEditor } from "./element";
|
|
5
|
+
export { format, highlightPd, jsonToPdText, pdToJsonText, } from "./element";
|
|
6
|
+
export interface PdEditorProps extends Omit<HTMLAttributes<HTMLElement>, "value" | "defaultValue" | "onChange" | "onInput" | "children"> {
|
|
7
|
+
value?: string;
|
|
8
|
+
defaultValue?: string;
|
|
9
|
+
language?: string;
|
|
10
|
+
placeholder?: string;
|
|
11
|
+
readOnly?: boolean;
|
|
12
|
+
disabled?: boolean;
|
|
13
|
+
lineNumbers?: boolean;
|
|
14
|
+
indentUnit?: string;
|
|
15
|
+
tabBehavior?: "indent" | "focus";
|
|
16
|
+
maxLength?: number;
|
|
17
|
+
/** BYO 高亮器(例如主入口导出的 prismHighlighter);不传则 pd-only */
|
|
18
|
+
highlight?: PdHighlighter | null;
|
|
19
|
+
onValueChange?: (value: string) => void;
|
|
20
|
+
onReady?: (element: PdEditorElement) => void;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* React 包装(React 17+)。自定义元素的复杂属性(函数/对象)在 React 18 会被
|
|
24
|
+
* 字符串化,因此这里统一用 DOM property 赋值,而不是走 attribute。
|
|
25
|
+
*
|
|
26
|
+
* - 受控:传 `value` + `onValueChange`;`el.value` 与 prop 相同则不会回写(不打断光标/撤销)
|
|
27
|
+
* - 非受控:传 `defaultValue`(只作初始值)
|
|
28
|
+
* - SSR:import 安全;元素在 layout effect 中注册,SSR 端渲染为空标签
|
|
29
|
+
*/
|
|
30
|
+
export declare const PdEditor: import("react").ForwardRefExoticComponent<PdEditorProps & import("react").RefAttributes<PdEditorElement>>;
|