From 275ea747724131848bd904324243901749f5cc87 Mon Sep 17 00:00:00 2001 From: Peng Xiao Date: Wed, 10 Jan 2024 05:25:37 +0000 Subject: [PATCH] chore(core): remove affine/cmdk package (#5552) patch cmdk based on https://github.com/pengx17/cmdk/tree/patch-1 fix https://github.com/toeverything/AFFiNE/issues/5548 --- .yarn/patches/cmdk-npm-0.2.0-302237a911.patch | 202 +++ package.json | 3 +- packages/common/cmdk/LICENSE.md | 21 - packages/common/cmdk/README.md | 3 - packages/common/cmdk/package.json | 15 - packages/common/cmdk/src/command-score.ts | 179 --- packages/common/cmdk/src/index.tsx | 1151 ----------------- packages/common/cmdk/tsconfig.json | 9 - packages/frontend/core/package.json | 2 +- .../core/src/components/pure/cmdk/data.tsx | 2 +- .../core/src/components/pure/cmdk/main.tsx | 14 +- .../src/components/pure/cmdk/not-found.tsx | 2 +- tsconfig.json | 3 - yarn.lock | 47 +- 14 files changed, 243 insertions(+), 1410 deletions(-) create mode 100644 .yarn/patches/cmdk-npm-0.2.0-302237a911.patch delete mode 100644 packages/common/cmdk/LICENSE.md delete mode 100644 packages/common/cmdk/README.md delete mode 100644 packages/common/cmdk/package.json delete mode 100644 packages/common/cmdk/src/command-score.ts delete mode 100644 packages/common/cmdk/src/index.tsx delete mode 100644 packages/common/cmdk/tsconfig.json diff --git a/.yarn/patches/cmdk-npm-0.2.0-302237a911.patch b/.yarn/patches/cmdk-npm-0.2.0-302237a911.patch new file mode 100644 index 000000000..538dea1a1 --- /dev/null +++ b/.yarn/patches/cmdk-npm-0.2.0-302237a911.patch @@ -0,0 +1,202 @@ +diff --git a/dist/command-score.d.ts b/dist/command-score.d.ts +new file mode 100644 +index 0000000000000000000000000000000000000000..949ceeb1266241f7bf294b6df4422fd904e163c1 +--- /dev/null ++++ b/dist/command-score.d.ts +@@ -0,0 +1,3 @@ ++declare function commandScore(string: string, abbreviation: string): number; ++ ++export { commandScore }; +diff --git a/dist/command-score.js b/dist/command-score.js +new file mode 100644 +index 0000000000000000000000000000000000000000..0d88276d3d39315e68322c54aceb3cf9769ad732 +--- /dev/null ++++ b/dist/command-score.js +@@ -0,0 +1 @@ ++var p=Object.defineProperty;var a=Object.getOwnPropertyDescriptor;var H=Object.getOwnPropertyNames;var J=Object.prototype.hasOwnProperty;var k=(_,E)=>{for(var f in E)p(_,f,{get:E[f],enumerable:!0})},m=(_,E,f,C)=>{if(E&&typeof E=="object"||typeof E=="function")for(let c of H(E))!J.call(_,c)&&c!==f&&p(_,c,{get:()=>E[c],enumerable:!(C=a(E,c))||C.enumerable});return _};var B=_=>m(p({},"__esModule",{value:!0}),_);var Z={};k(Z,{commandScore:()=>V});module.exports=B(Z);var D=1,K=.9,W=.8,$=.17,u=.1,G=.999,y=.9999;var F=.99,j=/[\\\/_+.#"@\[\(\{&]/,q=/[\\\/_+.#"@\[\(\{&]/g,Q=/[\s-]/,Y=/[\s-]/g;function L(_,E,f,C,c,P,O){if(P===E.length)return c===_.length?D:F;var T=`${c},${P}`;if(O[T]!==void 0)return O[T];for(var U=C.charAt(P),A=f.indexOf(U,c),S=0,h,N,R,M;A>=0;)h=L(_,E,f,C,A+1,P+1,O),h>S&&(A===c?h*=D:j.test(_.charAt(A-1))?(h*=W,R=_.slice(c,A-1).match(q),R&&c>0&&(h*=Math.pow(G,R.length))):Q.test(_.charAt(A-1))?(h*=K,M=_.slice(c,A-1).match(Y),M&&c>0&&(h*=Math.pow(G,M.length))):(h*=$,c>0&&(h*=Math.pow(G,A-c))),_.charAt(A)!==E.charAt(P)&&(h*=y)),(hh&&(h=N*u)),h>S&&(S=h),A=f.indexOf(U,A+1);return O[T]=S,S}function X(_){return _.toLowerCase().replace(Y," ")}function V(_,E){return L(_,E,X(_),X(E),0,0,{})}0&&(module.exports={commandScore}); +diff --git a/dist/command-score.mjs b/dist/command-score.mjs +new file mode 100644 +index 0000000000000000000000000000000000000000..bb680ba9ce704741e08454e4884bcbb1697c7f2b +--- /dev/null ++++ b/dist/command-score.mjs +@@ -0,0 +1 @@ ++var U=1,Y=.9,a=.8,H=.17,p=.1,u=.999,J=.9999;var k=.99,m=/[\\\/_+.#"@\[\(\{&]/,B=/[\\\/_+.#"@\[\(\{&]/g,K=/[\s-]/,X=/[\s-]/g;function G(c,f,P,C,h,A,O){if(A===f.length)return h===c.length?U:k;var T=`${h},${A}`;if(O[T]!==void 0)return O[T];for(var L=C.charAt(A),E=P.indexOf(L,h),S=0,_,N,R,M;E>=0;)_=G(c,f,P,C,E+1,A+1,O),_>S&&(E===h?_*=U:m.test(c.charAt(E-1))?(_*=a,R=c.slice(h,E-1).match(B),R&&h>0&&(_*=Math.pow(u,R.length))):K.test(c.charAt(E-1))?(_*=Y,M=c.slice(h,E-1).match(X),M&&h>0&&(_*=Math.pow(u,M.length))):(_*=H,h>0&&(_*=Math.pow(u,E-h))),c.charAt(E)!==f.charAt(A)&&(_*=J)),(__&&(_=N*p)),_>S&&(S=_),E=P.indexOf(L,E+1);return O[T]=S,S}function D(c){return c.toLowerCase().replace(X," ")}function W(c,f){return G(c,f,D(c),D(f),0,0,{})}export{W as commandScore}; +diff --git a/dist/index.d.ts b/dist/index.d.ts +index faf9d6c5ad2de8af1abf49c9d70903bd1e911408..53eed433f6571e6a4ee34395a24d8cedefca3a33 100644 +--- a/dist/index.d.ts ++++ b/dist/index.d.ts +@@ -1,5 +1,6 @@ + import * as RadixDialog from '@radix-ui/react-dialog'; + import * as React from 'react'; ++export { commandScore } from './command-score.js'; + + declare type Children = { + children?: React.ReactNode; +@@ -30,6 +31,10 @@ declare const Command: React.ForwardRefExoticComponent number; ++ /** ++ * Optional default item value when it is initially rendered. ++ */ ++ defaultValue?: string; + /** + * Optional controlled state of the selected command menu item. + */ +@@ -42,6 +47,10 @@ declare const Command: React.ForwardRefExoticComponent>; + /** + * Command menu item. Becomes active on pointer enter or through keyboard navigation. +@@ -58,7 +67,13 @@ declare const Item: React.ForwardRefExoticComponent>; ++declare type Group = { ++ id: string; ++ forceMount?: boolean; ++}; + /** + * Group command menu items together with a heading. + * Grouped items are always shown together. +@@ -68,6 +83,8 @@ declare const Group: React.ForwardRefExoticComponent>; + /** + * A visual and semantic separator between items or groups. +@@ -115,6 +132,10 @@ declare const Dialog: React.ForwardRefExoticComponent number; ++ /** ++ * Optional default item value when it is initially rendered. ++ */ ++ defaultValue?: string; + /** + * Optional controlled state of the selected command menu item. + */ +@@ -127,7 +148,15 @@ declare const Dialog: React.ForwardRefExoticComponent>; +@@ -138,7 +167,7 @@ declare const Empty: React.ForwardRefExoticComponent>; +@@ -158,6 +187,10 @@ declare const pkg: React.ForwardRefExoticComponent number; ++ /** ++ * Optional default item value when it is initially rendered. ++ */ ++ defaultValue?: string; + /** + * Optional controlled state of the selected command menu item. + */ +@@ -170,6 +203,10 @@ declare const pkg: React.ForwardRefExoticComponent> & { + List: React.ForwardRefExoticComponent>; + Item: React.ForwardRefExoticComponent & { +@@ -182,6 +219,8 @@ declare const pkg: React.ForwardRefExoticComponent>; + Input: React.ForwardRefExoticComponent, "value" | "onChange" | "type"> & { + /** +@@ -198,6 +237,8 @@ declare const pkg: React.ForwardRefExoticComponent>; + Separator: React.ForwardRefExoticComponent number; ++ /** ++ * Optional default item value when it is initially rendered. ++ */ ++ defaultValue?: string; + /** + * Optional controlled state of the selected command menu item. + */ +@@ -231,12 +276,20 @@ declare const pkg: React.ForwardRefExoticComponent>; + Empty: React.ForwardRefExoticComponent>; +- Loading: React.ForwardRefExoticComponent>; +diff --git a/dist/index.js b/dist/index.js +index 64801d481bdc4872c6ace390225105ab21508c0c..038dbe22b7c0eecb6babe424d1425131fac4d242 100644 +--- a/dist/index.js ++++ b/dist/index.js +@@ -1 +1 @@ +-var Se=Object.create;var F=Object.defineProperty;var Ce=Object.getOwnPropertyDescriptor;var ye=Object.getOwnPropertyNames;var xe=Object.getPrototypeOf,Te=Object.prototype.hasOwnProperty;var Le=(r,o)=>{for(var n in o)F(r,n,{get:o[n],enumerable:!0})},re=(r,o,n,a)=>{if(o&&typeof o=="object"||typeof o=="function")for(let l of ye(o))!Te.call(r,l)&&l!==n&&F(r,l,{get:()=>o[l],enumerable:!(a=Ce(o,l))||a.enumerable});return r};var z=(r,o,n)=>(n=r!=null?Se(xe(r)):{},re(o||!r||!r.__esModule?F(n,"default",{value:r,enumerable:!0}):n,r)),we=r=>re(F({},"__esModule",{value:!0}),r);var _e={};Le(_e,{Command:()=>Me,CommandDialog:()=>pe,CommandEmpty:()=>ge,CommandGroup:()=>ue,CommandInput:()=>fe,CommandItem:()=>le,CommandList:()=>me,CommandLoading:()=>ve,CommandRoot:()=>J,CommandSeparator:()=>de,useCommandState:()=>y});module.exports=we(_e);var C=z(require("@radix-ui/react-dialog")),t=z(require("react")),oe=z(require("command-score")),De='[cmdk-list-sizer=""]',M='[cmdk-group=""]',U='[cmdk-group-items=""]',Ie='[cmdk-group-heading=""]',ae='[cmdk-item=""]',ne=`${ae}:not([aria-disabled="true"])`,B="cmdk-item-select",S="data-value",Pe=(r,o)=>(0,oe.default)(r,o),se=t.createContext(void 0),k=()=>t.useContext(se),ie=t.createContext(void 0),W=()=>t.useContext(ie),ce=t.createContext(void 0),J=t.forwardRef((r,o)=>{let n=t.useRef(null),a=T(()=>({search:"",value:"",filtered:{count:0,items:new Map,groups:new Set}})),l=T(()=>new Set),u=T(()=>new Map),p=T(()=>new Map),f=T(()=>new Set),d=Re(r),{label:v,children:E,value:R,onValueChange:w,filter:O,shouldFilter:he,...D}=r,K=t.useId(),g=t.useId(),A=t.useId(),x=Oe();L(()=>{if(R!==void 0){let e=R.trim().toLowerCase();a.current.value=e,x(6,X),h.emit()}},[R]);let h=t.useMemo(()=>({subscribe:e=>(f.current.add(e),()=>f.current.delete(e)),snapshot:()=>a.current,setState:(e,c,i)=>{var s,m,b;if(!Object.is(a.current[e],c)){if(a.current[e]=c,e==="search")q(),V(),x(1,j);else if(e==="value")if(((s=d.current)==null?void 0:s.value)!==void 0){(b=(m=d.current).onValueChange)==null||b.call(m,c);return}else i||x(5,X);h.emit()}},emit:()=>{f.current.forEach(e=>e())}}),[]),G=t.useMemo(()=>({value:(e,c)=>{c!==p.current.get(e)&&(p.current.set(e,c),a.current.filtered.items.set(e,Q(c)),x(2,()=>{V(),h.emit()}))},item:(e,c)=>(l.current.add(e),c&&(u.current.has(c)?u.current.get(c).add(e):u.current.set(c,new Set([e]))),x(3,()=>{q(),V(),a.current.value||j(),h.emit()}),()=>{p.current.delete(e),l.current.delete(e),a.current.filtered.items.delete(e),x(4,()=>{q(),j(),h.emit()})}),group:e=>(u.current.has(e)||u.current.set(e,new Set),()=>{p.current.delete(e),u.current.delete(e)}),filter:()=>d.current.shouldFilter,label:v||r["aria-label"],listId:K,inputId:A,labelId:g}),[]);function Q(e){var i;let c=((i=d.current)==null?void 0:i.filter)??Pe;return e?c(e,a.current.search):0}function V(){if(!n.current||!a.current.search||d.current.shouldFilter===!1)return;let e=a.current.filtered.items,c=[];a.current.filtered.groups.forEach(s=>{let m=u.current.get(s),b=0;m.forEach(P=>{let Ee=e.get(P);b=Math.max(Ee,b)}),c.push([s,b])});let i=n.current.querySelector(De);I().sort((s,m)=>{let b=s.getAttribute(S),P=m.getAttribute(S);return(e.get(P)??0)-(e.get(b)??0)}).forEach(s=>{let m=s.closest(U);m?m.appendChild(s.parentElement===m?s:s.closest(`${U} > *`)):i.appendChild(s.parentElement===i?s:s.closest(`${U} > *`))}),c.sort((s,m)=>m[1]-s[1]).forEach(s=>{let m=n.current.querySelector(`${M}[${S}="${s[0]}"]`);m==null||m.parentElement.appendChild(m)})}function j(){let e=I().find(i=>!i.ariaDisabled),c=e==null?void 0:e.getAttribute(S);h.setState("value",c||void 0)}function q(){if(!a.current.search||d.current.shouldFilter===!1){a.current.filtered.count=l.current.size;return}a.current.filtered.groups=new Set;let e=0;for(let c of l.current){let i=p.current.get(c),s=Q(i);a.current.filtered.items.set(c,s),s>0&&e++}for(let[c,i]of u.current)for(let s of i)if(a.current.filtered.items.get(s)>0){a.current.filtered.groups.add(c);break}a.current.filtered.count=e}function X(){var c,i,s;let e=_();e&&(((c=e.parentElement)==null?void 0:c.firstChild)===e&&((s=(i=e.closest(M))==null?void 0:i.querySelector(Ie))==null||s.scrollIntoView({block:"nearest"})),e.scrollIntoView({block:"nearest"}))}function _(){return n.current.querySelector(`${ae}[aria-selected="true"]`)}function I(){return Array.from(n.current.querySelectorAll(ne))}function $(e){let i=I()[e];i&&h.setState("value",i.getAttribute(S))}function N(e){var b;let c=_(),i=I(),s=i.findIndex(P=>P===c),m=i[s+e];(b=d.current)!=null&&b.loop&&(m=s+e<0?i[i.length-1]:s+e===i.length?i[0]:i[s+e]),m&&h.setState("value",m.getAttribute(S))}function Y(e){let c=_(),i=c==null?void 0:c.closest(M),s;for(;i&&!s;)i=e>0?ke(i,M):He(i,M),s=i==null?void 0:i.querySelector(ne);s?h.setState("value",s.getAttribute(S)):N(e)}let Z=()=>$(I().length-1),ee=e=>{e.preventDefault(),e.metaKey?Z():e.altKey?Y(1):N(1)},te=e=>{e.preventDefault(),e.metaKey?$(0):e.altKey?Y(-1):N(-1)};return t.createElement("div",{ref:H([n,o]),...D,"cmdk-root":"",onKeyDown:e=>{var c;if((c=D.onKeyDown)==null||c.call(D,e),!e.defaultPrevented)switch(e.key){case"n":case"j":{e.ctrlKey&&ee(e);break}case"ArrowDown":{ee(e);break}case"p":case"k":{e.ctrlKey&&te(e);break}case"ArrowUp":{te(e);break}case"Home":{e.preventDefault(),$(0);break}case"End":{e.preventDefault(),Z();break}case"Enter":{e.preventDefault();let i=_();if(i){let s=new Event(B);i.dispatchEvent(s)}}}}},t.createElement("label",{"cmdk-label":"",htmlFor:G.inputId,id:G.labelId,style:Ae},v),t.createElement(ie.Provider,{value:h},t.createElement(se.Provider,{value:G},E)))}),le=t.forwardRef((r,o)=>{let n=t.useId(),a=t.useRef(null),l=t.useContext(ce),u=k(),p=Re(r);L(()=>u.item(n,l),[]);let f=be(n,a,[r.value,r.children,a]),d=W(),v=y(g=>g.value&&g.value===f.current),E=y(g=>u.filter()===!1?!0:g.search?g.filtered.items.get(n)>0:!0);t.useEffect(()=>{let g=a.current;if(!(!g||r.disabled))return g.addEventListener(B,R),()=>g.removeEventListener(B,R)},[E,r.onSelect,r.disabled]);function R(){var g,A;(A=(g=p.current).onSelect)==null||A.call(g,f.current)}function w(){d.setState("value",f.current,!0)}if(!E)return null;let{disabled:O,value:he,onSelect:D,...K}=r;return t.createElement("div",{ref:H([a,o]),...K,"cmdk-item":"",role:"option","aria-disabled":O||void 0,"aria-selected":v||void 0,"data-selected":v||void 0,onPointerMove:O?void 0:w,onClick:O?void 0:R},r.children)}),ue=t.forwardRef((r,o)=>{let{heading:n,children:a,...l}=r,u=t.useId(),p=t.useRef(null),f=t.useRef(null),d=t.useId(),v=k(),E=y(w=>v.filter()===!1?!0:w.search?w.filtered.groups.has(u):!0);L(()=>v.group(u),[]),be(u,p,[r.value,r.heading,f]);let R=t.createElement(ce.Provider,{value:u},a);return t.createElement("div",{ref:H([p,o]),...l,"cmdk-group":"",role:"presentation",hidden:E?void 0:!0},n&&t.createElement("div",{ref:f,"cmdk-group-heading":"","aria-hidden":!0,id:d},n),t.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":n?d:void 0},R))}),de=t.forwardRef((r,o)=>{let{alwaysRender:n,...a}=r,l=t.useRef(null),u=y(p=>!p.search);return!n&&!u?null:t.createElement("div",{ref:H([l,o]),...a,"cmdk-separator":"",role:"separator"})}),fe=t.forwardRef((r,o)=>{let{onValueChange:n,...a}=r,l=r.value!=null,u=W(),p=y(d=>d.search),f=k();return t.useEffect(()=>{r.value!=null&&u.setState("search",r.value)},[r.value]),t.createElement("input",{ref:o,...a,"cmdk-input":"",autoComplete:"off",autoCorrect:"off",spellCheck:!1,"aria-autocomplete":"list",role:"combobox","aria-expanded":!0,"aria-controls":f.listId,"aria-labelledby":f.labelId,id:f.inputId,type:"text",value:l?r.value:p,onChange:d=>{l||u.setState("search",d.target.value),n==null||n(d.target.value)}})}),me=t.forwardRef((r,o)=>{let{children:n,...a}=r,l=t.useRef(null),u=t.useRef(null),p=k();return t.useEffect(()=>{if(u.current&&l.current){let f=u.current,d=l.current,v,E=new ResizeObserver(()=>{v=requestAnimationFrame(()=>{let R=f.getBoundingClientRect().height;d.style.setProperty("--cmdk-list-height",R.toFixed(1)+"px")})});return E.observe(f),()=>{cancelAnimationFrame(v),E.unobserve(f)}}},[]),t.createElement("div",{ref:H([l,o]),...a,"cmdk-list":"",role:"listbox","aria-label":"Suggestions",id:p.listId,"aria-labelledby":p.inputId},t.createElement("div",{ref:u,"cmdk-list-sizer":""},n))}),pe=t.forwardRef((r,o)=>{let{open:n,onOpenChange:a,container:l,...u}=r;return t.createElement(C.Root,{open:n,onOpenChange:a},t.createElement(C.Portal,{container:l},t.createElement(C.Overlay,{"cmdk-overlay":""}),t.createElement(C.Content,{"aria-label":r.label,"cmdk-dialog":""},t.createElement(J,{ref:o,...u}))))}),ge=t.forwardRef((r,o)=>{let n=t.useRef(!0),a=y(l=>l.filtered.count===0);return t.useEffect(()=>{n.current=!1},[]),n.current||!a?null:t.createElement("div",{ref:o,...r,"cmdk-empty":"",role:"presentation"})}),ve=t.forwardRef((r,o)=>{let{progress:n,children:a,...l}=r;return t.createElement("div",{ref:o,...l,"cmdk-loading":"",role:"progressbar","aria-valuenow":n,"aria-valuemin":0,"aria-valuemax":100,"aria-label":"Loading..."},t.createElement("div",{"aria-hidden":!0},a))}),Me=Object.assign(J,{List:me,Item:le,Input:fe,Group:ue,Separator:de,Dialog:pe,Empty:ge,Loading:ve});function ke(r,o){let n=r.nextElementSibling;for(;n;){if(n.matches(o))return n;n=n.nextElementSibling}}function He(r,o){let n=r.previousElementSibling;for(;n;){if(n.matches(o))return n;n=n.previousElementSibling}}function Re(r){let o=t.useRef(r);return L(()=>{o.current=r}),o}var L=typeof window>"u"?t.useEffect:t.useLayoutEffect;function T(r){let o=t.useRef();return o.current===void 0&&(o.current=r()),o}function H(r){return o=>{r.forEach(n=>{typeof n=="function"?n(o):n!=null&&(n.current=o)})}}function y(r){let o=W(),n=()=>r(o.snapshot());return t.useSyncExternalStore(o.subscribe,n,n)}function be(r,o,n){let a=t.useRef(),l=k();return L(()=>{var p;let u=(()=>{var f;for(let d of n){if(typeof d=="string")return d.trim().toLowerCase();if(typeof d=="object"&&"current"in d&&d.current)return(f=d.current.textContent)==null?void 0:f.trim().toLowerCase()}})();l.value(r,u),(p=o.current)==null||p.setAttribute(S,u),a.current=u}),a}var Oe=()=>{let[r,o]=t.useState(),n=T(()=>new Map);return L(()=>{n.current.forEach(a=>a()),n.current=new Map},[r]),(a,l)=>{n.current.set(a,l),o({})}},Ae={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};0&&(module.exports={Command,CommandDialog,CommandEmpty,CommandGroup,CommandInput,CommandItem,CommandList,CommandLoading,CommandRoot,CommandSeparator,useCommandState}); ++var De=Object.create;var G=Object.defineProperty;var xe=Object.getOwnPropertyDescriptor;var Ae=Object.getOwnPropertyNames;var we=Object.getPrototypeOf,_e=Object.prototype.hasOwnProperty;var Oe=(t,o)=>{for(var n in o)G(t,n,{get:o[n],enumerable:!0})},ie=(t,o,n,a)=>{if(o&&typeof o=="object"||typeof o=="function")for(let c of Ae(o))!_e.call(t,c)&&c!==n&&G(t,c,{get:()=>o[c],enumerable:!(a=xe(o,c))||a.enumerable});return t};var le=(t,o,n)=>(n=t!=null?De(we(t)):{},ie(o||!t||!t.__esModule?G(n,"default",{value:t,enumerable:!0}):n,t)),ke=t=>ie(G({},"__esModule",{value:!0}),t);var ze={};Oe(ze,{Command:()=>Be,CommandDialog:()=>be,CommandEmpty:()=>Te,CommandGroup:()=>he,CommandInput:()=>Ce,CommandItem:()=>ge,CommandList:()=>Se,CommandLoading:()=>ye,CommandRoot:()=>te,CommandSeparator:()=>Ee,commandScore:()=>W,useCommandState:()=>P});module.exports=ke(ze);var M=le(require("@radix-ui/react-dialog")),r=le(require("react"));var ue=1,Ie=.9,He=.8,Ne=.17,X=.1,Y=.999,Ge=.9999;var Ke=.99,Ve=/[\\\/_+.#"@\[\(\{&]/,Fe=/[\\\/_+.#"@\[\(\{&]/g,$e=/[\s-]/,fe=/[\s-]/g;function J(t,o,n,a,c,i,f){if(i===o.length)return c===t.length?ue:Ke;var v=`${c},${i}`;if(f[v]!==void 0)return f[v];for(var d=a.charAt(i),p=n.indexOf(d,c),R=0,m,S,T,E;p>=0;)m=J(t,o,n,a,p+1,i+1,f),m>R&&(p===c?m*=ue:Ve.test(t.charAt(p-1))?(m*=He,T=t.slice(c,p-1).match(Fe),T&&c>0&&(m*=Math.pow(Y,T.length))):$e.test(t.charAt(p-1))?(m*=Ie,E=t.slice(c,p-1).match(fe),E&&c>0&&(m*=Math.pow(Y,E.length))):(m*=Ne,c>0&&(m*=Math.pow(Y,p-c))),t.charAt(p)!==o.charAt(i)&&(m*=Ge)),(mm&&(m=S*X)),m>R&&(R=m),p=n.indexOf(d,p+1);return f[v]=R,R}function de(t){return t.toLowerCase().replace(fe," ")}function W(t,o){return J(t,o,de(t),de(o),0,0,{})}var je='[cmdk-list-sizer=""]',k='[cmdk-group=""]',z='[cmdk-group-items=""]',Ue='[cmdk-group-heading=""]',Z='[cmdk-item=""]',me=`${Z}:not([aria-disabled="true"])`,Q="cmdk-item-select",D="data-value",qe=(t,o)=>W(t,o),pe=r.createContext(void 0),I=()=>r.useContext(pe),Re=r.createContext(void 0),ee=()=>r.useContext(Re),ve=r.createContext(void 0),te=r.forwardRef((t,o)=>{let n=r.useRef(null),a=x(()=>{var e;return{search:"",value:t.value??((e=t.defaultValue)==null?void 0:e.toLowerCase())??"",filtered:{count:0,items:new Map,groups:new Set}}}),c=x(()=>new Set),i=x(()=>new Map),f=x(()=>new Map),v=x(()=>new Set),d=Pe(t),{label:p,children:R,value:m,onValueChange:S,filter:T,shouldFilter:E,vimBindings:K=!0,...w}=t,V=r.useId(),N=r.useId(),h=r.useId(),y=Je();A(()=>{if(m!==void 0){let e=m.trim().toLowerCase();a.current.value=e,y(6,ne),b.emit()}},[m]);let b=r.useMemo(()=>({subscribe:e=>(v.current.add(e),()=>v.current.delete(e)),snapshot:()=>a.current,setState:(e,u,s)=>{var l,g,C;if(!Object.is(a.current[e],u)){if(a.current[e]=u,e==="search")U(),$(),y(1,j);else if(e==="value")if(((l=d.current)==null?void 0:l.value)!==void 0){let L=u??"";(C=(g=d.current).onValueChange)==null||C.call(g,L);return}else s||y(5,ne);b.emit()}},emit:()=>{v.current.forEach(e=>e())}}),[]),F=r.useMemo(()=>({value:(e,u)=>{u!==f.current.get(e)&&(f.current.set(e,u),a.current.filtered.items.set(e,re(u)),y(2,()=>{$(),b.emit()}))},item:(e,u)=>(c.current.add(e),u&&(i.current.has(u)?i.current.get(u).add(e):i.current.set(u,new Set([e]))),y(3,()=>{U(),$(),a.current.value||j(),b.emit()}),()=>{f.current.delete(e),c.current.delete(e),a.current.filtered.items.delete(e);let s=_();y(4,()=>{U(),(s==null?void 0:s.getAttribute("id"))===e&&j(),b.emit()})}),group:e=>(i.current.has(e)||i.current.set(e,new Set),()=>{f.current.delete(e),i.current.delete(e)}),filter:()=>d.current.shouldFilter,label:p||t["aria-label"],commandRef:n,listId:V,inputId:h,labelId:N}),[]);function re(e){var s;let u=((s=d.current)==null?void 0:s.filter)??qe;return e?u(e,a.current.search):0}function $(){if(!n.current||!a.current.search||d.current.shouldFilter===!1)return;let e=a.current.filtered.items,u=[];a.current.filtered.groups.forEach(l=>{let g=i.current.get(l),C=0;g.forEach(L=>{let Le=e.get(L);C=Math.max(Le,C)}),u.push([l,C])});let s=n.current.querySelector(je);O().sort((l,g)=>{let C=l.getAttribute("id"),L=g.getAttribute("id");return(e.get(L)??0)-(e.get(C)??0)}).forEach(l=>{let g=l.closest(z);g?g.appendChild(l.parentElement===g?l:l.closest(`${z} > *`)):s.appendChild(l.parentElement===s?l:l.closest(`${z} > *`))}),u.sort((l,g)=>g[1]-l[1]).forEach(l=>{let g=n.current.querySelector(`${k}[${D}="${l[0]}"]`);g==null||g.parentElement.appendChild(g)})}function j(){let e=O().find(s=>!s.ariaDisabled),u=e==null?void 0:e.getAttribute(D);b.setState("value",u||void 0)}function U(){if(!a.current.search||d.current.shouldFilter===!1){a.current.filtered.count=c.current.size;return}a.current.filtered.groups=new Set;let e=0;for(let u of c.current){let s=f.current.get(u),l=re(s);a.current.filtered.items.set(u,l),l>0&&e++}for(let[u,s]of i.current)for(let l of s)if(a.current.filtered.items.get(l)>0){a.current.filtered.groups.add(u);break}a.current.filtered.count=e}function ne(){var u,s,l;let e=_();e&&(((u=e.parentElement)==null?void 0:u.firstChild)===e&&((l=(s=e.closest(k))==null?void 0:s.querySelector(Ue))==null||l.scrollIntoView({block:"nearest"})),e.scrollIntoView({block:"nearest"}))}function _(){var e;return(e=n.current)==null?void 0:e.querySelector(`${Z}[aria-selected="true"]`)}function O(){return Array.from(n.current.querySelectorAll(me))}function q(e){let s=O()[e];s&&b.setState("value",s.getAttribute(D))}function B(e){var C;let u=_(),s=O(),l=s.findIndex(L=>L===u),g=s[l+e];(C=d.current)!=null&&C.loop&&(g=l+e<0?s[s.length-1]:l+e===s.length?s[0]:s[l+e]),g&&b.setState("value",g.getAttribute(D))}function oe(e){let u=_(),s=u==null?void 0:u.closest(k),l;for(;s&&!l;)s=e>0?Xe(s,k):Ye(s,k),l=s==null?void 0:s.querySelector(me);l?b.setState("value",l.getAttribute(D)):B(e)}let ae=()=>q(O().length-1),ce=e=>{e.preventDefault(),e.metaKey?ae():e.altKey?oe(1):B(1)},se=e=>{e.preventDefault(),e.metaKey?q(0):e.altKey?oe(-1):B(-1)};return r.createElement("div",{ref:H([n,o]),...w,"cmdk-root":"",onKeyDown:e=>{var u;if((u=w.onKeyDown)==null||u.call(w,e),!e.defaultPrevented)switch(e.key){case"n":case"j":{K&&e.ctrlKey&&ce(e);break}case"ArrowDown":{ce(e);break}case"p":case"k":{K&&e.ctrlKey&&se(e);break}case"ArrowUp":{se(e);break}case"Home":{e.preventDefault(),q(0);break}case"End":{e.preventDefault(),ae();break}case"Enter":if(!e.nativeEvent.isComposing){e.preventDefault();let s=_();if(s){let l=new Event(Q);s.dispatchEvent(l)}}}}},r.createElement("label",{"cmdk-label":"",htmlFor:F.inputId,id:F.labelId,style:We},p),r.createElement(Re.Provider,{value:b},r.createElement(pe.Provider,{value:F},R)))}),ge=r.forwardRef((t,o)=>{var N;let n=r.useId(),a=r.useRef(null),c=r.useContext(ve),i=I(),f=Pe(t),v=((N=f.current)==null?void 0:N.forceMount)??(c==null?void 0:c.forceMount);A(()=>i.item(n,c==null?void 0:c.id),[]);let d=Me(n,a,[t.value,t.children,a]),p=ee(),R=P(h=>h.value&&h.value===d.current),m=P(h=>v||i.filter()===!1?!0:h.search?h.filtered.items.get(n)>0:!0);r.useEffect(()=>{let h=a.current;if(!(!h||t.disabled))return h.addEventListener(Q,S),()=>h.removeEventListener(Q,S)},[m,t.onSelect,t.disabled]);function S(){var h,y;T(),(y=(h=f.current).onSelect)==null||y.call(h,d.current)}function T(){p.setState("value",d.current,!0)}if(!m)return null;let{disabled:E,value:K,onSelect:w,...V}=t;return r.createElement("div",{ref:H([a,o]),...V,id:n,"cmdk-item":"",role:"option","aria-disabled":E||void 0,"aria-selected":R||void 0,"data-disabled":E||void 0,"data-selected":R||void 0,onPointerMove:E?void 0:T,onClick:E?void 0:S},t.children)}),he=r.forwardRef((t,o)=>{let{heading:n,children:a,forceMount:c,...i}=t,f=r.useId(),v=r.useRef(null),d=r.useRef(null),p=r.useId(),R=I(),m=P(E=>c||R.filter()===!1?!0:E.search?E.filtered.groups.has(f):!0);A(()=>R.group(f),[]),Me(f,v,[t.value,t.heading,d]);let S=r.useMemo(()=>({id:f,forceMount:c}),[c]),T=r.createElement(ve.Provider,{value:S},a);return r.createElement("div",{ref:H([v,o]),...i,"cmdk-group":"",role:"presentation",hidden:m?void 0:!0},n&&r.createElement("div",{ref:d,"cmdk-group-heading":"","aria-hidden":!0,id:p},n),r.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":n?p:void 0},T))}),Ee=r.forwardRef((t,o)=>{let{alwaysRender:n,...a}=t,c=r.useRef(null),i=P(f=>!f.search);return!n&&!i?null:r.createElement("div",{ref:H([c,o]),...a,"cmdk-separator":"",role:"separator"})}),Ce=r.forwardRef((t,o)=>{let{onValueChange:n,...a}=t,c=t.value!=null,i=ee(),f=P(R=>R.search),v=P(R=>R.value),d=I(),p=r.useMemo(()=>{var m;let R=(m=d.commandRef.current)==null?void 0:m.querySelector(`${Z}[${D}="${v}"]`);return R==null?void 0:R.getAttribute("id")},[v,d.commandRef]);return r.useEffect(()=>{t.value!=null&&i.setState("search",t.value)},[t.value]),r.createElement("input",{ref:o,...a,"cmdk-input":"",autoComplete:"off",autoCorrect:"off",spellCheck:!1,"aria-autocomplete":"list",role:"combobox","aria-expanded":!0,"aria-controls":d.listId,"aria-labelledby":d.labelId,"aria-activedescendant":p,id:d.inputId,type:"text",value:c?t.value:f,onChange:R=>{c||i.setState("search",R.target.value),n==null||n(R.target.value)}})}),Se=r.forwardRef((t,o)=>{let{children:n,...a}=t,c=r.useRef(null),i=r.useRef(null),f=I();return r.useEffect(()=>{if(i.current&&c.current){let v=i.current,d=c.current,p,R=new ResizeObserver(()=>{p=requestAnimationFrame(()=>{let m=v.offsetHeight;d.style.setProperty("--cmdk-list-height",m.toFixed(1)+"px")})});return R.observe(v),()=>{cancelAnimationFrame(p),R.unobserve(v)}}},[]),r.createElement("div",{ref:H([c,o]),...a,"cmdk-list":"",role:"listbox","aria-label":"Suggestions",id:f.listId,"aria-labelledby":f.inputId},r.createElement("div",{ref:i,"cmdk-list-sizer":""},n))}),be=r.forwardRef((t,o)=>{let{open:n,onOpenChange:a,overlayClassName:c,contentClassName:i,container:f,...v}=t;return r.createElement(M.Root,{open:n,onOpenChange:a},r.createElement(M.Portal,{container:f},r.createElement(M.Overlay,{"cmdk-overlay":"",className:c}),r.createElement(M.Content,{"aria-label":t.label,"cmdk-dialog":"",className:i},r.createElement(te,{ref:o,...v}))))}),Te=r.forwardRef((t,o)=>{let n=r.useRef(!0),a=P(c=>c.filtered.count===0);return r.useEffect(()=>{n.current=!1},[]),n.current||!a?null:r.createElement("div",{ref:o,...t,"cmdk-empty":"",role:"presentation"})}),ye=r.forwardRef((t,o)=>{let{progress:n,children:a,...c}=t;return r.createElement("div",{ref:o,...c,"cmdk-loading":"",role:"progressbar","aria-valuenow":n,"aria-valuemin":0,"aria-valuemax":100,"aria-label":"Loading..."},r.createElement("div",{"aria-hidden":!0},a))}),Be=Object.assign(te,{List:Se,Item:ge,Input:Ce,Group:he,Separator:Ee,Dialog:be,Empty:Te,Loading:ye});function Xe(t,o){let n=t.nextElementSibling;for(;n;){if(n.matches(o))return n;n=n.nextElementSibling}}function Ye(t,o){let n=t.previousElementSibling;for(;n;){if(n.matches(o))return n;n=n.previousElementSibling}}function Pe(t){let o=r.useRef(t);return A(()=>{o.current=t}),o}var A=typeof window>"u"?r.useEffect:r.useLayoutEffect;function x(t){let o=r.useRef();return o.current===void 0&&(o.current=t()),o}function H(t){return o=>{t.forEach(n=>{typeof n=="function"?n(o):n!=null&&(n.current=o)})}}function P(t){let o=ee(),n=()=>t(o.snapshot());return r.useSyncExternalStore(o.subscribe,n,n)}function Me(t,o,n){let a=r.useRef(),c=I();return A(()=>{var f;let i=(()=>{var v;for(let d of n){if(typeof d=="string")return d.trim().toLowerCase();if(typeof d=="object"&&"current"in d)return d.current?(v=d.current.textContent)==null?void 0:v.trim().toLowerCase():a.current}})();c.value(t,i),(f=o.current)==null||f.setAttribute(D,i),a.current=i}),a}var Je=()=>{let[t,o]=r.useState(),n=x(()=>new Map);return A(()=>{n.current.forEach(a=>a()),n.current=new Map},[t]),(a,c)=>{n.current.set(a,c),o({})}},We={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};0&&(module.exports={Command,CommandDialog,CommandEmpty,CommandGroup,CommandInput,CommandItem,CommandList,CommandLoading,CommandRoot,CommandSeparator,commandScore,useCommandState}); +diff --git a/dist/index.mjs b/dist/index.mjs +index 798a436cba7ea1506303d72e5708be4b464797e7..0cc5cf3a06d6450b21e1e51c01d39a0486d11f18 100644 +--- a/dist/index.mjs ++++ b/dist/index.mjs +@@ -1 +1 @@ +-import*as C from"@radix-ui/react-dialog";import*as t from"react";import le from"command-score";var ue='[cmdk-list-sizer=""]',M='[cmdk-group=""]',N='[cmdk-group-items=""]',de='[cmdk-group-heading=""]',ee='[cmdk-item=""]',Z=`${ee}:not([aria-disabled="true"])`,z="cmdk-item-select",S="data-value",fe=(n,a)=>le(n,a),te=t.createContext(void 0),k=()=>t.useContext(te),re=t.createContext(void 0),U=()=>t.useContext(re),ne=t.createContext(void 0),oe=t.forwardRef((n,a)=>{let r=t.useRef(null),o=x(()=>({search:"",value:"",filtered:{count:0,items:new Map,groups:new Set}})),u=x(()=>new Set),l=x(()=>new Map),p=x(()=>new Map),f=x(()=>new Set),d=ae(n),{label:v,children:E,value:R,onValueChange:w,filter:O,shouldFilter:ie,...D}=n,F=t.useId(),g=t.useId(),A=t.useId(),y=ye();L(()=>{if(R!==void 0){let e=R.trim().toLowerCase();o.current.value=e,y(6,W),h.emit()}},[R]);let h=t.useMemo(()=>({subscribe:e=>(f.current.add(e),()=>f.current.delete(e)),snapshot:()=>o.current,setState:(e,c,i)=>{var s,m,b;if(!Object.is(o.current[e],c)){if(o.current[e]=c,e==="search")j(),G(),y(1,V);else if(e==="value")if(((s=d.current)==null?void 0:s.value)!==void 0){(b=(m=d.current).onValueChange)==null||b.call(m,c);return}else i||y(5,W);h.emit()}},emit:()=>{f.current.forEach(e=>e())}}),[]),K=t.useMemo(()=>({value:(e,c)=>{c!==p.current.get(e)&&(p.current.set(e,c),o.current.filtered.items.set(e,B(c)),y(2,()=>{G(),h.emit()}))},item:(e,c)=>(u.current.add(e),c&&(l.current.has(c)?l.current.get(c).add(e):l.current.set(c,new Set([e]))),y(3,()=>{j(),G(),o.current.value||V(),h.emit()}),()=>{p.current.delete(e),u.current.delete(e),o.current.filtered.items.delete(e),y(4,()=>{j(),V(),h.emit()})}),group:e=>(l.current.has(e)||l.current.set(e,new Set),()=>{p.current.delete(e),l.current.delete(e)}),filter:()=>d.current.shouldFilter,label:v||n["aria-label"],listId:F,inputId:A,labelId:g}),[]);function B(e){var i;let c=((i=d.current)==null?void 0:i.filter)??fe;return e?c(e,o.current.search):0}function G(){if(!r.current||!o.current.search||d.current.shouldFilter===!1)return;let e=o.current.filtered.items,c=[];o.current.filtered.groups.forEach(s=>{let m=l.current.get(s),b=0;m.forEach(P=>{let ce=e.get(P);b=Math.max(ce,b)}),c.push([s,b])});let i=r.current.querySelector(ue);I().sort((s,m)=>{let b=s.getAttribute(S),P=m.getAttribute(S);return(e.get(P)??0)-(e.get(b)??0)}).forEach(s=>{let m=s.closest(N);m?m.appendChild(s.parentElement===m?s:s.closest(`${N} > *`)):i.appendChild(s.parentElement===i?s:s.closest(`${N} > *`))}),c.sort((s,m)=>m[1]-s[1]).forEach(s=>{let m=r.current.querySelector(`${M}[${S}="${s[0]}"]`);m==null||m.parentElement.appendChild(m)})}function V(){let e=I().find(i=>!i.ariaDisabled),c=e==null?void 0:e.getAttribute(S);h.setState("value",c||void 0)}function j(){if(!o.current.search||d.current.shouldFilter===!1){o.current.filtered.count=u.current.size;return}o.current.filtered.groups=new Set;let e=0;for(let c of u.current){let i=p.current.get(c),s=B(i);o.current.filtered.items.set(c,s),s>0&&e++}for(let[c,i]of l.current)for(let s of i)if(o.current.filtered.items.get(s)>0){o.current.filtered.groups.add(c);break}o.current.filtered.count=e}function W(){var c,i,s;let e=_();e&&(((c=e.parentElement)==null?void 0:c.firstChild)===e&&((s=(i=e.closest(M))==null?void 0:i.querySelector(de))==null||s.scrollIntoView({block:"nearest"})),e.scrollIntoView({block:"nearest"}))}function _(){return r.current.querySelector(`${ee}[aria-selected="true"]`)}function I(){return Array.from(r.current.querySelectorAll(Z))}function q(e){let i=I()[e];i&&h.setState("value",i.getAttribute(S))}function $(e){var b;let c=_(),i=I(),s=i.findIndex(P=>P===c),m=i[s+e];(b=d.current)!=null&&b.loop&&(m=s+e<0?i[i.length-1]:s+e===i.length?i[0]:i[s+e]),m&&h.setState("value",m.getAttribute(S))}function J(e){let c=_(),i=c==null?void 0:c.closest(M),s;for(;i&&!s;)i=e>0?Se(i,M):Ce(i,M),s=i==null?void 0:i.querySelector(Z);s?h.setState("value",s.getAttribute(S)):$(e)}let Q=()=>q(I().length-1),X=e=>{e.preventDefault(),e.metaKey?Q():e.altKey?J(1):$(1)},Y=e=>{e.preventDefault(),e.metaKey?q(0):e.altKey?J(-1):$(-1)};return t.createElement("div",{ref:H([r,a]),...D,"cmdk-root":"",onKeyDown:e=>{var c;if((c=D.onKeyDown)==null||c.call(D,e),!e.defaultPrevented)switch(e.key){case"n":case"j":{e.ctrlKey&&X(e);break}case"ArrowDown":{X(e);break}case"p":case"k":{e.ctrlKey&&Y(e);break}case"ArrowUp":{Y(e);break}case"Home":{e.preventDefault(),q(0);break}case"End":{e.preventDefault(),Q();break}case"Enter":{e.preventDefault();let i=_();if(i){let s=new Event(z);i.dispatchEvent(s)}}}}},t.createElement("label",{"cmdk-label":"",htmlFor:K.inputId,id:K.labelId,style:xe},v),t.createElement(re.Provider,{value:h},t.createElement(te.Provider,{value:K},E)))}),me=t.forwardRef((n,a)=>{let r=t.useId(),o=t.useRef(null),u=t.useContext(ne),l=k(),p=ae(n);L(()=>l.item(r,u),[]);let f=se(r,o,[n.value,n.children,o]),d=U(),v=T(g=>g.value&&g.value===f.current),E=T(g=>l.filter()===!1?!0:g.search?g.filtered.items.get(r)>0:!0);t.useEffect(()=>{let g=o.current;if(!(!g||n.disabled))return g.addEventListener(z,R),()=>g.removeEventListener(z,R)},[E,n.onSelect,n.disabled]);function R(){var g,A;(A=(g=p.current).onSelect)==null||A.call(g,f.current)}function w(){d.setState("value",f.current,!0)}if(!E)return null;let{disabled:O,value:ie,onSelect:D,...F}=n;return t.createElement("div",{ref:H([o,a]),...F,"cmdk-item":"",role:"option","aria-disabled":O||void 0,"aria-selected":v||void 0,"data-selected":v||void 0,onPointerMove:O?void 0:w,onClick:O?void 0:R},n.children)}),pe=t.forwardRef((n,a)=>{let{heading:r,children:o,...u}=n,l=t.useId(),p=t.useRef(null),f=t.useRef(null),d=t.useId(),v=k(),E=T(w=>v.filter()===!1?!0:w.search?w.filtered.groups.has(l):!0);L(()=>v.group(l),[]),se(l,p,[n.value,n.heading,f]);let R=t.createElement(ne.Provider,{value:l},o);return t.createElement("div",{ref:H([p,a]),...u,"cmdk-group":"",role:"presentation",hidden:E?void 0:!0},r&&t.createElement("div",{ref:f,"cmdk-group-heading":"","aria-hidden":!0,id:d},r),t.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":r?d:void 0},R))}),ge=t.forwardRef((n,a)=>{let{alwaysRender:r,...o}=n,u=t.useRef(null),l=T(p=>!p.search);return!r&&!l?null:t.createElement("div",{ref:H([u,a]),...o,"cmdk-separator":"",role:"separator"})}),ve=t.forwardRef((n,a)=>{let{onValueChange:r,...o}=n,u=n.value!=null,l=U(),p=T(d=>d.search),f=k();return t.useEffect(()=>{n.value!=null&&l.setState("search",n.value)},[n.value]),t.createElement("input",{ref:a,...o,"cmdk-input":"",autoComplete:"off",autoCorrect:"off",spellCheck:!1,"aria-autocomplete":"list",role:"combobox","aria-expanded":!0,"aria-controls":f.listId,"aria-labelledby":f.labelId,id:f.inputId,type:"text",value:u?n.value:p,onChange:d=>{u||l.setState("search",d.target.value),r==null||r(d.target.value)}})}),Re=t.forwardRef((n,a)=>{let{children:r,...o}=n,u=t.useRef(null),l=t.useRef(null),p=k();return t.useEffect(()=>{if(l.current&&u.current){let f=l.current,d=u.current,v,E=new ResizeObserver(()=>{v=requestAnimationFrame(()=>{let R=f.getBoundingClientRect().height;d.style.setProperty("--cmdk-list-height",R.toFixed(1)+"px")})});return E.observe(f),()=>{cancelAnimationFrame(v),E.unobserve(f)}}},[]),t.createElement("div",{ref:H([u,a]),...o,"cmdk-list":"",role:"listbox","aria-label":"Suggestions",id:p.listId,"aria-labelledby":p.inputId},t.createElement("div",{ref:l,"cmdk-list-sizer":""},r))}),be=t.forwardRef((n,a)=>{let{open:r,onOpenChange:o,container:u,...l}=n;return t.createElement(C.Root,{open:r,onOpenChange:o},t.createElement(C.Portal,{container:u},t.createElement(C.Overlay,{"cmdk-overlay":""}),t.createElement(C.Content,{"aria-label":n.label,"cmdk-dialog":""},t.createElement(oe,{ref:a,...l}))))}),he=t.forwardRef((n,a)=>{let r=t.useRef(!0),o=T(u=>u.filtered.count===0);return t.useEffect(()=>{r.current=!1},[]),r.current||!o?null:t.createElement("div",{ref:a,...n,"cmdk-empty":"",role:"presentation"})}),Ee=t.forwardRef((n,a)=>{let{progress:r,children:o,...u}=n;return t.createElement("div",{ref:a,...u,"cmdk-loading":"",role:"progressbar","aria-valuenow":r,"aria-valuemin":0,"aria-valuemax":100,"aria-label":"Loading..."},t.createElement("div",{"aria-hidden":!0},o))}),Le=Object.assign(oe,{List:Re,Item:me,Input:ve,Group:pe,Separator:ge,Dialog:be,Empty:he,Loading:Ee});function Se(n,a){let r=n.nextElementSibling;for(;r;){if(r.matches(a))return r;r=r.nextElementSibling}}function Ce(n,a){let r=n.previousElementSibling;for(;r;){if(r.matches(a))return r;r=r.previousElementSibling}}function ae(n){let a=t.useRef(n);return L(()=>{a.current=n}),a}var L=typeof window>"u"?t.useEffect:t.useLayoutEffect;function x(n){let a=t.useRef();return a.current===void 0&&(a.current=n()),a}function H(n){return a=>{n.forEach(r=>{typeof r=="function"?r(a):r!=null&&(r.current=a)})}}function T(n){let a=U(),r=()=>n(a.snapshot());return t.useSyncExternalStore(a.subscribe,r,r)}function se(n,a,r){let o=t.useRef(),u=k();return L(()=>{var p;let l=(()=>{var f;for(let d of r){if(typeof d=="string")return d.trim().toLowerCase();if(typeof d=="object"&&"current"in d&&d.current)return(f=d.current.textContent)==null?void 0:f.trim().toLowerCase()}})();u.value(n,l),(p=a.current)==null||p.setAttribute(S,l),o.current=l}),o}var ye=()=>{let[n,a]=t.useState(),r=x(()=>new Map);return L(()=>{r.current.forEach(o=>o()),r.current=new Map},[n]),(o,u)=>{r.current.set(o,u),a({})}},xe={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};export{Le as Command,be as CommandDialog,he as CommandEmpty,pe as CommandGroup,ve as CommandInput,me as CommandItem,Re as CommandList,Ee as CommandLoading,oe as CommandRoot,ge as CommandSeparator,T as useCommandState}; ++import*as P from"@radix-ui/react-dialog";import*as t from"react";var ae=1,ge=.9,he=.8,Ee=.17,B=.1,X=.999,Ce=.9999;var Se=.99,be=/[\\\/_+.#"@\[\(\{&]/,Te=/[\\\/_+.#"@\[\(\{&]/g,ye=/[\s-]/,se=/[\s-]/g;function Y(r,a,n,o,c,i,f){if(i===a.length)return c===r.length?ae:Se;var v=`${c},${i}`;if(f[v]!==void 0)return f[v];for(var d=o.charAt(i),p=n.indexOf(d,c),R=0,m,S,T,E;p>=0;)m=Y(r,a,n,o,p+1,i+1,f),m>R&&(p===c?m*=ae:be.test(r.charAt(p-1))?(m*=he,T=r.slice(c,p-1).match(Te),T&&c>0&&(m*=Math.pow(X,T.length))):ye.test(r.charAt(p-1))?(m*=ge,E=r.slice(c,p-1).match(se),E&&c>0&&(m*=Math.pow(X,E.length))):(m*=Ee,c>0&&(m*=Math.pow(X,p-c))),r.charAt(p)!==a.charAt(i)&&(m*=Ce)),(mm&&(m=S*B)),m>R&&(R=m),p=n.indexOf(d,p+1);return f[v]=R,R}function ce(r){return r.toLowerCase().replace(se," ")}function ie(r,a){return Y(r,a,ce(r),ce(a),0,0,{})}var Pe='[cmdk-list-sizer=""]',k='[cmdk-group=""]',J='[cmdk-group-items=""]',Me='[cmdk-group-heading=""]',z='[cmdk-item=""]',le=`${z}:not([aria-disabled="true"])`,W="cmdk-item-select",L="data-value",Le=(r,a)=>ie(r,a),ue=t.createContext(void 0),I=()=>t.useContext(ue),de=t.createContext(void 0),Q=()=>t.useContext(de),fe=t.createContext(void 0),me=t.forwardRef((r,a)=>{let n=t.useRef(null),o=x(()=>{var e;return{search:"",value:r.value??((e=r.defaultValue)==null?void 0:e.toLowerCase())??"",filtered:{count:0,items:new Map,groups:new Set}}}),c=x(()=>new Set),i=x(()=>new Map),f=x(()=>new Map),v=x(()=>new Set),d=pe(r),{label:p,children:R,value:m,onValueChange:S,filter:T,shouldFilter:E,vimBindings:G=!0,...w}=r,K=t.useId(),N=t.useId(),h=t.useId(),y=Ge();A(()=>{if(m!==void 0){let e=m.trim().toLowerCase();o.current.value=e,y(6,ee),b.emit()}},[m]);let b=t.useMemo(()=>({subscribe:e=>(v.current.add(e),()=>v.current.delete(e)),snapshot:()=>o.current,setState:(e,u,s)=>{var l,g,C;if(!Object.is(o.current[e],u)){if(o.current[e]=u,e==="search")j(),F(),y(1,$);else if(e==="value")if(((l=d.current)==null?void 0:l.value)!==void 0){let M=u??"";(C=(g=d.current).onValueChange)==null||C.call(g,M);return}else s||y(5,ee);b.emit()}},emit:()=>{v.current.forEach(e=>e())}}),[]),V=t.useMemo(()=>({value:(e,u)=>{u!==f.current.get(e)&&(f.current.set(e,u),o.current.filtered.items.set(e,Z(u)),y(2,()=>{F(),b.emit()}))},item:(e,u)=>(c.current.add(e),u&&(i.current.has(u)?i.current.get(u).add(e):i.current.set(u,new Set([e]))),y(3,()=>{j(),F(),o.current.value||$(),b.emit()}),()=>{f.current.delete(e),c.current.delete(e),o.current.filtered.items.delete(e);let s=_();y(4,()=>{j(),(s==null?void 0:s.getAttribute("id"))===e&&$(),b.emit()})}),group:e=>(i.current.has(e)||i.current.set(e,new Set),()=>{f.current.delete(e),i.current.delete(e)}),filter:()=>d.current.shouldFilter,label:p||r["aria-label"],commandRef:n,listId:K,inputId:h,labelId:N}),[]);function Z(e){var s;let u=((s=d.current)==null?void 0:s.filter)??Le;return e?u(e,o.current.search):0}function F(){if(!n.current||!o.current.search||d.current.shouldFilter===!1)return;let e=o.current.filtered.items,u=[];o.current.filtered.groups.forEach(l=>{let g=i.current.get(l),C=0;g.forEach(M=>{let ve=e.get(M);C=Math.max(ve,C)}),u.push([l,C])});let s=n.current.querySelector(Pe);O().sort((l,g)=>{let C=l.getAttribute("id"),M=g.getAttribute("id");return(e.get(M)??0)-(e.get(C)??0)}).forEach(l=>{let g=l.closest(J);g?g.appendChild(l.parentElement===g?l:l.closest(`${J} > *`)):s.appendChild(l.parentElement===s?l:l.closest(`${J} > *`))}),u.sort((l,g)=>g[1]-l[1]).forEach(l=>{let g=n.current.querySelector(`${k}[${L}="${l[0]}"]`);g==null||g.parentElement.appendChild(g)})}function $(){let e=O().find(s=>!s.ariaDisabled),u=e==null?void 0:e.getAttribute(L);b.setState("value",u||void 0)}function j(){if(!o.current.search||d.current.shouldFilter===!1){o.current.filtered.count=c.current.size;return}o.current.filtered.groups=new Set;let e=0;for(let u of c.current){let s=f.current.get(u),l=Z(s);o.current.filtered.items.set(u,l),l>0&&e++}for(let[u,s]of i.current)for(let l of s)if(o.current.filtered.items.get(l)>0){o.current.filtered.groups.add(u);break}o.current.filtered.count=e}function ee(){var u,s,l;let e=_();e&&(((u=e.parentElement)==null?void 0:u.firstChild)===e&&((l=(s=e.closest(k))==null?void 0:s.querySelector(Me))==null||l.scrollIntoView({block:"nearest"})),e.scrollIntoView({block:"nearest"}))}function _(){var e;return(e=n.current)==null?void 0:e.querySelector(`${z}[aria-selected="true"]`)}function O(){return Array.from(n.current.querySelectorAll(le))}function U(e){let s=O()[e];s&&b.setState("value",s.getAttribute(L))}function q(e){var C;let u=_(),s=O(),l=s.findIndex(M=>M===u),g=s[l+e];(C=d.current)!=null&&C.loop&&(g=l+e<0?s[s.length-1]:l+e===s.length?s[0]:s[l+e]),g&&b.setState("value",g.getAttribute(L))}function te(e){let u=_(),s=u==null?void 0:u.closest(k),l;for(;s&&!l;)s=e>0?He(s,k):Ne(s,k),l=s==null?void 0:s.querySelector(le);l?b.setState("value",l.getAttribute(L)):q(e)}let re=()=>U(O().length-1),ne=e=>{e.preventDefault(),e.metaKey?re():e.altKey?te(1):q(1)},oe=e=>{e.preventDefault(),e.metaKey?U(0):e.altKey?te(-1):q(-1)};return t.createElement("div",{ref:H([n,a]),...w,"cmdk-root":"",onKeyDown:e=>{var u;if((u=w.onKeyDown)==null||u.call(w,e),!e.defaultPrevented)switch(e.key){case"n":case"j":{G&&e.ctrlKey&&ne(e);break}case"ArrowDown":{ne(e);break}case"p":case"k":{G&&e.ctrlKey&&oe(e);break}case"ArrowUp":{oe(e);break}case"Home":{e.preventDefault(),U(0);break}case"End":{e.preventDefault(),re();break}case"Enter":if(!e.nativeEvent.isComposing){e.preventDefault();let s=_();if(s){let l=new Event(W);s.dispatchEvent(l)}}}}},t.createElement("label",{"cmdk-label":"",htmlFor:V.inputId,id:V.labelId,style:Ke},p),t.createElement(de.Provider,{value:b},t.createElement(ue.Provider,{value:V},R)))}),De=t.forwardRef((r,a)=>{var N;let n=t.useId(),o=t.useRef(null),c=t.useContext(fe),i=I(),f=pe(r),v=((N=f.current)==null?void 0:N.forceMount)??(c==null?void 0:c.forceMount);A(()=>i.item(n,c==null?void 0:c.id),[]);let d=Re(n,o,[r.value,r.children,o]),p=Q(),R=D(h=>h.value&&h.value===d.current),m=D(h=>v||i.filter()===!1?!0:h.search?h.filtered.items.get(n)>0:!0);t.useEffect(()=>{let h=o.current;if(!(!h||r.disabled))return h.addEventListener(W,S),()=>h.removeEventListener(W,S)},[m,r.onSelect,r.disabled]);function S(){var h,y;T(),(y=(h=f.current).onSelect)==null||y.call(h,d.current)}function T(){p.setState("value",d.current,!0)}if(!m)return null;let{disabled:E,value:G,onSelect:w,...K}=r;return t.createElement("div",{ref:H([o,a]),...K,id:n,"cmdk-item":"",role:"option","aria-disabled":E||void 0,"aria-selected":R||void 0,"data-disabled":E||void 0,"data-selected":R||void 0,onPointerMove:E?void 0:T,onClick:E?void 0:S},r.children)}),xe=t.forwardRef((r,a)=>{let{heading:n,children:o,forceMount:c,...i}=r,f=t.useId(),v=t.useRef(null),d=t.useRef(null),p=t.useId(),R=I(),m=D(E=>c||R.filter()===!1?!0:E.search?E.filtered.groups.has(f):!0);A(()=>R.group(f),[]),Re(f,v,[r.value,r.heading,d]);let S=t.useMemo(()=>({id:f,forceMount:c}),[c]),T=t.createElement(fe.Provider,{value:S},o);return t.createElement("div",{ref:H([v,a]),...i,"cmdk-group":"",role:"presentation",hidden:m?void 0:!0},n&&t.createElement("div",{ref:d,"cmdk-group-heading":"","aria-hidden":!0,id:p},n),t.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":n?p:void 0},T))}),Ae=t.forwardRef((r,a)=>{let{alwaysRender:n,...o}=r,c=t.useRef(null),i=D(f=>!f.search);return!n&&!i?null:t.createElement("div",{ref:H([c,a]),...o,"cmdk-separator":"",role:"separator"})}),we=t.forwardRef((r,a)=>{let{onValueChange:n,...o}=r,c=r.value!=null,i=Q(),f=D(R=>R.search),v=D(R=>R.value),d=I(),p=t.useMemo(()=>{var m;let R=(m=d.commandRef.current)==null?void 0:m.querySelector(`${z}[${L}="${v}"]`);return R==null?void 0:R.getAttribute("id")},[v,d.commandRef]);return t.useEffect(()=>{r.value!=null&&i.setState("search",r.value)},[r.value]),t.createElement("input",{ref:a,...o,"cmdk-input":"",autoComplete:"off",autoCorrect:"off",spellCheck:!1,"aria-autocomplete":"list",role:"combobox","aria-expanded":!0,"aria-controls":d.listId,"aria-labelledby":d.labelId,"aria-activedescendant":p,id:d.inputId,type:"text",value:c?r.value:f,onChange:R=>{c||i.setState("search",R.target.value),n==null||n(R.target.value)}})}),_e=t.forwardRef((r,a)=>{let{children:n,...o}=r,c=t.useRef(null),i=t.useRef(null),f=I();return t.useEffect(()=>{if(i.current&&c.current){let v=i.current,d=c.current,p,R=new ResizeObserver(()=>{p=requestAnimationFrame(()=>{let m=v.offsetHeight;d.style.setProperty("--cmdk-list-height",m.toFixed(1)+"px")})});return R.observe(v),()=>{cancelAnimationFrame(p),R.unobserve(v)}}},[]),t.createElement("div",{ref:H([c,a]),...o,"cmdk-list":"",role:"listbox","aria-label":"Suggestions",id:f.listId,"aria-labelledby":f.inputId},t.createElement("div",{ref:i,"cmdk-list-sizer":""},n))}),Oe=t.forwardRef((r,a)=>{let{open:n,onOpenChange:o,overlayClassName:c,contentClassName:i,container:f,...v}=r;return t.createElement(P.Root,{open:n,onOpenChange:o},t.createElement(P.Portal,{container:f},t.createElement(P.Overlay,{"cmdk-overlay":"",className:c}),t.createElement(P.Content,{"aria-label":r.label,"cmdk-dialog":"",className:i},t.createElement(me,{ref:a,...v}))))}),ke=t.forwardRef((r,a)=>{let n=t.useRef(!0),o=D(c=>c.filtered.count===0);return t.useEffect(()=>{n.current=!1},[]),n.current||!o?null:t.createElement("div",{ref:a,...r,"cmdk-empty":"",role:"presentation"})}),Ie=t.forwardRef((r,a)=>{let{progress:n,children:o,...c}=r;return t.createElement("div",{ref:a,...c,"cmdk-loading":"",role:"progressbar","aria-valuenow":n,"aria-valuemin":0,"aria-valuemax":100,"aria-label":"Loading..."},t.createElement("div",{"aria-hidden":!0},o))}),$e=Object.assign(me,{List:_e,Item:De,Input:we,Group:xe,Separator:Ae,Dialog:Oe,Empty:ke,Loading:Ie});function He(r,a){let n=r.nextElementSibling;for(;n;){if(n.matches(a))return n;n=n.nextElementSibling}}function Ne(r,a){let n=r.previousElementSibling;for(;n;){if(n.matches(a))return n;n=n.previousElementSibling}}function pe(r){let a=t.useRef(r);return A(()=>{a.current=r}),a}var A=typeof window>"u"?t.useEffect:t.useLayoutEffect;function x(r){let a=t.useRef();return a.current===void 0&&(a.current=r()),a}function H(r){return a=>{r.forEach(n=>{typeof n=="function"?n(a):n!=null&&(n.current=a)})}}function D(r){let a=Q(),n=()=>r(a.snapshot());return t.useSyncExternalStore(a.subscribe,n,n)}function Re(r,a,n){let o=t.useRef(),c=I();return A(()=>{var f;let i=(()=>{var v;for(let d of n){if(typeof d=="string")return d.trim().toLowerCase();if(typeof d=="object"&&"current"in d)return d.current?(v=d.current.textContent)==null?void 0:v.trim().toLowerCase():o.current}})();c.value(r,i),(f=a.current)==null||f.setAttribute(L,i),o.current=i}),o}var Ge=()=>{let[r,a]=t.useState(),n=x(()=>new Map);return A(()=>{n.current.forEach(o=>o()),n.current=new Map},[r]),(o,c)=>{n.current.set(o,c),a({})}},Ke={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};export{$e as Command,Oe as CommandDialog,ke as CommandEmpty,xe as CommandGroup,we as CommandInput,De as CommandItem,_e as CommandList,Ie as CommandLoading,me as CommandRoot,Ae as CommandSeparator,ie as commandScore,D as useCommandState}; diff --git a/package.json b/package.json index ec60f92b6..dd8bbf264 100644 --- a/package.json +++ b/package.json @@ -172,6 +172,7 @@ "next-auth@^4.24.5": "patch:next-auth@npm%3A4.24.5#~/.yarn/patches/next-auth-npm-4.24.5-8428e11927.patch", "@reforged/maker-appimage/@electron-forge/maker-base": "7.2.0", "macos-alias": "npm:macos-alias-building@latest", - "fs-xattr": "npm:@napi-rs/xattr@latest" + "fs-xattr": "npm:@napi-rs/xattr@latest", + "@radix-ui/react-dialog": "npm:@radix-ui/react-dialog@latest" } } diff --git a/packages/common/cmdk/LICENSE.md b/packages/common/cmdk/LICENSE.md deleted file mode 100644 index 76228ccc3..000000000 --- a/packages/common/cmdk/LICENSE.md +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2022 Paco Coursey - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/packages/common/cmdk/README.md b/packages/common/cmdk/README.md deleted file mode 100644 index f4a7a1fa3..000000000 --- a/packages/common/cmdk/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# copied directly from https://github.com/pacocoursey/cmdk - -will remove after a new CMDK version is published to npm diff --git a/packages/common/cmdk/package.json b/packages/common/cmdk/package.json deleted file mode 100644 index b7017dcd7..000000000 --- a/packages/common/cmdk/package.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "name": "@affine/cmdk", - "private": true, - "type": "module", - "main": "./src/index.tsx", - "module": "./src/index.tsx", - "devDependencies": { - "react": "18.2.0", - "react-dom": "18.2.0" - }, - "dependencies": { - "@radix-ui/react-dialog": "^1.0.5" - }, - "version": "0.11.0" -} diff --git a/packages/common/cmdk/src/command-score.ts b/packages/common/cmdk/src/command-score.ts deleted file mode 100644 index ee4eff7d7..000000000 --- a/packages/common/cmdk/src/command-score.ts +++ /dev/null @@ -1,179 +0,0 @@ -/* eslint-disable */ -// @ts-nocheck - -// The scores are arranged so that a continuous match of characters will -// result in a total score of 1. -// -// The best case, this character is a match, and either this is the start -// of the string, or the previous character was also a match. -var SCORE_CONTINUE_MATCH = 1, - // A new match at the start of a word scores better than a new match - // elsewhere as it's more likely that the user will type the starts - // of fragments. - // NOTE: We score word jumps between spaces slightly higher than slashes, brackets - // hyphens, etc. - SCORE_SPACE_WORD_JUMP = 0.9, - SCORE_NON_SPACE_WORD_JUMP = 0.8, - // Any other match isn't ideal, but we include it for completeness. - SCORE_CHARACTER_JUMP = 0.17, - // If the user transposed two letters, it should be significantly penalized. - // - // i.e. "ouch" is more likely than "curtain" when "uc" is typed. - SCORE_TRANSPOSITION = 0.1, - // The goodness of a match should decay slightly with each missing - // character. - // - // i.e. "bad" is more likely than "bard" when "bd" is typed. - // - // This will not change the order of suggestions based on SCORE_* until - // 100 characters are inserted between matches. - PENALTY_SKIPPED = 0.999, - // The goodness of an exact-case match should be higher than a - // case-insensitive match by a small amount. - // - // i.e. "HTML" is more likely than "haml" when "HM" is typed. - // - // This will not change the order of suggestions based on SCORE_* until - // 1000 characters are inserted between matches. - PENALTY_CASE_MISMATCH = 0.9999, - // Match higher for letters closer to the beginning of the word - PENALTY_DISTANCE_FROM_START = 0.9, - // If the word has more characters than the user typed, it should - // be penalised slightly. - // - // i.e. "html" is more likely than "html5" if I type "html". - // - // However, it may well be the case that there's a sensible secondary - // ordering (like alphabetical) that it makes sense to rely on when - // there are many prefix matches, so we don't make the penalty increase - // with the number of tokens. - PENALTY_NOT_COMPLETE = 0.99; - -var IS_GAP_REGEXP = /[\\\/_+.#"@\[\(\{&]/, - COUNT_GAPS_REGEXP = /[\\\/_+.#"@\[\(\{&]/g, - IS_SPACE_REGEXP = /[\s-]/, - COUNT_SPACE_REGEXP = /[\s-]/g; - -function commandScoreInner( - string, - abbreviation, - lowerString, - lowerAbbreviation, - stringIndex, - abbreviationIndex, - memoizedResults -) { - if (abbreviationIndex === abbreviation.length) { - if (stringIndex === string.length) { - return SCORE_CONTINUE_MATCH; - } - return PENALTY_NOT_COMPLETE; - } - - var memoizeKey = `${stringIndex},${abbreviationIndex}`; - if (memoizedResults[memoizeKey] !== undefined) { - return memoizedResults[memoizeKey]; - } - - var abbreviationChar = lowerAbbreviation.charAt(abbreviationIndex); - var index = lowerString.indexOf(abbreviationChar, stringIndex); - var highScore = 0; - - var score, transposedScore, wordBreaks, spaceBreaks; - - while (index >= 0) { - score = commandScoreInner( - string, - abbreviation, - lowerString, - lowerAbbreviation, - index + 1, - abbreviationIndex + 1, - memoizedResults - ); - if (score > highScore) { - if (index === stringIndex) { - score *= SCORE_CONTINUE_MATCH; - } else if (IS_GAP_REGEXP.test(string.charAt(index - 1))) { - score *= SCORE_NON_SPACE_WORD_JUMP; - wordBreaks = string - .slice(stringIndex, index - 1) - .match(COUNT_GAPS_REGEXP); - if (wordBreaks && stringIndex > 0) { - score *= Math.pow(PENALTY_SKIPPED, wordBreaks.length); - } - } else if (IS_SPACE_REGEXP.test(string.charAt(index - 1))) { - score *= SCORE_SPACE_WORD_JUMP; - spaceBreaks = string - .slice(stringIndex, index - 1) - .match(COUNT_SPACE_REGEXP); - if (spaceBreaks && stringIndex > 0) { - score *= Math.pow(PENALTY_SKIPPED, spaceBreaks.length); - } - } else { - score *= SCORE_CHARACTER_JUMP; - if (stringIndex > 0) { - score *= Math.pow(PENALTY_SKIPPED, index - stringIndex); - } - } - - if (string.charAt(index) !== abbreviation.charAt(abbreviationIndex)) { - score *= PENALTY_CASE_MISMATCH; - } - } - - if ( - (score < SCORE_TRANSPOSITION && - lowerString.charAt(index - 1) === - lowerAbbreviation.charAt(abbreviationIndex + 1)) || - (lowerAbbreviation.charAt(abbreviationIndex + 1) === - lowerAbbreviation.charAt(abbreviationIndex) && // allow duplicate letters. Ref #7428 - lowerString.charAt(index - 1) !== - lowerAbbreviation.charAt(abbreviationIndex)) - ) { - transposedScore = commandScoreInner( - string, - abbreviation, - lowerString, - lowerAbbreviation, - index + 1, - abbreviationIndex + 2, - memoizedResults - ); - - if (transposedScore * SCORE_TRANSPOSITION > score) { - score = transposedScore * SCORE_TRANSPOSITION; - } - } - - if (score > highScore) { - highScore = score; - } - - index = lowerString.indexOf(abbreviationChar, index + 1); - } - - memoizedResults[memoizeKey] = highScore; - return highScore; -} - -function formatInput(string) { - // convert all valid space characters to space so they match each other - return string.toLowerCase().replace(COUNT_SPACE_REGEXP, ' '); -} - -export function commandScore(string: string, abbreviation: string): number { - /* NOTE: - * in the original, we used to do the lower-casing on each recursive call, but this meant that toLowerCase() - * was the dominating cost in the algorithm, passing both is a little ugly, but considerably faster. - */ - return commandScoreInner( - string, - abbreviation, - formatInput(string), - formatInput(abbreviation), - 0, - 0, - {} - ); -} diff --git a/packages/common/cmdk/src/index.tsx b/packages/common/cmdk/src/index.tsx deleted file mode 100644 index e8549a438..000000000 --- a/packages/common/cmdk/src/index.tsx +++ /dev/null @@ -1,1151 +0,0 @@ -/* eslint-disable */ -// @ts-nocheck -import * as RadixDialog from '@radix-ui/react-dialog'; -import * as React from 'react'; -import { commandScore } from './command-score'; - -type Children = { - children?: React.ReactNode; -}; -type DivProps = React.HTMLAttributes; - -type LoadingProps = Children & - DivProps & { - /** Estimated progress of loading asynchronous options. */ - progress?: number; - }; -type EmptyProps = Children & DivProps & {}; -type SeparatorProps = DivProps & { - /** Whether this separator should always be rendered. Useful if you disable automatic filtering. */ - alwaysRender?: boolean; -}; -type DialogProps = RadixDialog.DialogProps & - CommandProps & { - /** Provide a className to the Dialog overlay. */ - overlayClassName?: string; - /** Provide a className to the Dialog content. */ - contentClassName?: string; - /** Provide a custom element the Dialog should portal into. */ - container?: HTMLElement; - }; -type ListProps = Children & DivProps & {}; -type ItemProps = Children & - Omit & { - /** Whether this item is currently disabled. */ - disabled?: boolean; - /** Event handler for when this item is selected, either via click or keyboard selection. */ - onSelect?: (value: string) => void; - /** - * A unique value for this item. - * If no value is provided, it will be inferred from `children` or the rendered `textContent`. If your `textContent` changes between renders, you _must_ provide a stable, unique `value`. - */ - value?: string; - /** Whether this item is forcibly rendered regardless of filtering. */ - forceMount?: boolean; - }; -type GroupProps = Children & - Omit & { - /** Optional heading to render for this group. */ - heading?: React.ReactNode; - /** If no heading is provided, you must provide a value that is unique for this group. */ - value?: string; - /** Whether this group is forcibly rendered regardless of filtering. */ - forceMount?: boolean; - }; -type InputProps = Omit< - React.InputHTMLAttributes, - 'value' | 'onChange' | 'type' -> & { - /** - * Optional controlled state for the value of the search input. - */ - value?: string; - /** - * Event handler called when the search value changes. - */ - onValueChange?: (search: string) => void; -}; -type CommandProps = Children & - DivProps & { - /** - * Accessible label for this command menu. Not shown visibly. - */ - label?: string; - /** - * Optionally set to `false` to turn off the automatic filtering and sorting. - * If `false`, you must conditionally render valid items based on the search query yourself. - */ - shouldFilter?: boolean; - /** - * Custom filter function for whether each command menu item should matches the given search query. - * It should return a number between 0 and 1, with 1 being the best match and 0 being hidden entirely. - * By default, uses the `command-score` library. - */ - filter?: (value: string, search: string) => number; - /** - * Optional default item value when it is initially rendered. - */ - defaultValue?: string; - /** - * Optional controlled state of the selected command menu item. - */ - value?: string; - /** - * Event handler called when the selected item of the menu changes. - */ - onValueChange?: (value: string) => void; - /** - * Optionally set to `true` to turn on looping around when using the arrow keys. - */ - loop?: boolean; - /** - * Set to `false` to disable ctrl+n/j/p/k shortcuts. Defaults to `true`. - */ - vimBindings?: boolean; - }; - -type Context = { - value: (id: string, value: string) => void; - item: (id: string, groupId: string) => () => void; - group: (id: string) => () => void; - filter: () => boolean; - label: string; - commandRef: React.RefObject; - // Ids - listId: string; - labelId: string; - inputId: string; -}; -type State = { - search: string; - value: string; - filtered: { - count: number; - items: Map; - groups: Set; - }; -}; -type Store = { - subscribe: (callback: () => void) => () => void; - snapshot: () => State; - setState: ( - key: K, - value: State[K], - opts?: any - ) => void; - emit: () => void; -}; -type Group = { - id: string; - forceMount?: boolean; -}; - -const LIST_SELECTOR = `[cmdk-list-sizer=""]`; -const GROUP_SELECTOR = `[cmdk-group=""]`; -const GROUP_ITEMS_SELECTOR = `[cmdk-group-items=""]`; -const GROUP_HEADING_SELECTOR = `[cmdk-group-heading=""]`; -const ITEM_SELECTOR = `[cmdk-item=""]`; -const VALID_ITEM_SELECTOR = `${ITEM_SELECTOR}:not([aria-disabled="true"])`; -const SELECT_EVENT = `cmdk-item-select`; -const VALUE_ATTR = `data-value`; -const defaultFilter: CommandProps['filter'] = (value, search) => - commandScore(value, search); - -// @ts-ignore -const CommandContext = React.createContext(undefined); -const useCommand = () => React.useContext(CommandContext); -// @ts-ignore -const StoreContext = React.createContext(undefined); -const useStore = () => React.useContext(StoreContext); -// @ts-ignore -const GroupContext = React.createContext(undefined); - -const Command = React.forwardRef( - (props, forwardedRef) => { - const ref = React.useRef(null); - const state = useLazyRef(() => ({ - /** Value of the search query. */ - search: '', - /** Currently selected item value. */ - value: props.value ?? props.defaultValue?.toLowerCase() ?? '', - filtered: { - /** The count of all visible items. */ - count: 0, - /** Map from visible item id to its search score. */ - items: new Map(), - /** Set of groups with at least one visible item. */ - groups: new Set(), - }, - })); - const allItems = useLazyRef>(() => new Set()); // [...itemIds] - const allGroups = useLazyRef>>(() => new Map()); // groupId → [...itemIds] - const ids = useLazyRef>(() => new Map()); // id → value - const listeners = useLazyRef void>>(() => new Set()); // [...rerenders] - const propsRef = useAsRef(props); - const { - label, - children, - value, - onValueChange, - filter, - shouldFilter, - vimBindings = true, - ...etc - } = props; - - const listId = React.useId(); - const labelId = React.useId(); - const inputId = React.useId(); - - const schedule = useScheduleLayoutEffect(); - - /** Controlled mode `value` handling. */ - useLayoutEffect(() => { - if (value !== undefined) { - const v = value.trim().toLowerCase(); - state.current.value = v; - schedule(6, scrollSelectedIntoView); - store.emit(); - } - }, [value]); - - const store: Store = React.useMemo(() => { - return { - subscribe: cb => { - listeners.current.add(cb); - return () => listeners.current.delete(cb); - }, - snapshot: () => { - return state.current; - }, - setState: (key, value, opts) => { - if (Object.is(state.current[key], value)) return; - state.current[key] = value; - - if (key === 'search') { - // Filter synchronously before emitting back to children - filterItems(); - sort(); - schedule(1, selectFirstItem); - } else if (key === 'value') { - if (propsRef.current?.value !== undefined) { - // If controlled, just call the callback instead of updating state internally - const newValue = (value ?? '') as string; - propsRef.current.onValueChange?.(newValue); - return; - // opts is a boolean referring to whether it should NOT be scrolled into view - } else if (!opts) { - // Scroll the selected item into view - schedule(5, scrollSelectedIntoView); - } - } - - // Notify subscribers that state has changed - store.emit(); - }, - emit: () => { - listeners.current.forEach(l => l()); - }, - }; - }, []); - - const context: Context = React.useMemo( - () => ({ - // Keep id → value mapping up-to-date - value: (id, value) => { - if (value !== ids.current.get(id)) { - ids.current.set(id, value); - state.current.filtered.items.set(id, score(value)); - schedule(2, () => { - sort(); - store.emit(); - }); - } - }, - // Track item lifecycle (mount, unmount) - item: (id, groupId) => { - allItems.current.add(id); - - // Track this item within the group - if (groupId) { - if (!allGroups.current.has(groupId)) { - allGroups.current.set(groupId, new Set([id])); - } else { - allGroups.current.get(groupId).add(id); - } - } - - // Batch this, multiple items can mount in one pass - // and we should not be filtering/sorting/emitting each time - schedule(3, () => { - filterItems(); - sort(); - - // Could be initial mount, select the first item if none already selected - if (!state.current.value) { - selectFirstItem(); - } - - store.emit(); - }); - - return () => { - ids.current.delete(id); - allItems.current.delete(id); - state.current.filtered.items.delete(id); - const selectedItem = getSelectedItem(); - - // Batch this, multiple items could be removed in one pass - schedule(4, () => { - filterItems(); - - // The item removed have been the selected one, - // so selection should be moved to the first - if (selectedItem?.getAttribute('id') === id) selectFirstItem(); - - store.emit(); - }); - }; - }, - // Track group lifecycle (mount, unmount) - group: id => { - if (!allGroups.current.has(id)) { - allGroups.current.set(id, new Set()); - } - - return () => { - ids.current.delete(id); - allGroups.current.delete(id); - }; - }, - filter: () => { - return propsRef.current.shouldFilter; - }, - label: label || props['aria-label'], - commandRef: ref, - listId, - inputId, - labelId, - }), - [] - ); - - function score(value: string) { - const filter = propsRef.current?.filter ?? defaultFilter; - return value ? filter(value, state.current.search) : 0; - } - - /** Sorts items by score, and groups by highest item score. */ - function sort() { - if ( - !ref.current || - !state.current.search || - // Explicitly false, because true | undefined is the default - propsRef.current.shouldFilter === false - ) { - return; - } - - const scores = state.current.filtered.items; - - // Sort the groups - const groups: [string, number][] = []; - state.current.filtered.groups.forEach(value => { - const items = allGroups.current.get(value); - - // Get the maximum score of the group's items - let max = 0; - items.forEach(item => { - const score = scores.get(item); - max = Math.max(score, max); - }); - - groups.push([value, max]); - }); - - // Sort items within groups to bottom - // Sort items outside of groups - // Sort groups to bottom (pushes all non-grouped items to the top) - const list = ref.current.querySelector(LIST_SELECTOR); - - // Sort the items - getValidItems() - .sort((a, b) => { - const valueA = a.getAttribute('id'); - const valueB = b.getAttribute('id'); - return (scores.get(valueB) ?? 0) - (scores.get(valueA) ?? 0); - }) - .forEach(item => { - const group = item.closest(GROUP_ITEMS_SELECTOR); - - if (group) { - group.appendChild( - item.parentElement === group - ? item - : item.closest(`${GROUP_ITEMS_SELECTOR} > *`) - ); - } else { - list.appendChild( - item.parentElement === list - ? item - : item.closest(`${GROUP_ITEMS_SELECTOR} > *`) - ); - } - }); - - groups - .sort((a, b) => b[1] - a[1]) - .forEach(group => { - const element = ref.current.querySelector( - `${GROUP_SELECTOR}[${VALUE_ATTR}="${group[0]}"]` - ); - element?.parentElement.appendChild(element); - }); - } - - function selectFirstItem() { - const item = getValidItems().find(item => !item.ariaDisabled); - const value = item?.getAttribute(VALUE_ATTR); - store.setState('value', value || undefined); - } - - /** Filters the current items. */ - function filterItems() { - if ( - !state.current.search || - // Explicitly false, because true | undefined is the default - propsRef.current.shouldFilter === false - ) { - state.current.filtered.count = allItems.current.size; - // Do nothing, each item will know to show itself because search is empty - return; - } - - // Reset the groups - state.current.filtered.groups = new Set(); - let itemCount = 0; - - // Check which items should be included - for (const id of allItems.current) { - const value = ids.current.get(id); - const rank = score(value); - state.current.filtered.items.set(id, rank); - if (rank > 0) itemCount++; - } - - // Check which groups have at least 1 item shown - for (const [groupId, group] of allGroups.current) { - for (const itemId of group) { - if (state.current.filtered.items.get(itemId) > 0) { - state.current.filtered.groups.add(groupId); - break; - } - } - } - - state.current.filtered.count = itemCount; - } - - function scrollSelectedIntoView() { - const item = getSelectedItem(); - - if (item) { - if (item.parentElement?.firstChild === item) { - // First item in Group, ensure heading is in view - item - .closest(GROUP_SELECTOR) - ?.querySelector(GROUP_HEADING_SELECTOR) - ?.scrollIntoView({ block: 'nearest' }); - } - - // Ensure the item is always in view - item.scrollIntoView({ block: 'nearest' }); - } - } - - /** Getters */ - - function getSelectedItem() { - return ref.current?.querySelector( - `${ITEM_SELECTOR}[aria-selected="true"]` - ); - } - - function getValidItems() { - return Array.from(ref.current.querySelectorAll(VALID_ITEM_SELECTOR)); - } - - /** Setters */ - - function updateSelectedToIndex(index: number) { - const items = getValidItems(); - const item = items[index]; - if (item) store.setState('value', item.getAttribute(VALUE_ATTR)); - } - - function updateSelectedByChange(change: 1 | -1) { - const selected = getSelectedItem(); - const items = getValidItems(); - const index = items.findIndex(item => item === selected); - - // Get item at this index - let newSelected = items[index + change]; - - if (propsRef.current?.loop) { - newSelected = - index + change < 0 - ? items[items.length - 1] - : index + change === items.length - ? items[0] - : items[index + change]; - } - - if (newSelected) - store.setState('value', newSelected.getAttribute(VALUE_ATTR)); - } - - function updateSelectedToGroup(change: 1 | -1) { - const selected = getSelectedItem(); - let group = selected?.closest(GROUP_SELECTOR); - let item: HTMLElement; - - while (group && !item) { - group = - change > 0 - ? findNextSibling(group, GROUP_SELECTOR) - : findPreviousSibling(group, GROUP_SELECTOR); - item = group?.querySelector(VALID_ITEM_SELECTOR); - } - - if (item) { - store.setState('value', item.getAttribute(VALUE_ATTR)); - } else { - updateSelectedByChange(change); - } - } - - const last = () => updateSelectedToIndex(getValidItems().length - 1); - - const next = (e: React.KeyboardEvent) => { - e.preventDefault(); - - if (e.metaKey) { - // Last item - last(); - } else if (e.altKey) { - // Next group - updateSelectedToGroup(1); - } else { - // Next item - updateSelectedByChange(1); - } - }; - - const prev = (e: React.KeyboardEvent) => { - e.preventDefault(); - - if (e.metaKey) { - // First item - updateSelectedToIndex(0); - } else if (e.altKey) { - // Previous group - updateSelectedToGroup(-1); - } else { - // Previous item - updateSelectedByChange(-1); - } - }; - - return ( -
{ - etc.onKeyDown?.(e); - - if (!e.defaultPrevented) { - switch (e.key) { - case 'n': - case 'j': { - // vim keybind down - if (vimBindings && e.ctrlKey) { - next(e); - } - break; - } - case 'ArrowDown': { - next(e); - break; - } - case 'p': - case 'k': { - // vim keybind up - if (vimBindings && e.ctrlKey) { - prev(e); - } - break; - } - case 'ArrowUp': { - prev(e); - break; - } - case 'Home': { - // First item - e.preventDefault(); - updateSelectedToIndex(0); - break; - } - case 'End': { - // Last item - e.preventDefault(); - last(); - break; - } - case 'Enter': { - // Check if IME composition is finished before triggering onSelect - // This prevents unwanted triggering while user is still inputting text with IME - if (!e.nativeEvent.isComposing) { - // Trigger item onSelect - e.preventDefault(); - const item = getSelectedItem(); - if (item) { - const event = new Event(SELECT_EVENT); - item.dispatchEvent(event); - } - } - } - } - } - }} - > - - - - {children} - - -
- ); - } -); - -/** - * Command menu item. Becomes active on pointer enter or through keyboard navigation. - * Preferably pass a `value`, otherwise the value will be inferred from `children` or - * the rendered item's `textContent`. - */ -const Item = React.forwardRef( - (props, forwardedRef) => { - const id = React.useId(); - const ref = React.useRef(null); - const groupContext = React.useContext(GroupContext); - const context = useCommand(); - const propsRef = useAsRef(props); - const forceMount = propsRef.current?.forceMount ?? groupContext?.forceMount; - - useLayoutEffect(() => { - return context.item(id, groupContext?.id); - }, []); - - const value = useValue(id, ref, [props.value, props.children, ref]); - - const store = useStore(); - const selected = useCmdk( - state => state.value && state.value === value.current - ); - const render = useCmdk(state => - forceMount - ? true - : context.filter() === false - ? true - : !state.search - ? true - : state.filtered.items.get(id) > 0 - ); - - React.useEffect(() => { - const element = ref.current; - if (!element || props.disabled) return; - element.addEventListener(SELECT_EVENT, onSelect); - return () => element.removeEventListener(SELECT_EVENT, onSelect); - }, [render, props.onSelect, props.disabled]); - - function onSelect() { - select(); - propsRef.current.onSelect?.(value.current); - } - - function select() { - store.setState('value', value.current, true); - } - - if (!render) return null; - - const { disabled, value: _, onSelect: __, ...etc } = props; - - return ( -
- {props.children} -
- ); - } -); - -/** - * Group command menu items together with a heading. - * Grouped items are always shown together. - */ -const Group = React.forwardRef( - (props, forwardedRef) => { - const { heading, children, forceMount, ...etc } = props; - const id = React.useId(); - const ref = React.useRef(null); - const headingRef = React.useRef(null); - const headingId = React.useId(); - const context = useCommand(); - const render = useCmdk(state => - forceMount - ? true - : context.filter() === false - ? true - : !state.search - ? true - : state.filtered.groups.has(id) - ); - - useLayoutEffect(() => { - return context.group(id); - }, []); - - useValue(id, ref, [props.value, props.heading, headingRef]); - - const contextValue = React.useMemo( - () => ({ id, forceMount }), - [forceMount] - ); - const inner = ( - - {children} - - ); - - return ( - - ); - } -); - -/** - * A visual and semantic separator between items or groups. - * Visible when the search query is empty or `alwaysRender` is true, hidden otherwise. - */ -const Separator = React.forwardRef( - (props, forwardedRef) => { - const { alwaysRender, ...etc } = props; - const ref = React.useRef(null); - const render = useCmdk(state => !state.search); - - if (!alwaysRender && !render) return null; - return ( -
- ); - } -); - -/** - * Command menu input. - * All props are forwarded to the underyling `input` element. - */ -const Input = React.forwardRef( - (props, forwardedRef) => { - const { onValueChange, ...etc } = props; - const isControlled = props.value != null; - const store = useStore(); - const search = useCmdk(state => state.search); - const value = useCmdk(state => state.value); - const context = useCommand(); - - const selectedItemId = React.useMemo(() => { - const item = context.commandRef.current?.querySelector( - `${ITEM_SELECTOR}[${VALUE_ATTR}="${value}"]` - ); - return item?.getAttribute('id'); - }, [value, context.commandRef]); - - React.useEffect(() => { - if (props.value != null) { - store.setState('search', props.value); - } - }, [props.value]); - - return ( - { - if ( - e.key === 'Escape' || - e.key === 'k' || - e.key.startsWith('Arrow') || - e.key === 'Enter' - ) { - return; - } - e.stopPropagation(); - }} - autoComplete="off" - autoCorrect="off" - spellCheck={false} - aria-autocomplete="list" - role="combobox" - aria-expanded={true} - aria-controls={context.listId} - aria-labelledby={context.labelId} - aria-activedescendant={selectedItemId} - id={context.inputId} - type="text" - value={isControlled ? props.value : search} - onChange={e => { - if (!isControlled) { - store.setState('search', e.target.value); - } - - onValueChange?.(e.target.value); - }} - /> - ); - } -); - -/** - * Contains `Item`, `Group`, and `Separator`. - * Use the `--cmdk-list-height` CSS variable to animate height based on the number of results. - */ -const List = React.forwardRef( - (props, forwardedRef) => { - const { children, ...etc } = props; - const ref = React.useRef(null); - const height = React.useRef(null); - const context = useCommand(); - - React.useEffect(() => { - if (height.current && ref.current) { - const el = height.current; - const wrapper = ref.current; - let animationFrame; - const observer = new ResizeObserver(() => { - animationFrame = requestAnimationFrame(() => { - const height = el.offsetHeight; - wrapper.style.setProperty( - `--cmdk-list-height`, - height.toFixed(1) + 'px' - ); - }); - }); - observer.observe(el); - return () => { - cancelAnimationFrame(animationFrame); - observer.unobserve(el); - }; - } - }, []); - - return ( -
-
- {children} -
-
- ); - } -); - -/** - * Renders the command menu in a Radix Dialog. - */ -const Dialog = React.forwardRef( - (props, forwardedRef) => { - const { - open, - onOpenChange, - overlayClassName, - contentClassName, - container, - ...etc - } = props; - return ( - - - - - - - - - ); - } -); - -/** - * Automatically renders when there are no results for the search query. - */ -const Empty = React.forwardRef( - (props, forwardedRef) => { - const isFirstRender = React.useRef(true); - const render = useCmdk(state => state.filtered.count === 0); - - React.useEffect(() => { - isFirstRender.current = false; - }, []); - - if (isFirstRender.current || !render) return null; - return ( -
- ); - } -); - -/** - * You should conditionally render this with `progress` while loading asynchronous items. - */ -const Loading = React.forwardRef( - (props, forwardedRef) => { - const { progress, children, ...etc } = props; - - return ( -
-
{children}
-
- ); - } -); - -const pkg = Object.assign(Command, { - List, - Item, - Input, - Group, - Separator, - Dialog, - Empty, - Loading, -}); - -export { useCmdk as useCommandState }; -export { pkg as Command }; - -export { Command as CommandRoot }; -export { List as CommandList }; -export { Item as CommandItem }; -export { Input as CommandInput }; -export { Group as CommandGroup }; -export { Separator as CommandSeparator }; -export { Dialog as CommandDialog }; -export { Empty as CommandEmpty }; -export { Loading as CommandLoading }; -export { commandScore }; - -/** - * - * - * Helpers - * - * - */ - -function findNextSibling(el: Element, selector: string) { - let sibling = el.nextElementSibling; - - while (sibling) { - if (sibling.matches(selector)) return sibling; - sibling = sibling.nextElementSibling; - } -} - -function findPreviousSibling(el: Element, selector: string) { - let sibling = el.previousElementSibling; - - while (sibling) { - if (sibling.matches(selector)) return sibling; - sibling = sibling.previousElementSibling; - } -} - -function useAsRef(data: T) { - const ref = React.useRef(data); - - useLayoutEffect(() => { - ref.current = data; - }); - - return ref; -} - -const useLayoutEffect = - typeof window === 'undefined' ? React.useEffect : React.useLayoutEffect; - -function useLazyRef(fn: () => T) { - const ref = React.useRef(); - - if (ref.current === undefined) { - ref.current = fn(); - } - - return ref as React.MutableRefObject; -} - -// ESM is still a nightmare with Next.js so I'm just gonna copy the package code in -// https://github.com/gregberge/react-merge-refs -// Copyright (c) 2020 Greg Bergé -function mergeRefs( - refs: Array | React.LegacyRef> -): React.RefCallback { - return value => { - refs.forEach(ref => { - if (typeof ref === 'function') { - ref(value); - } else if (ref != null) { - (ref as React.MutableRefObject).current = value; - } - }); - }; -} - -/** Run a selector against the store state. */ -function useCmdk(selector: (state: State) => T) { - const store = useStore(); - const cb = () => selector(store.snapshot()); - return React.useSyncExternalStore(store.subscribe, cb, cb); -} - -function useValue( - id: string, - ref: React.RefObject, - deps: (string | React.ReactNode | React.RefObject)[] -) { - const valueRef = React.useRef(); - const context = useCommand(); - - useLayoutEffect(() => { - const value = (() => { - for (const part of deps) { - if (typeof part === 'string') { - return part.trim().toLowerCase(); - } - - if (typeof part === 'object' && 'current' in part) { - if (part.current) { - return part.current.textContent?.trim().toLowerCase(); - } - return valueRef.current; - } - } - })(); - - context.value(id, value); - ref.current?.setAttribute(VALUE_ATTR, value); - valueRef.current = value; - }); - - return valueRef; -} - -/** Imperatively run a function on the next layout effect cycle. */ -const useScheduleLayoutEffect = () => { - const [s, ss] = React.useState(); - const fns = useLazyRef(() => new Map void>()); - - useLayoutEffect(() => { - fns.current.forEach(f => f()); - fns.current = new Map(); - }, [s]); - - return (id: string | number, cb: () => void) => { - fns.current.set(id, cb); - ss({}); - }; -}; - -const srOnlyStyles = { - position: 'absolute', - width: '1px', - height: '1px', - padding: '0', - margin: '-1px', - overflow: 'hidden', - clip: 'rect(0, 0, 0, 0)', - whiteSpace: 'nowrap', - borderWidth: '0', -} as const; diff --git a/packages/common/cmdk/tsconfig.json b/packages/common/cmdk/tsconfig.json deleted file mode 100644 index 4bbd8d0b7..000000000 --- a/packages/common/cmdk/tsconfig.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "extends": "../../../tsconfig.json", - "include": ["./src"], - "compilerOptions": { - "composite": true, - "noEmit": false, - "outDir": "lib" - } -} diff --git a/packages/frontend/core/package.json b/packages/frontend/core/package.json index 5056d8176..77e22c8d8 100644 --- a/packages/frontend/core/package.json +++ b/packages/frontend/core/package.json @@ -17,7 +17,6 @@ }, "dependencies": { "@affine-test/fixtures": "workspace:*", - "@affine/cmdk": "workspace:*", "@affine/component": "workspace:*", "@affine/debug": "workspace:*", "@affine/electron-api": "workspace:*", @@ -55,6 +54,7 @@ "async-call-rpc": "^6.3.1", "bytes": "^3.1.2", "clsx": "^2.0.0", + "cmdk": "patch:cmdk@npm%3A0.2.0#~/.yarn/patches/cmdk-npm-0.2.0-302237a911.patch", "css-spring": "^4.1.0", "cssnano": "^6.0.1", "dayjs": "^1.11.10", diff --git a/packages/frontend/core/src/components/pure/cmdk/data.tsx b/packages/frontend/core/src/components/pure/cmdk/data.tsx index d37d08aeb..0bec9f4ac 100644 --- a/packages/frontend/core/src/components/pure/cmdk/data.tsx +++ b/packages/frontend/core/src/components/pure/cmdk/data.tsx @@ -1,4 +1,3 @@ -import { commandScore } from '@affine/cmdk'; import { useCollectionManager } from '@affine/component/page-list'; import { useBlockSuitePageMeta, @@ -19,6 +18,7 @@ import { type CommandCategory, PreconditionStrategy, } from '@toeverything/infra/command'; +import { commandScore } from 'cmdk'; import { atom, useAtomValue } from 'jotai'; import { groupBy } from 'lodash-es'; import { useCallback, useEffect, useMemo, useState } from 'react'; diff --git a/packages/frontend/core/src/components/pure/cmdk/main.tsx b/packages/frontend/core/src/components/pure/cmdk/main.tsx index ced65792e..4a28ca08d 100644 --- a/packages/frontend/core/src/components/pure/cmdk/main.tsx +++ b/packages/frontend/core/src/components/pure/cmdk/main.tsx @@ -1,11 +1,10 @@ -import { Command } from '@affine/cmdk'; -import { useCommandState } from '@affine/cmdk'; import { formatDate } from '@affine/component/page-list'; import { useAsyncCallback } from '@affine/core/hooks/affine-async-hooks'; import { useAFFiNEI18N } from '@affine/i18n/hooks'; import type { PageMeta } from '@blocksuite/store'; import type { CommandCategory } from '@toeverything/infra/command'; import clsx from 'clsx'; +import { Command, useCommandState } from 'cmdk'; import { useAtom, useAtomValue } from 'jotai'; import { Suspense, @@ -225,17 +224,6 @@ export const CMDKContainer = ({ className={clsx(className, styles.panelContainer)} value={value} onValueChange={setValue} - // Handle KeyboardEvent conflicts with blocksuite - onKeyDown={(e: React.KeyboardEvent) => { - if ( - e.key === 'ArrowDown' || - e.key === 'ArrowUp' || - e.key === 'ArrowLeft' || - e.key === 'ArrowRight' - ) { - e.stopPropagation(); - } - }} > {/* todo: add page context here */} {isInEditor ? ( diff --git a/packages/frontend/core/src/components/pure/cmdk/not-found.tsx b/packages/frontend/core/src/components/pure/cmdk/not-found.tsx index d1c2c8007..fd9631533 100644 --- a/packages/frontend/core/src/components/pure/cmdk/not-found.tsx +++ b/packages/frontend/core/src/components/pure/cmdk/not-found.tsx @@ -1,5 +1,5 @@ -import { useCommandState } from '@affine/cmdk'; import { SearchIcon } from '@blocksuite/icons'; +import { useCommandState } from 'cmdk'; import { useAtomValue } from 'jotai'; import { cmdkQueryAtom } from './data'; diff --git a/tsconfig.json b/tsconfig.json index 0a9b0cee9..120becff9 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -107,9 +107,6 @@ "path": "./packages/frontend/workspace-impl" }, // Common - { - "path": "./packages/common/cmdk" - }, { "path": "./packages/common/debug" }, diff --git a/yarn.lock b/yarn.lock index 5c7e013ba..d4ba009b0 100644 --- a/yarn.lock +++ b/yarn.lock @@ -187,16 +187,6 @@ __metadata: languageName: unknown linkType: soft -"@affine/cmdk@workspace:*, @affine/cmdk@workspace:packages/common/cmdk": - version: 0.0.0-use.local - resolution: "@affine/cmdk@workspace:packages/common/cmdk" - dependencies: - "@radix-ui/react-dialog": "npm:^1.0.5" - react: "npm:18.2.0" - react-dom: "npm:18.2.0" - languageName: unknown - linkType: soft - "@affine/commitlint-config@workspace:tools/commitlint": version: 0.0.0-use.local resolution: "@affine/commitlint-config@workspace:tools/commitlint" @@ -308,7 +298,6 @@ __metadata: resolution: "@affine/core@workspace:packages/frontend/core" dependencies: "@affine-test/fixtures": "workspace:*" - "@affine/cmdk": "workspace:*" "@affine/component": "workspace:*" "@affine/debug": "workspace:*" "@affine/electron-api": "workspace:*" @@ -359,6 +348,7 @@ __metadata: async-call-rpc: "npm:^6.3.1" bytes: "npm:^3.1.2" clsx: "npm:^2.0.0" + cmdk: "patch:cmdk@npm%3A0.2.0#~/.yarn/patches/cmdk-npm-0.2.0-302237a911.patch" copy-webpack-plugin: "npm:^11.0.0" css-loader: "npm:^6.8.1" css-spring: "npm:^4.1.0" @@ -9422,7 +9412,7 @@ __metadata: languageName: node linkType: hard -"@radix-ui/react-dialog@npm:^1.0.4, @radix-ui/react-dialog@npm:^1.0.5": +"@radix-ui/react-dialog@npm:@radix-ui/react-dialog@latest": version: 1.0.5 resolution: "@radix-ui/react-dialog@npm:1.0.5" dependencies: @@ -17092,6 +17082,32 @@ __metadata: languageName: node linkType: hard +"cmdk@npm:0.2.0": + version: 0.2.0 + resolution: "cmdk@npm:0.2.0" + dependencies: + "@radix-ui/react-dialog": "npm:1.0.0" + command-score: "npm:0.1.2" + peerDependencies: + react: ^18.0.0 + react-dom: ^18.0.0 + checksum: e178e3d3276e0b5fd158c9c99716c0405427871f48fa97c15c4be2de24be4a478cf0205ffa04244628dbe103dd8573a1bd1aa68f04f8b60633d4ffc04e5eee62 + languageName: node + linkType: hard + +"cmdk@patch:cmdk@npm%3A0.2.0#~/.yarn/patches/cmdk-npm-0.2.0-302237a911.patch": + version: 0.2.0 + resolution: "cmdk@patch:cmdk@npm%3A0.2.0#~/.yarn/patches/cmdk-npm-0.2.0-302237a911.patch::version=0.2.0&hash=640d85" + dependencies: + "@radix-ui/react-dialog": "npm:1.0.0" + command-score: "npm:0.1.2" + peerDependencies: + react: ^18.0.0 + react-dom: ^18.0.0 + checksum: 758bacb7761a72c6fa03a1b20ea2514ff14ad6b3d00cc1d8bc6781a216b0a719f991eacded9f923ddcf1b58b8efb304209b268c17bd7d6f5671aa3352934b754 + languageName: node + linkType: hard + "co@npm:^4.6.0": version: 4.6.0 resolution: "co@npm:4.6.0" @@ -17237,6 +17253,13 @@ __metadata: languageName: node linkType: hard +"command-score@npm:0.1.2": + version: 0.1.2 + resolution: "command-score@npm:0.1.2" + checksum: 84f6a69e6b215d3fc8c9ed402d109587f511e4cc84cd5da10a7857b50fb1638953e32dcce8ed8f3549b0bfe499e82601fb7fb6891c9c71b48933d4bb8bac238a + languageName: node + linkType: hard + "commander@npm:11.0.0": version: 11.0.0 resolution: "commander@npm:11.0.0"