'use strict'; var obsidian = require('obsidian'); function __awaiter(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value);});}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value));}catch(e){reject(e);}}function rejected(value){try{step(generator["throw"](value));}catch(e){reject(e);}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected);}step((generator=generator.apply(thisArg,_arguments||[])).next());});}function __generator(thisArg,body){var _={label:0,sent:function(){if(t[0]&1)throw t[1];return t[1];},trys:[],ops:[]},f,y,t,g;return g={next:verb(0),"throw":verb(1),"return":verb(2)},typeof Symbol==="function"&&(g[Symbol.iterator]=function(){return this;}),g;function verb(n){return function(v){return step([n,v]);};}function step(op){if(f)throw new TypeError("Generator is already executing.");while(g&&(g=0,op[0]&&(_=0)),_)try{if(f=1,y&&(t=op[0]&2?y["return"]:op[0]?y["throw"]||((t=y["return"])&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;if(y=0,t)op=[op[0]&2,t.value];switch(op[0]){case 0:case 1:t=op;break;case 4:_.label++;return {value:op[1],done:false};case 5:_.label++;y=op[1];op=[0];continue;case 7:op=_.ops.pop();_.trys.pop();continue;default:if(!(t=_.trys,t=t.length>0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue;}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]0)&&!(r=i.next()).done)ar.push(r.value);}catch(error){e={error:error};}finally{try{if(r&&!r.done&&(m=i["return"]))m.call(i);}finally{if(e)throw e.error;}}return ar;}function __spreadArray(to,from,pack){if(pack||arguments.length===2)for(var i=0,l=from.length,ar;i>>1,e=a[d];if(0>>1;dg(C,c))ng(x,C)?(a[d]=x,a[n]=c,d=n):(a[d]=C,a[m]=c,d=m);else if(ng(x,c))a[d]=x,a[n]=c,d=n;else break a;}}return b;}function g(a,b){var c=a.sortIndex-b.sortIndex;return 0!==c?c:a.id-b.id;}if("object"===typeof performance&&"function"===typeof performance.now){var l=performance;exports.unstable_now=function(){return l.now();};}else {var p=Date,q=p.now();exports.unstable_now=function(){return p.now()-q;};}var r=[],t=[],u=1,v=null,y=3,z=!1,A=!1,B=!1,D="function"===typeof setTimeout?setTimeout:null,E="function"===typeof clearTimeout?clearTimeout:null,F="undefined"!==typeof setImmediate?setImmediate:null;"undefined"!==typeof navigator&&void 0!==navigator.scheduling&&void 0!==navigator.scheduling.isInputPending&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function G(a){for(var b=h(t);null!==b;){if(null===b.callback)k(t);else if(b.startTime<=a)k(t),b.sortIndex=b.expirationTime,f(r,b);else break;b=h(t);}}function H(a){B=!1;G(a);if(!A)if(null!==h(r))A=!0,I(J);else {var b=h(t);null!==b&&K(H,b.startTime-a);}}function J(a,b){A=!1;B&&(B=!1,E(L),L=-1);z=!0;var c=y;try{G(b);for(v=h(r);null!==v&&(!(v.expirationTime>b)||a&&!M());){var d=v.callback;if("function"===typeof d){v.callback=null;y=v.priorityLevel;var e=d(v.expirationTime<=b);b=exports.unstable_now();"function"===typeof e?v.callback=e:v===h(r)&&k(r);G(b);}else k(r);v=h(r);}if(null!==v)var w=!0;else {var m=h(t);null!==m&&K(H,m.startTime-b);w=!1;}return w;}finally{v=null,y=c,z=!1;}}var N=!1,O=null,L=-1,P=5,Q=-1;function M(){return exports.unstable_now()-Qa||125d?(a.sortIndex=c,f(t,a),null===h(r)&&a===h(t)&&(B?(E(L),L=-1):B=!0,K(H,c-d))):(a.sortIndex=e,f(r,a),A||z||(A=!0,I(J)));return a;};exports.unstable_shouldYield=M;exports.unstable_wrapCallback=function(a){var b=y;return function(){var c=y;y=b;try{return a.apply(this,arguments);}finally{y=c;}};}; } (scheduler_production_min)); {scheduler.exports=scheduler_production_min;} var schedulerExports = scheduler.exports; /** * @license React * react-dom.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var aa=reactExports,ca=schedulerExports;function p$1(a){for(var b="https://reactjs.org/docs/error-decoder.html?invariant="+a,c=1;cb;}return !1;}function v(a,b,c,d,e,f,g){this.acceptsBooleans=2===b||3===b||4===b;this.attributeName=d;this.attributeNamespace=e;this.mustUseProperty=c;this.propertyName=a;this.type=b;this.sanitizeURL=f;this.removeEmptyString=g;}var z={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(a){z[a]=new v(a,0,!1,a,null,!1,!1);});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(a){var b=a[0];z[b]=new v(b,1,!1,a[1],null,!1,!1);});["contentEditable","draggable","spellCheck","value"].forEach(function(a){z[a]=new v(a,2,!1,a.toLowerCase(),null,!1,!1);});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(a){z[a]=new v(a,2,!1,a,null,!1,!1);});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(a){z[a]=new v(a,3,!1,a.toLowerCase(),null,!1,!1);});["checked","multiple","muted","selected"].forEach(function(a){z[a]=new v(a,3,!0,a,null,!1,!1);});["capture","download"].forEach(function(a){z[a]=new v(a,4,!1,a,null,!1,!1);});["cols","rows","size","span"].forEach(function(a){z[a]=new v(a,6,!1,a,null,!1,!1);});["rowSpan","start"].forEach(function(a){z[a]=new v(a,5,!1,a.toLowerCase(),null,!1,!1);});var ra=/[\-:]([a-z])/g;function sa(a){return a[1].toUpperCase();}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(a){var b=a.replace(ra,sa);z[b]=new v(b,1,!1,a,null,!1,!1);});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(a){var b=a.replace(ra,sa);z[b]=new v(b,1,!1,a,"http://www.w3.org/1999/xlink",!1,!1);});["xml:base","xml:lang","xml:space"].forEach(function(a){var b=a.replace(ra,sa);z[b]=new v(b,1,!1,a,"http://www.w3.org/XML/1998/namespace",!1,!1);});["tabIndex","crossOrigin"].forEach(function(a){z[a]=new v(a,1,!1,a.toLowerCase(),null,!1,!1);});z.xlinkHref=new v("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(a){z[a]=new v(a,1,!1,a.toLowerCase(),null,!0,!0);});function ta(a,b,c,d){var e=z.hasOwnProperty(b)?z[b]:null;if(null!==e?0!==e.type:d||!(2h||e[g]!==f[h]){var k="\n"+e[g].replace(" at new "," at ");a.displayName&&k.includes("")&&(k=k.replace("",a.displayName));return k;}while(1<=g&&0<=h);}break;}}}finally{Na=!1,Error.prepareStackTrace=c;}return (a=a?a.displayName||a.name:"")?Ma(a):"";}function Pa(a){switch(a.tag){case 5:return Ma(a.type);case 16:return Ma("Lazy");case 13:return Ma("Suspense");case 19:return Ma("SuspenseList");case 0:case 2:case 15:return a=Oa(a.type,!1),a;case 11:return a=Oa(a.type.render,!1),a;case 1:return a=Oa(a.type,!0),a;default:return "";}}function Qa(a){if(null==a)return null;if("function"===typeof a)return a.displayName||a.name||null;if("string"===typeof a)return a;switch(a){case ya:return "Fragment";case wa:return "Portal";case Aa:return "Profiler";case za:return "StrictMode";case Ea:return "Suspense";case Fa:return "SuspenseList";}if("object"===typeof a)switch(a.$$typeof){case Ca:return (a.displayName||"Context")+".Consumer";case Ba:return (a._context.displayName||"Context")+".Provider";case Da:var b=a.render;a=a.displayName;a||(a=b.displayName||b.name||"",a=""!==a?"ForwardRef("+a+")":"ForwardRef");return a;case Ga:return b=a.displayName||null,null!==b?b:Qa(a.type)||"Memo";case Ha:b=a._payload;a=a._init;try{return Qa(a(b));}catch(c){}}return null;}function Ra(a){var b=a.type;switch(a.tag){case 24:return "Cache";case 9:return (b.displayName||"Context")+".Consumer";case 10:return (b._context.displayName||"Context")+".Provider";case 18:return "DehydratedFragment";case 11:return a=b.render,a=a.displayName||a.name||"",b.displayName||(""!==a?"ForwardRef("+a+")":"ForwardRef");case 7:return "Fragment";case 5:return b;case 4:return "Portal";case 3:return "Root";case 6:return "Text";case 16:return Qa(b);case 8:return b===za?"StrictMode":"Mode";case 22:return "Offscreen";case 12:return "Profiler";case 21:return "Scope";case 13:return "Suspense";case 19:return "SuspenseList";case 25:return "TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if("function"===typeof b)return b.displayName||b.name||null;if("string"===typeof b)return b;}return null;}function Sa(a){switch(typeof a){case"boolean":case"number":case"string":case"undefined":return a;case"object":return a;default:return "";}}function Ta(a){var b=a.type;return (a=a.nodeName)&&"input"===a.toLowerCase()&&("checkbox"===b||"radio"===b);}function Ua(a){var b=Ta(a)?"checked":"value",c=Object.getOwnPropertyDescriptor(a.constructor.prototype,b),d=""+a[b];if(!a.hasOwnProperty(b)&&"undefined"!==typeof c&&"function"===typeof c.get&&"function"===typeof c.set){var e=c.get,f=c.set;Object.defineProperty(a,b,{configurable:!0,get:function(){return e.call(this);},set:function(a){d=""+a;f.call(this,a);}});Object.defineProperty(a,b,{enumerable:c.enumerable});return {getValue:function(){return d;},setValue:function(a){d=""+a;},stopTracking:function(){a._valueTracker=null;delete a[b];}};}}function Va(a){a._valueTracker||(a._valueTracker=Ua(a));}function Wa(a){if(!a)return !1;var b=a._valueTracker;if(!b)return !0;var c=b.getValue();var d="";a&&(d=Ta(a)?a.checked?"true":"false":a.value);a=d;return a!==c?(b.setValue(a),!0):!1;}function Xa(a){a=a||("undefined"!==typeof document?document:void 0);if("undefined"===typeof a)return null;try{return a.activeElement||a.body;}catch(b){return a.body;}}function Ya(a,b){var c=b.checked;return A({},b,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:null!=c?c:a._wrapperState.initialChecked});}function Za(a,b){var c=null==b.defaultValue?"":b.defaultValue,d=null!=b.checked?b.checked:b.defaultChecked;c=Sa(null!=b.value?b.value:c);a._wrapperState={initialChecked:d,initialValue:c,controlled:"checkbox"===b.type||"radio"===b.type?null!=b.checked:null!=b.value};}function ab(a,b){b=b.checked;null!=b&&ta(a,"checked",b,!1);}function bb(a,b){ab(a,b);var c=Sa(b.value),d=b.type;if(null!=c){if("number"===d){if(0===c&&""===a.value||a.value!=c)a.value=""+c;}else a.value!==""+c&&(a.value=""+c);}else if("submit"===d||"reset"===d){a.removeAttribute("value");return;}b.hasOwnProperty("value")?cb(a,b.type,c):b.hasOwnProperty("defaultValue")&&cb(a,b.type,Sa(b.defaultValue));null==b.checked&&null!=b.defaultChecked&&(a.defaultChecked=!!b.defaultChecked);}function db(a,b,c){if(b.hasOwnProperty("value")||b.hasOwnProperty("defaultValue")){var d=b.type;if(!("submit"!==d&&"reset"!==d||void 0!==b.value&&null!==b.value))return;b=""+a._wrapperState.initialValue;c||b===a.value||(a.value=b);a.defaultValue=b;}c=a.name;""!==c&&(a.name="");a.defaultChecked=!!a._wrapperState.initialChecked;""!==c&&(a.name=c);}function cb(a,b,c){if("number"!==b||Xa(a.ownerDocument)!==a)null==c?a.defaultValue=""+a._wrapperState.initialValue:a.defaultValue!==""+c&&(a.defaultValue=""+c);}var eb=Array.isArray;function fb(a,b,c,d){a=a.options;if(b){b={};for(var e=0;e"+b.valueOf().toString()+"";for(b=mb.firstChild;a.firstChild;)a.removeChild(a.firstChild);for(;b.firstChild;)a.appendChild(b.firstChild);}});function ob(a,b){if(b){var c=a.firstChild;if(c&&c===a.lastChild&&3===c.nodeType){c.nodeValue=b;return;}}a.textContent=b;}var pb={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},qb=["Webkit","ms","Moz","O"];Object.keys(pb).forEach(function(a){qb.forEach(function(b){b=b+a.charAt(0).toUpperCase()+a.substring(1);pb[b]=pb[a];});});function rb(a,b,c){return null==b||"boolean"===typeof b||""===b?"":c||"number"!==typeof b||0===b||pb.hasOwnProperty(a)&&pb[a]?(""+b).trim():b+"px";}function sb(a,b){a=a.style;for(var c in b)if(b.hasOwnProperty(c)){var d=0===c.indexOf("--"),e=rb(c,b[c],d);"float"===c&&(c="cssFloat");d?a.setProperty(c,e):a[c]=e;}}var tb=A({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function ub(a,b){if(b){if(tb[a]&&(null!=b.children||null!=b.dangerouslySetInnerHTML))throw Error(p$1(137,a));if(null!=b.dangerouslySetInnerHTML){if(null!=b.children)throw Error(p$1(60));if("object"!==typeof b.dangerouslySetInnerHTML||!("__html"in b.dangerouslySetInnerHTML))throw Error(p$1(61));}if(null!=b.style&&"object"!==typeof b.style)throw Error(p$1(62));}}function vb(a,b){if(-1===a.indexOf("-"))return "string"===typeof b.is;switch(a){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return !1;default:return !0;}}var wb=null;function xb(a){a=a.target||a.srcElement||window;a.correspondingUseElement&&(a=a.correspondingUseElement);return 3===a.nodeType?a.parentNode:a;}var yb=null,zb=null,Ab=null;function Bb(a){if(a=Cb(a)){if("function"!==typeof yb)throw Error(p$1(280));var b=a.stateNode;b&&(b=Db(b),yb(a.stateNode,a.type,b));}}function Eb(a){zb?Ab?Ab.push(a):Ab=[a]:zb=a;}function Fb(){if(zb){var a=zb,b=Ab;Ab=zb=null;Bb(a);if(b)for(a=0;a>>=0;return 0===a?32:31-(pc(a)/qc|0)|0;}var rc=64,sc=4194304;function tc(a){switch(a&-a){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return a&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return a&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return a;}}function uc(a,b){var c=a.pendingLanes;if(0===c)return 0;var d=0,e=a.suspendedLanes,f=a.pingedLanes,g=c&268435455;if(0!==g){var h=g&~e;0!==h?d=tc(h):(f&=g,0!==f&&(d=tc(f)));}else g=c&~e,0!==g?d=tc(g):0!==f&&(d=tc(f));if(0===d)return 0;if(0!==b&&b!==d&&0===(b&e)&&(e=d&-d,f=b&-b,e>=f||16===e&&0!==(f&4194240)))return b;0!==(d&4)&&(d|=c&16);b=a.entangledLanes;if(0!==b)for(a=a.entanglements,b&=d;0c;c++)b.push(a);return b;}function Ac(a,b,c){a.pendingLanes|=b;536870912!==b&&(a.suspendedLanes=0,a.pingedLanes=0);a=a.eventTimes;b=31-oc(b);a[b]=c;}function Bc(a,b){var c=a.pendingLanes&~b;a.pendingLanes=b;a.suspendedLanes=0;a.pingedLanes=0;a.expiredLanes&=b;a.mutableReadLanes&=b;a.entangledLanes&=b;b=a.entanglements;var d=a.eventTimes;for(a=a.expirationTimes;0=be),ee=String.fromCharCode(32),fe=!1;function ge(a,b){switch(a){case"keyup":return -1!==$d.indexOf(b.keyCode);case"keydown":return 229!==b.keyCode;case"keypress":case"mousedown":case"focusout":return !0;default:return !1;}}function he(a){a=a.detail;return "object"===typeof a&&"data"in a?a.data:null;}var ie=!1;function je(a,b){switch(a){case"compositionend":return he(b);case"keypress":if(32!==b.which)return null;fe=!0;return ee;case"textInput":return a=b.data,a===ee&&fe?null:a;default:return null;}}function ke(a,b){if(ie)return "compositionend"===a||!ae&&ge(a,b)?(a=nd(),md=ld=kd=null,ie=!1,a):null;switch(a){case"paste":return null;case"keypress":if(!(b.ctrlKey||b.altKey||b.metaKey)||b.ctrlKey&&b.altKey){if(b.char&&1=b)return {node:c,offset:b-a};a=d;}a:{for(;c;){if(c.nextSibling){c=c.nextSibling;break a;}c=c.parentNode;}c=void 0;}c=Je(c);}}function Le(a,b){return a&&b?a===b?!0:a&&3===a.nodeType?!1:b&&3===b.nodeType?Le(a,b.parentNode):"contains"in a?a.contains(b):a.compareDocumentPosition?!!(a.compareDocumentPosition(b)&16):!1:!1;}function Me(){for(var a=window,b=Xa();b instanceof a.HTMLIFrameElement;){try{var c="string"===typeof b.contentWindow.location.href;}catch(d){c=!1;}if(c)a=b.contentWindow;else break;b=Xa(a.document);}return b;}function Ne(a){var b=a&&a.nodeName&&a.nodeName.toLowerCase();return b&&("input"===b&&("text"===a.type||"search"===a.type||"tel"===a.type||"url"===a.type||"password"===a.type)||"textarea"===b||"true"===a.contentEditable);}function Oe(a){var b=Me(),c=a.focusedElem,d=a.selectionRange;if(b!==c&&c&&c.ownerDocument&&Le(c.ownerDocument.documentElement,c)){if(null!==d&&Ne(c))if(b=d.start,a=d.end,void 0===a&&(a=b),"selectionStart"in c)c.selectionStart=b,c.selectionEnd=Math.min(a,c.value.length);else if(a=(b=c.ownerDocument||document)&&b.defaultView||window,a.getSelection){a=a.getSelection();var e=c.textContent.length,f=Math.min(d.start,e);d=void 0===d.end?f:Math.min(d.end,e);!a.extend&&f>d&&(e=d,d=f,f=e);e=Ke(c,f);var g=Ke(c,d);e&&g&&(1!==a.rangeCount||a.anchorNode!==e.node||a.anchorOffset!==e.offset||a.focusNode!==g.node||a.focusOffset!==g.offset)&&(b=b.createRange(),b.setStart(e.node,e.offset),a.removeAllRanges(),f>d?(a.addRange(b),a.extend(g.node,g.offset)):(b.setEnd(g.node,g.offset),a.addRange(b)));}b=[];for(a=c;a=a.parentNode;)1===a.nodeType&&b.push({element:a,left:a.scrollLeft,top:a.scrollTop});"function"===typeof c.focus&&c.focus();for(c=0;c=document.documentMode,Qe=null,Re=null,Se=null,Te=!1;function Ue(a,b,c){var d=c.window===c?c.document:9===c.nodeType?c:c.ownerDocument;Te||null==Qe||Qe!==Xa(d)||(d=Qe,"selectionStart"in d&&Ne(d)?d={start:d.selectionStart,end:d.selectionEnd}:(d=(d.ownerDocument&&d.ownerDocument.defaultView||window).getSelection(),d={anchorNode:d.anchorNode,anchorOffset:d.anchorOffset,focusNode:d.focusNode,focusOffset:d.focusOffset}),Se&&Ie(Se,d)||(Se=d,d=oe(Re,"onSelect"),0Tf||(a.current=Sf[Tf],Sf[Tf]=null,Tf--);}function G(a,b){Tf++;Sf[Tf]=a.current;a.current=b;}var Vf={},H=Uf(Vf),Wf=Uf(!1),Xf=Vf;function Yf(a,b){var c=a.type.contextTypes;if(!c)return Vf;var d=a.stateNode;if(d&&d.__reactInternalMemoizedUnmaskedChildContext===b)return d.__reactInternalMemoizedMaskedChildContext;var e={},f;for(f in c)e[f]=b[f];d&&(a=a.stateNode,a.__reactInternalMemoizedUnmaskedChildContext=b,a.__reactInternalMemoizedMaskedChildContext=e);return e;}function Zf(a){a=a.childContextTypes;return null!==a&&void 0!==a;}function $f(){E(Wf);E(H);}function ag(a,b,c){if(H.current!==Vf)throw Error(p$1(168));G(H,b);G(Wf,c);}function bg(a,b,c){var d=a.stateNode;b=b.childContextTypes;if("function"!==typeof d.getChildContext)return c;d=d.getChildContext();for(var e in d)if(!(e in b))throw Error(p$1(108,Ra(a)||"Unknown",e));return A({},c,d);}function cg(a){a=(a=a.stateNode)&&a.__reactInternalMemoizedMergedChildContext||Vf;Xf=H.current;G(H,a);G(Wf,Wf.current);return !0;}function dg(a,b,c){var d=a.stateNode;if(!d)throw Error(p$1(169));c?(a=bg(a,b,Xf),d.__reactInternalMemoizedMergedChildContext=a,E(Wf),E(H),G(H,a)):E(Wf);G(Wf,c);}var eg=null,fg=!1,gg=!1;function hg(a){null===eg?eg=[a]:eg.push(a);}function ig(a){fg=!0;hg(a);}function jg(){if(!gg&&null!==eg){gg=!0;var a=0,b=C;try{var c=eg;for(C=1;a>=g;e-=g;rg=1<<32-oc(b)+e|c<w?(x=u,u=null):x=u.sibling;var n=r(e,u,h[w],k);if(null===n){null===u&&(u=x);break;}a&&u&&null===n.alternate&&b(e,u);g=f(n,g,w);null===m?l=n:m.sibling=n;m=n;u=x;}if(w===h.length)return c(e,u),I&&tg(e,w),l;if(null===u){for(;ww?(x=m,m=null):x=m.sibling;var t=r(e,m,n.value,k);if(null===t){null===m&&(m=x);break;}a&&m&&null===t.alternate&&b(e,m);g=f(t,g,w);null===u?l=t:u.sibling=t;u=t;m=x;}if(n.done)return c(e,m),I&&tg(e,w),l;if(null===m){for(;!n.done;w++,n=h.next())n=q(e,n.value,k),null!==n&&(g=f(n,g,w),null===u?l=n:u.sibling=n,u=n);I&&tg(e,w);return l;}for(m=d(e,m);!n.done;w++,n=h.next())n=y(m,e,w,n.value,k),null!==n&&(a&&null!==n.alternate&&m.delete(null===n.key?w:n.key),g=f(n,g,w),null===u?l=n:u.sibling=n,u=n);a&&m.forEach(function(a){return b(e,a);});I&&tg(e,w);return l;}function J(a,d,f,h){"object"===typeof f&&null!==f&&f.type===ya&&null===f.key&&(f=f.props.children);if("object"===typeof f&&null!==f){switch(f.$$typeof){case va:a:{for(var k=f.key,l=d;null!==l;){if(l.key===k){k=f.type;if(k===ya){if(7===l.tag){c(a,l.sibling);d=e(l,f.props.children);d.return=a;a=d;break a;}}else if(l.elementType===k||"object"===typeof k&&null!==k&&k.$$typeof===Ha&&uh(k)===l.type){c(a,l.sibling);d=e(l,f.props);d.ref=sh(a,l,f);d.return=a;a=d;break a;}c(a,l);break;}else b(a,l);l=l.sibling;}f.type===ya?(d=Ah(f.props.children,a.mode,h,f.key),d.return=a,a=d):(h=yh(f.type,f.key,f.props,null,a.mode,h),h.ref=sh(a,d,f),h.return=a,a=h);}return g(a);case wa:a:{for(l=f.key;null!==d;){if(d.key===l){if(4===d.tag&&d.stateNode.containerInfo===f.containerInfo&&d.stateNode.implementation===f.implementation){c(a,d.sibling);d=e(d,f.children||[]);d.return=a;a=d;break a;}else {c(a,d);break;}}else b(a,d);d=d.sibling;}d=zh(f,a.mode,h);d.return=a;a=d;}return g(a);case Ha:return l=f._init,J(a,d,l(f._payload),h);}if(eb(f))return n(a,d,f,h);if(Ka(f))return t(a,d,f,h);th(a,f);}return "string"===typeof f&&""!==f||"number"===typeof f?(f=""+f,null!==d&&6===d.tag?(c(a,d.sibling),d=e(d,f),d.return=a,a=d):(c(a,d),d=xh(f,a.mode,h),d.return=a,a=d),g(a)):c(a,d);}return J;}var Bh=vh(!0),Ch=vh(!1),Dh={},Eh=Uf(Dh),Fh=Uf(Dh),Gh=Uf(Dh);function Hh(a){if(a===Dh)throw Error(p$1(174));return a;}function Ih(a,b){G(Gh,b);G(Fh,a);G(Eh,Dh);a=b.nodeType;switch(a){case 9:case 11:b=(b=b.documentElement)?b.namespaceURI:lb(null,"");break;default:a=8===a?b.parentNode:b,b=a.namespaceURI||null,a=a.tagName,b=lb(b,a);}E(Eh);G(Eh,b);}function Jh(){E(Eh);E(Fh);E(Gh);}function Kh(a){Hh(Gh.current);var b=Hh(Eh.current);var c=lb(b,a.type);b!==c&&(G(Fh,a),G(Eh,c));}function Lh(a){Fh.current===a&&(E(Eh),E(Fh));}var M=Uf(0);function Mh(a){for(var b=a;null!==b;){if(13===b.tag){var c=b.memoizedState;if(null!==c&&(c=c.dehydrated,null===c||"$?"===c.data||"$!"===c.data))return b;}else if(19===b.tag&&void 0!==b.memoizedProps.revealOrder){if(0!==(b.flags&128))return b;}else if(null!==b.child){b.child.return=b;b=b.child;continue;}if(b===a)break;for(;null===b.sibling;){if(null===b.return||b.return===a)return null;b=b.return;}b.sibling.return=b.return;b=b.sibling;}return null;}var Nh=[];function Oh(){for(var a=0;ac?c:4;a(!0);var d=Qh.transition;Qh.transition={};try{a(!1),b();}finally{C=c,Qh.transition=d;}}function Fi(){return di().memoizedState;}function Gi(a,b,c){var d=lh(a);c={lane:d,action:c,hasEagerState:!1,eagerState:null,next:null};if(Hi(a))Ii(b,c);else if(c=Yg(a,b,c,d),null!==c){var e=L();mh(c,a,d,e);Ji(c,b,d);}}function ri(a,b,c){var d=lh(a),e={lane:d,action:c,hasEagerState:!1,eagerState:null,next:null};if(Hi(a))Ii(b,e);else {var f=a.alternate;if(0===a.lanes&&(null===f||0===f.lanes)&&(f=b.lastRenderedReducer,null!==f))try{var g=b.lastRenderedState,h=f(g,c);e.hasEagerState=!0;e.eagerState=h;if(He(h,g)){var k=b.interleaved;null===k?(e.next=e,Xg(b)):(e.next=k.next,k.next=e);b.interleaved=e;return;}}catch(l){}finally{}c=Yg(a,b,e,d);null!==c&&(e=L(),mh(c,a,d,e),Ji(c,b,d));}}function Hi(a){var b=a.alternate;return a===N||null!==b&&b===N;}function Ii(a,b){Th=Sh=!0;var c=a.pending;null===c?b.next=b:(b.next=c.next,c.next=b);a.pending=b;}function Ji(a,b,c){if(0!==(c&4194240)){var d=b.lanes;d&=a.pendingLanes;c|=d;b.lanes=c;Cc(a,c);}}var ai={readContext:Vg,useCallback:Q,useContext:Q,useEffect:Q,useImperativeHandle:Q,useInsertionEffect:Q,useLayoutEffect:Q,useMemo:Q,useReducer:Q,useRef:Q,useState:Q,useDebugValue:Q,useDeferredValue:Q,useTransition:Q,useMutableSource:Q,useSyncExternalStore:Q,useId:Q,unstable_isNewReconciler:!1},Yh={readContext:Vg,useCallback:function(a,b){ci().memoizedState=[a,void 0===b?null:b];return a;},useContext:Vg,useEffect:vi,useImperativeHandle:function(a,b,c){c=null!==c&&void 0!==c?c.concat([a]):null;return ti(4194308,4,yi.bind(null,b,a),c);},useLayoutEffect:function(a,b){return ti(4194308,4,a,b);},useInsertionEffect:function(a,b){return ti(4,2,a,b);},useMemo:function(a,b){var c=ci();b=void 0===b?null:b;a=a();c.memoizedState=[a,b];return a;},useReducer:function(a,b,c){var d=ci();b=void 0!==c?c(b):b;d.memoizedState=d.baseState=b;a={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:a,lastRenderedState:b};d.queue=a;a=a.dispatch=Gi.bind(null,N,a);return [d.memoizedState,a];},useRef:function(a){var b=ci();a={current:a};return b.memoizedState=a;},useState:qi,useDebugValue:Ai,useDeferredValue:function(a){return ci().memoizedState=a;},useTransition:function(){var a=qi(!1),b=a[0];a=Ei.bind(null,a[1]);ci().memoizedState=a;return [b,a];},useMutableSource:function(){},useSyncExternalStore:function(a,b,c){var d=N,e=ci();if(I){if(void 0===c)throw Error(p$1(407));c=c();}else {c=b();if(null===R)throw Error(p$1(349));0!==(Rh&30)||ni(d,b,c);}e.memoizedState=c;var f={value:c,getSnapshot:b};e.queue=f;vi(ki.bind(null,d,f,a),[a]);d.flags|=2048;li(9,mi.bind(null,d,f,c,b),void 0,null);return c;},useId:function(){var a=ci(),b=R.identifierPrefix;if(I){var c=sg;var d=rg;c=(d&~(1<<32-oc(d)-1)).toString(32)+c;b=":"+b+"R"+c;c=Uh++;0\x3c/script>",a=a.removeChild(a.firstChild)):"string"===typeof d.is?a=g.createElement(c,{is:d.is}):(a=g.createElement(c),"select"===c&&(g=a,d.multiple?g.multiple=!0:d.size&&(g.size=d.size))):a=g.createElementNS(a,c);a[Of]=b;a[Pf]=d;Aj(a,b,!1,!1);b.stateNode=a;a:{g=vb(c,d);switch(c){case"dialog":D("cancel",a);D("close",a);e=d;break;case"iframe":case"object":case"embed":D("load",a);e=d;break;case"video":case"audio":for(e=0;eHj&&(b.flags|=128,d=!0,Ej(f,!1),b.lanes=4194304);}}else {if(!d)if(a=Mh(g),null!==a){if(b.flags|=128,d=!0,c=a.updateQueue,null!==c&&(b.updateQueue=c,b.flags|=4),Ej(f,!0),null===f.tail&&"hidden"===f.tailMode&&!g.alternate&&!I)return S(b),null;}else 2*B()-f.renderingStartTime>Hj&&1073741824!==c&&(b.flags|=128,d=!0,Ej(f,!1),b.lanes=4194304);f.isBackwards?(g.sibling=b.child,b.child=g):(c=f.last,null!==c?c.sibling=g:b.child=g,f.last=g);}if(null!==f.tail)return b=f.tail,f.rendering=b,f.tail=b.sibling,f.renderingStartTime=B(),b.sibling=null,c=M.current,G(M,d?c&1|2:c&1),b;S(b);return null;case 22:case 23:return Ij(),d=null!==b.memoizedState,null!==a&&null!==a.memoizedState!==d&&(b.flags|=8192),d&&0!==(b.mode&1)?0!==(gj&1073741824)&&(S(b),b.subtreeFlags&6&&(b.flags|=8192)):S(b),null;case 24:return null;case 25:return null;}throw Error(p$1(156,b.tag));}function Jj(a,b){wg(b);switch(b.tag){case 1:return Zf(b.type)&&$f(),a=b.flags,a&65536?(b.flags=a&-65537|128,b):null;case 3:return Jh(),E(Wf),E(H),Oh(),a=b.flags,0!==(a&65536)&&0===(a&128)?(b.flags=a&-65537|128,b):null;case 5:return Lh(b),null;case 13:E(M);a=b.memoizedState;if(null!==a&&null!==a.dehydrated){if(null===b.alternate)throw Error(p$1(340));Ig();}a=b.flags;return a&65536?(b.flags=a&-65537|128,b):null;case 19:return E(M),null;case 4:return Jh(),null;case 10:return Rg(b.type._context),null;case 22:case 23:return Ij(),null;case 24:return null;default:return null;}}var Kj=!1,U=!1,Lj="function"===typeof WeakSet?WeakSet:Set,V=null;function Mj(a,b){var c=a.ref;if(null!==c)if("function"===typeof c)try{c(null);}catch(d){W(a,b,d);}else c.current=null;}function Nj(a,b,c){try{c();}catch(d){W(a,b,d);}}var Oj=!1;function Pj(a,b){Cf=dd;a=Me();if(Ne(a)){if("selectionStart"in a)var c={start:a.selectionStart,end:a.selectionEnd};else a:{c=(c=a.ownerDocument)&&c.defaultView||window;var d=c.getSelection&&c.getSelection();if(d&&0!==d.rangeCount){c=d.anchorNode;var e=d.anchorOffset,f=d.focusNode;d=d.focusOffset;try{c.nodeType,f.nodeType;}catch(F){c=null;break a;}var g=0,h=-1,k=-1,l=0,m=0,q=a,r=null;b:for(;;){for(var y;;){q!==c||0!==e&&3!==q.nodeType||(h=g+e);q!==f||0!==d&&3!==q.nodeType||(k=g+d);3===q.nodeType&&(g+=q.nodeValue.length);if(null===(y=q.firstChild))break;r=q;q=y;}for(;;){if(q===a)break b;r===c&&++l===e&&(h=g);r===f&&++m===d&&(k=g);if(null!==(y=q.nextSibling))break;q=r;r=q.parentNode;}q=y;}c=-1===h||-1===k?null:{start:h,end:k};}else c=null;}c=c||{start:0,end:0};}else c=null;Df={focusedElem:a,selectionRange:c};dd=!1;for(V=b;null!==V;)if(b=V,a=b.child,0!==(b.subtreeFlags&1028)&&null!==a)a.return=b,V=a;else for(;null!==V;){b=V;try{var n=b.alternate;if(0!==(b.flags&1024))switch(b.tag){case 0:case 11:case 15:break;case 1:if(null!==n){var t=n.memoizedProps,J=n.memoizedState,x=b.stateNode,w=x.getSnapshotBeforeUpdate(b.elementType===b.type?t:Lg(b.type,t),J);x.__reactInternalSnapshotBeforeUpdate=w;}break;case 3:var u=b.stateNode.containerInfo;1===u.nodeType?u.textContent="":9===u.nodeType&&u.documentElement&&u.removeChild(u.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(p$1(163));}}catch(F){W(b,b.return,F);}a=b.sibling;if(null!==a){a.return=b.return;V=a;break;}V=b.return;}n=Oj;Oj=!1;return n;}function Qj(a,b,c){var d=b.updateQueue;d=null!==d?d.lastEffect:null;if(null!==d){var e=d=d.next;do{if((e.tag&a)===a){var f=e.destroy;e.destroy=void 0;void 0!==f&&Nj(b,c,f);}e=e.next;}while(e!==d);}}function Rj(a,b){b=b.updateQueue;b=null!==b?b.lastEffect:null;if(null!==b){var c=b=b.next;do{if((c.tag&a)===a){var d=c.create;c.destroy=d();}c=c.next;}while(c!==b);}}function Sj(a){var b=a.ref;if(null!==b){var c=a.stateNode;switch(a.tag){case 5:a=c;break;default:a=c;}"function"===typeof b?b(a):b.current=a;}}function Tj(a){var b=a.alternate;null!==b&&(a.alternate=null,Tj(b));a.child=null;a.deletions=null;a.sibling=null;5===a.tag&&(b=a.stateNode,null!==b&&(delete b[Of],delete b[Pf],delete b[of],delete b[Qf],delete b[Rf]));a.stateNode=null;a.return=null;a.dependencies=null;a.memoizedProps=null;a.memoizedState=null;a.pendingProps=null;a.stateNode=null;a.updateQueue=null;}function Uj(a){return 5===a.tag||3===a.tag||4===a.tag;}function Vj(a){a:for(;;){for(;null===a.sibling;){if(null===a.return||Uj(a.return))return null;a=a.return;}a.sibling.return=a.return;for(a=a.sibling;5!==a.tag&&6!==a.tag&&18!==a.tag;){if(a.flags&2)continue a;if(null===a.child||4===a.tag)continue a;else a.child.return=a,a=a.child;}if(!(a.flags&2))return a.stateNode;}}function Wj(a,b,c){var d=a.tag;if(5===d||6===d)a=a.stateNode,b?8===c.nodeType?c.parentNode.insertBefore(a,b):c.insertBefore(a,b):(8===c.nodeType?(b=c.parentNode,b.insertBefore(a,c)):(b=c,b.appendChild(a)),c=c._reactRootContainer,null!==c&&void 0!==c||null!==b.onclick||(b.onclick=Bf));else if(4!==d&&(a=a.child,null!==a))for(Wj(a,b,c),a=a.sibling;null!==a;)Wj(a,b,c),a=a.sibling;}function Xj(a,b,c){var d=a.tag;if(5===d||6===d)a=a.stateNode,b?c.insertBefore(a,b):c.appendChild(a);else if(4!==d&&(a=a.child,null!==a))for(Xj(a,b,c),a=a.sibling;null!==a;)Xj(a,b,c),a=a.sibling;}var X=null,Yj=!1;function Zj(a,b,c){for(c=c.child;null!==c;)ak(a,b,c),c=c.sibling;}function ak(a,b,c){if(lc&&"function"===typeof lc.onCommitFiberUnmount)try{lc.onCommitFiberUnmount(kc,c);}catch(h){}switch(c.tag){case 5:U||Mj(c,b);case 6:var d=X,e=Yj;X=null;Zj(a,b,c);X=d;Yj=e;null!==X&&(Yj?(a=X,c=c.stateNode,8===a.nodeType?a.parentNode.removeChild(c):a.removeChild(c)):X.removeChild(c.stateNode));break;case 18:null!==X&&(Yj?(a=X,c=c.stateNode,8===a.nodeType?Kf(a.parentNode,c):1===a.nodeType&&Kf(a,c),bd(a)):Kf(X,c.stateNode));break;case 4:d=X;e=Yj;X=c.stateNode.containerInfo;Yj=!0;Zj(a,b,c);X=d;Yj=e;break;case 0:case 11:case 14:case 15:if(!U&&(d=c.updateQueue,null!==d&&(d=d.lastEffect,null!==d))){e=d=d.next;do{var f=e,g=f.destroy;f=f.tag;void 0!==g&&(0!==(f&2)?Nj(c,b,g):0!==(f&4)&&Nj(c,b,g));e=e.next;}while(e!==d);}Zj(a,b,c);break;case 1:if(!U&&(Mj(c,b),d=c.stateNode,"function"===typeof d.componentWillUnmount))try{d.props=c.memoizedProps,d.state=c.memoizedState,d.componentWillUnmount();}catch(h){W(c,b,h);}Zj(a,b,c);break;case 21:Zj(a,b,c);break;case 22:c.mode&1?(U=(d=U)||null!==c.memoizedState,Zj(a,b,c),U=d):Zj(a,b,c);break;default:Zj(a,b,c);}}function bk(a){var b=a.updateQueue;if(null!==b){a.updateQueue=null;var c=a.stateNode;null===c&&(c=a.stateNode=new Lj());b.forEach(function(b){var d=ck.bind(null,a,b);c.has(b)||(c.add(b),b.then(d,d));});}}function dk(a,b){var c=b.deletions;if(null!==c)for(var d=0;de&&(e=g);d&=~f;}d=e;d=B()-d;d=(120>d?120:480>d?480:1080>d?1080:1920>d?1920:3E3>d?3E3:4320>d?4320:1960*mk(d/1960))-d;if(10a?16:a;if(null===xk)var d=!1;else {a=xk;xk=null;yk=0;if(0!==(K&6))throw Error(p$1(331));var e=K;K|=4;for(V=a.current;null!==V;){var f=V,g=f.child;if(0!==(V.flags&16)){var h=f.deletions;if(null!==h){for(var k=0;kB()-gk?Lk(a,0):sk|=c);Ek(a,b);}function Zk(a,b){0===b&&(0===(a.mode&1)?b=1:(b=sc,sc<<=1,0===(sc&130023424)&&(sc=4194304)));var c=L();a=Zg(a,b);null!==a&&(Ac(a,b,c),Ek(a,c));}function vj(a){var b=a.memoizedState,c=0;null!==b&&(c=b.retryLane);Zk(a,c);}function ck(a,b){var c=0;switch(a.tag){case 13:var d=a.stateNode;var e=a.memoizedState;null!==e&&(c=e.retryLane);break;case 19:d=a.stateNode;break;default:throw Error(p$1(314));}null!==d&&d.delete(b);Zk(a,c);}var Wk;Wk=function(a,b,c){if(null!==a){if(a.memoizedProps!==b.pendingProps||Wf.current)Ug=!0;else {if(0===(a.lanes&c)&&0===(b.flags&128))return Ug=!1,zj(a,b,c);Ug=0!==(a.flags&131072)?!0:!1;}}else Ug=!1,I&&0!==(b.flags&1048576)&&ug(b,ng,b.index);b.lanes=0;switch(b.tag){case 2:var d=b.type;jj(a,b);a=b.pendingProps;var e=Yf(b,H.current);Tg(b,c);e=Xh(null,b,d,a,e,c);var f=bi();b.flags|=1;"object"===typeof e&&null!==e&&"function"===typeof e.render&&void 0===e.$$typeof?(b.tag=1,b.memoizedState=null,b.updateQueue=null,Zf(d)?(f=!0,cg(b)):f=!1,b.memoizedState=null!==e.state&&void 0!==e.state?e.state:null,ah(b),e.updater=nh,b.stateNode=e,e._reactInternals=b,rh(b,d,a,c),b=kj(null,b,d,!0,f,c)):(b.tag=0,I&&f&&vg(b),Yi(null,b,e,c),b=b.child);return b;case 16:d=b.elementType;a:{jj(a,b);a=b.pendingProps;e=d._init;d=e(d._payload);b.type=d;e=b.tag=$k(d);a=Lg(d,a);switch(e){case 0:b=dj(null,b,d,a,c);break a;case 1:b=ij(null,b,d,a,c);break a;case 11:b=Zi(null,b,d,a,c);break a;case 14:b=aj(null,b,d,Lg(d.type,a),c);break a;}throw Error(p$1(306,d,""));}return b;case 0:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Lg(d,e),dj(a,b,d,e,c);case 1:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Lg(d,e),ij(a,b,d,e,c);case 3:a:{lj(b);if(null===a)throw Error(p$1(387));d=b.pendingProps;f=b.memoizedState;e=f.element;bh(a,b);gh(b,d,null,c);var g=b.memoizedState;d=g.element;if(f.isDehydrated){if(f={element:d,isDehydrated:!1,cache:g.cache,pendingSuspenseBoundaries:g.pendingSuspenseBoundaries,transitions:g.transitions},b.updateQueue.baseState=f,b.memoizedState=f,b.flags&256){e=Ki(Error(p$1(423)),b);b=mj(a,b,d,c,e);break a;}else if(d!==e){e=Ki(Error(p$1(424)),b);b=mj(a,b,d,c,e);break a;}else for(yg=Lf(b.stateNode.containerInfo.firstChild),xg=b,I=!0,zg=null,c=Ch(b,null,d,c),b.child=c;c;)c.flags=c.flags&-3|4096,c=c.sibling;}else {Ig();if(d===e){b=$i(a,b,c);break a;}Yi(a,b,d,c);}b=b.child;}return b;case 5:return Kh(b),null===a&&Eg(b),d=b.type,e=b.pendingProps,f=null!==a?a.memoizedProps:null,g=e.children,Ef(d,e)?g=null:null!==f&&Ef(d,f)&&(b.flags|=32),hj(a,b),Yi(a,b,g,c),b.child;case 6:return null===a&&Eg(b),null;case 13:return pj(a,b,c);case 4:return Ih(b,b.stateNode.containerInfo),d=b.pendingProps,null===a?b.child=Bh(b,null,d,c):Yi(a,b,d,c),b.child;case 11:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Lg(d,e),Zi(a,b,d,e,c);case 7:return Yi(a,b,b.pendingProps,c),b.child;case 8:return Yi(a,b,b.pendingProps.children,c),b.child;case 12:return Yi(a,b,b.pendingProps.children,c),b.child;case 10:a:{d=b.type._context;e=b.pendingProps;f=b.memoizedProps;g=e.value;G(Mg,d._currentValue);d._currentValue=g;if(null!==f)if(He(f.value,g)){if(f.children===e.children&&!Wf.current){b=$i(a,b,c);break a;}}else for(f=b.child,null!==f&&(f.return=b);null!==f;){var h=f.dependencies;if(null!==h){g=f.child;for(var k=h.firstContext;null!==k;){if(k.context===d){if(1===f.tag){k=ch(-1,c&-c);k.tag=2;var l=f.updateQueue;if(null!==l){l=l.shared;var m=l.pending;null===m?k.next=k:(k.next=m.next,m.next=k);l.pending=k;}}f.lanes|=c;k=f.alternate;null!==k&&(k.lanes|=c);Sg(f.return,c,b);h.lanes|=c;break;}k=k.next;}}else if(10===f.tag)g=f.type===b.type?null:f.child;else if(18===f.tag){g=f.return;if(null===g)throw Error(p$1(341));g.lanes|=c;h=g.alternate;null!==h&&(h.lanes|=c);Sg(g,c,b);g=f.sibling;}else g=f.child;if(null!==g)g.return=f;else for(g=f;null!==g;){if(g===b){g=null;break;}f=g.sibling;if(null!==f){f.return=g.return;g=f;break;}g=g.return;}f=g;}Yi(a,b,e.children,c);b=b.child;}return b;case 9:return e=b.type,d=b.pendingProps.children,Tg(b,c),e=Vg(e),d=d(e),b.flags|=1,Yi(a,b,d,c),b.child;case 14:return d=b.type,e=Lg(d,b.pendingProps),e=Lg(d.type,e),aj(a,b,d,e,c);case 15:return cj(a,b,b.type,b.pendingProps,c);case 17:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Lg(d,e),jj(a,b),b.tag=1,Zf(d)?(a=!0,cg(b)):a=!1,Tg(b,c),ph(b,d,e),rh(b,d,e,c),kj(null,b,d,!0,a,c);case 19:return yj(a,b,c);case 22:return ej(a,b,c);}throw Error(p$1(156,b.tag));};function Gk(a,b){return ac(a,b);}function al(a,b,c,d){this.tag=a;this.key=c;this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null;this.index=0;this.ref=null;this.pendingProps=b;this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null;this.mode=d;this.subtreeFlags=this.flags=0;this.deletions=null;this.childLanes=this.lanes=0;this.alternate=null;}function Bg(a,b,c,d){return new al(a,b,c,d);}function bj(a){a=a.prototype;return !(!a||!a.isReactComponent);}function $k(a){if("function"===typeof a)return bj(a)?1:0;if(void 0!==a&&null!==a){a=a.$$typeof;if(a===Da)return 11;if(a===Ga)return 14;}return 2;}function wh(a,b){var c=a.alternate;null===c?(c=Bg(a.tag,b,a.key,a.mode),c.elementType=a.elementType,c.type=a.type,c.stateNode=a.stateNode,c.alternate=a,a.alternate=c):(c.pendingProps=b,c.type=a.type,c.flags=0,c.subtreeFlags=0,c.deletions=null);c.flags=a.flags&14680064;c.childLanes=a.childLanes;c.lanes=a.lanes;c.child=a.child;c.memoizedProps=a.memoizedProps;c.memoizedState=a.memoizedState;c.updateQueue=a.updateQueue;b=a.dependencies;c.dependencies=null===b?null:{lanes:b.lanes,firstContext:b.firstContext};c.sibling=a.sibling;c.index=a.index;c.ref=a.ref;return c;}function yh(a,b,c,d,e,f){var g=2;d=a;if("function"===typeof a)bj(a)&&(g=1);else if("string"===typeof a)g=5;else a:switch(a){case ya:return Ah(c.children,e,f,b);case za:g=8;e|=8;break;case Aa:return a=Bg(12,c,b,e|2),a.elementType=Aa,a.lanes=f,a;case Ea:return a=Bg(13,c,b,e),a.elementType=Ea,a.lanes=f,a;case Fa:return a=Bg(19,c,b,e),a.elementType=Fa,a.lanes=f,a;case Ia:return qj(c,e,f,b);default:if("object"===typeof a&&null!==a)switch(a.$$typeof){case Ba:g=10;break a;case Ca:g=9;break a;case Da:g=11;break a;case Ga:g=14;break a;case Ha:g=16;d=null;break a;}throw Error(p$1(130,null==a?a:typeof a,""));}b=Bg(g,c,b,e);b.elementType=a;b.type=d;b.lanes=f;return b;}function Ah(a,b,c,d){a=Bg(7,a,d,b);a.lanes=c;return a;}function qj(a,b,c,d){a=Bg(22,a,d,b);a.elementType=Ia;a.lanes=c;a.stateNode={isHidden:!1};return a;}function xh(a,b,c){a=Bg(6,a,null,b);a.lanes=c;return a;}function zh(a,b,c){b=Bg(4,null!==a.children?a.children:[],a.key,b);b.lanes=c;b.stateNode={containerInfo:a.containerInfo,pendingChildren:null,implementation:a.implementation};return b;}function bl(a,b,c,d,e){this.tag=b;this.containerInfo=a;this.finishedWork=this.pingCache=this.current=this.pendingChildren=null;this.timeoutHandle=-1;this.callbackNode=this.pendingContext=this.context=null;this.callbackPriority=0;this.eventTimes=zc(0);this.expirationTimes=zc(-1);this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0;this.entanglements=zc(0);this.identifierPrefix=d;this.onRecoverableError=e;this.mutableSourceEagerHydrationData=null;}function cl(a,b,c,d,e,f,g,h,k){a=new bl(a,b,c,h,k);1===b?(b=1,!0===f&&(b|=8)):b=0;f=Bg(3,null,null,b);a.current=f;f.stateNode=a;f.memoizedState={element:d,isDehydrated:c,cache:null,transitions:null,pendingSuspenseBoundaries:null};ah(f);return a;}function dl(a,b,c){var d=3 is set, // the File will have a {webkitRelativePath} property // https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/webkitdirectory :typeof webkitRelativePath==='string'&&webkitRelativePath.length>0?webkitRelativePath:file.name,writable:false,configurable:false,enumerable:true});}return f;}function withMimeType(file){var name=file.name;var hasExtension=name&&name.lastIndexOf('.')!==-1;if(hasExtension&&!file.type){var ext=name.split('.').pop().toLowerCase();var type=COMMON_MIME_TYPES.get(ext);if(type){Object.defineProperty(file,'type',{value:type,writable:false,configurable:false,enumerable:true});}}return file;} var FILES_TO_IGNORE=[// Thumbnail cache files for macOS and Windows '.DS_Store','Thumbs.db'// Windows ];/** * Convert a DragEvent's DataTrasfer object to a list of File objects * NOTE: If some of the items are folders, * everything will be flattened and placed in the same list but the paths will be kept as a {path} property. * * EXPERIMENTAL: A list of https://developer.mozilla.org/en-US/docs/Web/API/FileSystemHandle objects can also be passed as an arg * and a list of File objects will be returned. * * @param evt */function fromEvent(evt){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a){if(isObject(evt)&&isDataTransfer(evt.dataTransfer)){return [2/*return*/,getDataTransferFiles(evt.dataTransfer,evt.type)];}else if(isChangeEvt(evt)){return [2/*return*/,getInputFiles(evt)];}else if(Array.isArray(evt)&&evt.every(function(item){return 'getFile'in item&&typeof item.getFile==='function';})){return [2/*return*/,getFsHandleFiles(evt)];}return [2/*return*/,[]];});});}function isDataTransfer(value){return isObject(value);}function isChangeEvt(value){return isObject(value)&&isObject(value.target);}function isObject(v){return typeof v==='object'&&v!==null;}function getInputFiles(evt){return fromList(evt.target.files).map(function(file){return toFileWithPath(file);});}// Ee expect each handle to be https://developer.mozilla.org/en-US/docs/Web/API/FileSystemFileHandle function getFsHandleFiles(handles){return __awaiter(this,void 0,void 0,function(){var files;return __generator(this,function(_a){switch(_a.label){case 0:return [4/*yield*/,Promise.all(handles.map(function(h){return h.getFile();}))];case 1:files=_a.sent();return [2/*return*/,files.map(function(file){return toFileWithPath(file);})];}});});}function getDataTransferFiles(dt,type){return __awaiter(this,void 0,void 0,function(){var items,files;return __generator(this,function(_a){switch(_a.label){case 0:if(!dt.items)return [3/*break*/,2];items=fromList(dt.items).filter(function(item){return item.kind==='file';});// According to https://html.spec.whatwg.org/multipage/dnd.html#dndevents, // only 'dragstart' and 'drop' has access to the data (source node) if(type!=='drop'){return [2/*return*/,items];}return [4/*yield*/,Promise.all(items.map(toFilePromises))];case 1:files=_a.sent();return [2/*return*/,noIgnoredFiles(flatten(files))];case 2:return [2/*return*/,noIgnoredFiles(fromList(dt.files).map(function(file){return toFileWithPath(file);}))];}});});}function noIgnoredFiles(files){return files.filter(function(file){return FILES_TO_IGNORE.indexOf(file.name)===-1;});}// IE11 does not support Array.from() // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from#Browser_compatibility // https://developer.mozilla.org/en-US/docs/Web/API/FileList // https://developer.mozilla.org/en-US/docs/Web/API/DataTransferItemList function fromList(items){if(items===null){return [];}var files=[];// tslint:disable: prefer-for-of for(var i=0;iarr.length)len=arr.length;for(var i=0,arr2=new Array(len);imaxSize)return [false,getTooLargeRejectionErr(maxSize)];if(file.sizemaxSize)return [false,getTooLargeRejectionErr(maxSize)];}return [true,null];}function isDefined(value){return value!==undefined&&value!==null;}/** * * @param {object} options * @param {File[]} options.files * @param {string|string[]} [options.accept] * @param {number} [options.minSize] * @param {number} [options.maxSize] * @param {boolean} [options.multiple] * @param {number} [options.maxFiles] * @param {(f: File) => FileError|FileError[]|null} [options.validator] * @returns */function allFilesAccepted(_ref){var files=_ref.files,accept=_ref.accept,minSize=_ref.minSize,maxSize=_ref.maxSize,multiple=_ref.multiple,maxFiles=_ref.maxFiles,validator=_ref.validator;if(!multiple&&files.length>1||multiple&&maxFiles>=1&&files.length>maxFiles){return false;}return files.every(function(file){var _fileAccepted=fileAccepted(file,accept),_fileAccepted2=_slicedToArray$1(_fileAccepted,1),accepted=_fileAccepted2[0];var _fileMatchSize=fileMatchSize(file,minSize,maxSize),_fileMatchSize2=_slicedToArray$1(_fileMatchSize,1),sizeMatch=_fileMatchSize2[0];var customErrors=validator?validator(file):null;return accepted&&sizeMatch&&!customErrors;});}// React's synthetic events has event.isPropagationStopped, // but to remain compatibility with other libs (Preact) fall back // to check event.cancelBubble function isPropagationStopped(event){if(typeof event.isPropagationStopped==="function"){return event.isPropagationStopped();}else if(typeof event.cancelBubble!=="undefined"){return event.cancelBubble;}return false;}function isEvtWithFiles(event){if(!event.dataTransfer){return !!event.target&&!!event.target.files;}// https://developer.mozilla.org/en-US/docs/Web/API/DataTransfer/types // https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API/Recommended_drag_types#file return Array.prototype.some.call(event.dataTransfer.types,function(type){return type==="Files"||type==="application/x-moz-file";});}function onDocumentDragOver(event){event.preventDefault();}function isIe(userAgent){return userAgent.indexOf("MSIE")!==-1||userAgent.indexOf("Trident/")!==-1;}function isEdge(userAgent){return userAgent.indexOf("Edge/")!==-1;}function isIeOrEdge(){var userAgent=arguments.length>0&&arguments[0]!==undefined?arguments[0]:window.navigator.userAgent;return isIe(userAgent)||isEdge(userAgent);}/** * This is intended to be used to compose event handlers * They are executed in order until one of them calls `event.isPropagationStopped()`. * Note that the check is done on the first invoke too, * meaning that if propagation was stopped before invoking the fns, * no handlers will be executed. * * @param {Function} fns the event hanlder functions * @return {Function} the event handler to add to an element */function composeEventHandlers(){for(var _len=arguments.length,fns=new Array(_len),_key=0;_key<_len;_key++){fns[_key]=arguments[_key];}return function(event){for(var _len2=arguments.length,args=new Array(_len2>1?_len2-1:0),_key2=1;_key2<_len2;_key2++){args[_key2-1]=arguments[_key2];}return fns.some(function(fn){if(!isPropagationStopped(event)&&fn){fn.apply(void 0,[event].concat(args));}return isPropagationStopped(event);});};}/** * canUseFileSystemAccessAPI checks if the [File System Access API](https://developer.mozilla.org/en-US/docs/Web/API/File_System_Access_API) * is supported by the browser. * @returns {boolean} */function canUseFileSystemAccessAPI(){return "showOpenFilePicker"in window;}/** * Convert the `{accept}` dropzone prop to the * `{types}` option for https://developer.mozilla.org/en-US/docs/Web/API/window/showOpenFilePicker * * @param {AcceptProp} accept * @returns {{accept: string[]}[]} */function pickerOptionsFromAccept(accept){if(isDefined(accept)){var acceptForPicker=Object.entries(accept).filter(function(_ref2){var _ref3=_slicedToArray$1(_ref2,2),mimeType=_ref3[0],ext=_ref3[1];var ok=true;if(!isMIMEType(mimeType)){console.warn("Skipped \"".concat(mimeType,"\" because it is not a valid MIME type. Check https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types for a list of valid MIME types."));ok=false;}if(!Array.isArray(ext)||!ext.every(isExt)){console.warn("Skipped \"".concat(mimeType,"\" because an invalid file extension was provided."));ok=false;}return ok;}).reduce(function(agg,_ref4){var _ref5=_slicedToArray$1(_ref4,2),mimeType=_ref5[0],ext=_ref5[1];return _objectSpread$1(_objectSpread$1({},agg),{},_defineProperty$2({},mimeType,ext));},{});return [{// description is required due to https://crbug.com/1264708 description:"Files",accept:acceptForPicker}];}return accept;}/** * Convert the `{accept}` dropzone prop to an array of MIME types/extensions. * @param {AcceptProp} accept * @returns {string} */function acceptPropAsAcceptAttr(accept){if(isDefined(accept)){return Object.entries(accept).reduce(function(a,_ref6){var _ref7=_slicedToArray$1(_ref6,2),mimeType=_ref7[0],ext=_ref7[1];return [].concat(_toConsumableArray$2(a),[mimeType],_toConsumableArray$2(ext));},[])// Silently discard invalid entries as pickerOptionsFromAccept warns about these .filter(function(v){return isMIMEType(v)||isExt(v);}).join(",");}return undefined;}/** * Check if v is an exception caused by aborting a request (e.g window.showOpenFilePicker()). * * See https://developer.mozilla.org/en-US/docs/Web/API/DOMException. * @param {any} v * @returns {boolean} True if v is an abort exception. */function isAbort(v){return v instanceof DOMException&&(v.name==="AbortError"||v.code===v.ABORT_ERR);}/** * Check if v is a security error. * * See https://developer.mozilla.org/en-US/docs/Web/API/DOMException. * @param {any} v * @returns {boolean} True if v is a security error. */function isSecurityError(v){return v instanceof DOMException&&(v.name==="SecurityError"||v.code===v.SECURITY_ERR);}/** * Check if v is a MIME type string. * * See accepted format: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file#unique_file_type_specifiers. * * @param {string} v */function isMIMEType(v){return v==="audio/*"||v==="video/*"||v==="image/*"||v==="text/*"||/\w+\/[-+.\w]+/g.test(v);}/** * Check if v is a file extension. * @param {string} v */function isExt(v){return /^.*\.[\w]+$/.test(v);}/** * @typedef {Object.} AcceptProp */ /** * @typedef {object} FileError * @property {string} message * @property {ErrorCode|string} code */ /** * @typedef {"file-invalid-type"|"file-too-large"|"file-too-small"|"too-many-files"} ErrorCode */ var _excluded=["children"],_excluded2=["open"],_excluded3=["refKey","role","onKeyDown","onFocus","onBlur","onClick","onDragEnter","onDragOver","onDragLeave","onDrop"],_excluded4=["refKey","onChange","onClick"];function _toConsumableArray$1(arr){return _arrayWithoutHoles(arr)||_iterableToArray(arr)||_unsupportedIterableToArray(arr)||_nonIterableSpread();}function _nonIterableSpread(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");}function _iterableToArray(iter){if(typeof Symbol!=="undefined"&&iter[Symbol.iterator]!=null||iter["@@iterator"]!=null)return Array.from(iter);}function _arrayWithoutHoles(arr){if(Array.isArray(arr))return _arrayLikeToArray(arr);}function _slicedToArray(arr,i){return _arrayWithHoles(arr)||_iterableToArrayLimit(arr,i)||_unsupportedIterableToArray(arr,i)||_nonIterableRest();}function _nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");}function _unsupportedIterableToArray(o,minLen){if(!o)return;if(typeof o==="string")return _arrayLikeToArray(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);if(n==="Object"&&o.constructor)n=o.constructor.name;if(n==="Map"||n==="Set")return Array.from(o);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return _arrayLikeToArray(o,minLen);}function _arrayLikeToArray(arr,len){if(len==null||len>arr.length)len=arr.length;for(var i=0,arr2=new Array(len);i=0)continue;if(!Object.prototype.propertyIsEnumerable.call(source,key))continue;target[key]=source[key];}}return target;}function _objectWithoutPropertiesLoose(source,excluded){if(source==null)return {};var target={};var sourceKeys=Object.keys(source);var key,i;for(i=0;i=0)continue;target[key]=source[key];}return target;}/** * Convenience wrapper component for the `useDropzone` hook * * ```jsx * * {({getRootProps, getInputProps}) => ( *
* *

Drag 'n' drop some files here, or click to select files

*
* )} *
* ``` */var Dropzone=/*#__PURE__*/reactExports.forwardRef(function(_ref,ref){var children=_ref.children,params=_objectWithoutProperties(_ref,_excluded);var _useDropzone=useDropzone(params),open=_useDropzone.open,props=_objectWithoutProperties(_useDropzone,_excluded2);reactExports.useImperativeHandle(ref,function(){return {open:open};},[open]);// TODO: Figure out why react-styleguidist cannot create docs if we don't return a jsx element return/*#__PURE__*/React.createElement(reactExports.Fragment,null,children(_objectSpread(_objectSpread({},props),{},{open:open})));});Dropzone.displayName="Dropzone";// Add default props for react-docgen var defaultProps={disabled:false,getFilesFromEvent:fromEvent,maxSize:Infinity,minSize:0,multiple:true,maxFiles:0,preventDropOnDocument:true,noClick:false,noKeyboard:false,noDrag:false,noDragEventsBubbling:false,validator:null,useFsAccessApi:true,autoFocus:false};Dropzone.defaultProps=defaultProps;Dropzone.propTypes={/** * Render function that exposes the dropzone state and prop getter fns * * @param {object} params * @param {Function} params.getRootProps Returns the props you should apply to the root drop container you render * @param {Function} params.getInputProps Returns the props you should apply to hidden file input you render * @param {Function} params.open Open the native file selection dialog * @param {boolean} params.isFocused Dropzone area is in focus * @param {boolean} params.isFileDialogActive File dialog is opened * @param {boolean} params.isDragActive Active drag is in progress * @param {boolean} params.isDragAccept Dragged files are accepted * @param {boolean} params.isDragReject Some dragged files are rejected * @param {File[]} params.acceptedFiles Accepted files * @param {FileRejection[]} params.fileRejections Rejected files and why they were rejected */children:PropTypes.func,/** * Set accepted file types. * Checkout https://developer.mozilla.org/en-US/docs/Web/API/window/showOpenFilePicker types option for more information. * Keep in mind that mime type determination is not reliable across platforms. CSV files, * for example, are reported as text/plain under macOS but as application/vnd.ms-excel under * Windows. In some cases there might not be a mime type set at all (https://github.com/react-dropzone/react-dropzone/issues/276). */accept:PropTypes.objectOf(PropTypes.arrayOf(PropTypes.string)),/** * Allow drag 'n' drop (or selection from the file dialog) of multiple files */multiple:PropTypes.bool,/** * If false, allow dropped items to take over the current browser window */preventDropOnDocument:PropTypes.bool,/** * If true, disables click to open the native file selection dialog */noClick:PropTypes.bool,/** * If true, disables SPACE/ENTER to open the native file selection dialog. * Note that it also stops tracking the focus state. */noKeyboard:PropTypes.bool,/** * If true, disables drag 'n' drop */noDrag:PropTypes.bool,/** * If true, stops drag event propagation to parents */noDragEventsBubbling:PropTypes.bool,/** * Minimum file size (in bytes) */minSize:PropTypes.number,/** * Maximum file size (in bytes) */maxSize:PropTypes.number,/** * Maximum accepted number of files * The default value is 0 which means there is no limitation to how many files are accepted. */maxFiles:PropTypes.number,/** * Enable/disable the dropzone */disabled:PropTypes.bool,/** * Use this to provide a custom file aggregator * * @param {(DragEvent|Event)} event A drag event or input change event (if files were selected via the file dialog) */getFilesFromEvent:PropTypes.func,/** * Cb for when closing the file dialog with no selection */onFileDialogCancel:PropTypes.func,/** * Cb for when opening the file dialog */onFileDialogOpen:PropTypes.func,/** * Set to true to use the https://developer.mozilla.org/en-US/docs/Web/API/File_System_Access_API * to open the file picker instead of using an `` click event. */useFsAccessApi:PropTypes.bool,/** * Set to true to focus the root element on render */autoFocus:PropTypes.bool,/** * Cb for when the `dragenter` event occurs. * * @param {DragEvent} event */onDragEnter:PropTypes.func,/** * Cb for when the `dragleave` event occurs * * @param {DragEvent} event */onDragLeave:PropTypes.func,/** * Cb for when the `dragover` event occurs * * @param {DragEvent} event */onDragOver:PropTypes.func,/** * Cb for when the `drop` event occurs. * Note that this callback is invoked after the `getFilesFromEvent` callback is done. * * Files are accepted or rejected based on the `accept`, `multiple`, `minSize` and `maxSize` props. * `accept` must be a valid [MIME type](http://www.iana.org/assignments/media-types/media-types.xhtml) according to [input element specification](https://www.w3.org/wiki/HTML/Elements/input/file) or a valid file extension. * If `multiple` is set to false and additional files are dropped, * all files besides the first will be rejected. * Any file which does not have a size in the [`minSize`, `maxSize`] range, will be rejected as well. * * Note that the `onDrop` callback will always be invoked regardless if the dropped files were accepted or rejected. * If you'd like to react to a specific scenario, use the `onDropAccepted`/`onDropRejected` props. * * `onDrop` will provide you with an array of [File](https://developer.mozilla.org/en-US/docs/Web/API/File) objects which you can then process and send to a server. * For example, with [SuperAgent](https://github.com/visionmedia/superagent) as a http/ajax library: * * ```js * function onDrop(acceptedFiles) { * const req = request.post('/upload') * acceptedFiles.forEach(file => { * req.attach(file.name, file) * }) * req.end(callback) * } * ``` * * @param {File[]} acceptedFiles * @param {FileRejection[]} fileRejections * @param {(DragEvent|Event)} event A drag event or input change event (if files were selected via the file dialog) */onDrop:PropTypes.func,/** * Cb for when the `drop` event occurs. * Note that if no files are accepted, this callback is not invoked. * * @param {File[]} files * @param {(DragEvent|Event)} event */onDropAccepted:PropTypes.func,/** * Cb for when the `drop` event occurs. * Note that if no files are rejected, this callback is not invoked. * * @param {FileRejection[]} fileRejections * @param {(DragEvent|Event)} event */onDropRejected:PropTypes.func,/** * Cb for when there's some error from any of the promises. * * @param {Error} error */onError:PropTypes.func,/** * Custom validation function. It must return null if there's no errors. * @param {File} file * @returns {FileError|FileError[]|null} */validator:PropTypes.func};var Dropzone$1 = Dropzone;/** * A function that is invoked for the `dragenter`, * `dragover` and `dragleave` events. * It is not invoked if the items are not files (such as link, text, etc.). * * @callback dragCb * @param {DragEvent} event */ /** * A function that is invoked for the `drop` or input change event. * It is not invoked if the items are not files (such as link, text, etc.). * * @callback dropCb * @param {File[]} acceptedFiles List of accepted files * @param {FileRejection[]} fileRejections List of rejected files and why they were rejected * @param {(DragEvent|Event)} event A drag event or input change event (if files were selected via the file dialog) */ /** * A function that is invoked for the `drop` or input change event. * It is not invoked if the items are files (such as link, text, etc.). * * @callback dropAcceptedCb * @param {File[]} files List of accepted files that meet the given criteria * (`accept`, `multiple`, `minSize`, `maxSize`) * @param {(DragEvent|Event)} event A drag event or input change event (if files were selected via the file dialog) */ /** * A function that is invoked for the `drop` or input change event. * * @callback dropRejectedCb * @param {File[]} files List of rejected files that do not meet the given criteria * (`accept`, `multiple`, `minSize`, `maxSize`) * @param {(DragEvent|Event)} event A drag event or input change event (if files were selected via the file dialog) */ /** * A function that is used aggregate files, * in a asynchronous fashion, from drag or input change events. * * @callback getFilesFromEvent * @param {(DragEvent|Event)} event A drag event or input change event (if files were selected via the file dialog) * @returns {(File[]|Promise)} */ /** * An object with the current dropzone state. * * @typedef {object} DropzoneState * @property {boolean} isFocused Dropzone area is in focus * @property {boolean} isFileDialogActive File dialog is opened * @property {boolean} isDragActive Active drag is in progress * @property {boolean} isDragAccept Dragged files are accepted * @property {boolean} isDragReject Some dragged files are rejected * @property {File[]} acceptedFiles Accepted files * @property {FileRejection[]} fileRejections Rejected files and why they were rejected */ /** * An object with the dropzone methods. * * @typedef {object} DropzoneMethods * @property {Function} getRootProps Returns the props you should apply to the root drop container you render * @property {Function} getInputProps Returns the props you should apply to hidden file input you render * @property {Function} open Open the native file selection dialog */var initialState={isFocused:false,isFileDialogActive:false,isDragActive:false,isDragAccept:false,isDragReject:false,acceptedFiles:[],fileRejections:[]};/** * A React hook that creates a drag 'n' drop area. * * ```jsx * function MyDropzone(props) { * const {getRootProps, getInputProps} = useDropzone({ * onDrop: acceptedFiles => { * // do something with the File objects, e.g. upload to some server * } * }); * return ( *
* *

Drag and drop some files here, or click to select files

*
* ) * } * ``` * * @function useDropzone * * @param {object} props * @param {import("./utils").AcceptProp} [props.accept] Set accepted file types. * Checkout https://developer.mozilla.org/en-US/docs/Web/API/window/showOpenFilePicker types option for more information. * Keep in mind that mime type determination is not reliable across platforms. CSV files, * for example, are reported as text/plain under macOS but as application/vnd.ms-excel under * Windows. In some cases there might not be a mime type set at all (https://github.com/react-dropzone/react-dropzone/issues/276). * @param {boolean} [props.multiple=true] Allow drag 'n' drop (or selection from the file dialog) of multiple files * @param {boolean} [props.preventDropOnDocument=true] If false, allow dropped items to take over the current browser window * @param {boolean} [props.noClick=false] If true, disables click to open the native file selection dialog * @param {boolean} [props.noKeyboard=false] If true, disables SPACE/ENTER to open the native file selection dialog. * Note that it also stops tracking the focus state. * @param {boolean} [props.noDrag=false] If true, disables drag 'n' drop * @param {boolean} [props.noDragEventsBubbling=false] If true, stops drag event propagation to parents * @param {number} [props.minSize=0] Minimum file size (in bytes) * @param {number} [props.maxSize=Infinity] Maximum file size (in bytes) * @param {boolean} [props.disabled=false] Enable/disable the dropzone * @param {getFilesFromEvent} [props.getFilesFromEvent] Use this to provide a custom file aggregator * @param {Function} [props.onFileDialogCancel] Cb for when closing the file dialog with no selection * @param {boolean} [props.useFsAccessApi] Set to true to use the https://developer.mozilla.org/en-US/docs/Web/API/File_System_Access_API * to open the file picker instead of using an `` click event. * @param {boolean} autoFocus Set to true to auto focus the root element. * @param {Function} [props.onFileDialogOpen] Cb for when opening the file dialog * @param {dragCb} [props.onDragEnter] Cb for when the `dragenter` event occurs. * @param {dragCb} [props.onDragLeave] Cb for when the `dragleave` event occurs * @param {dragCb} [props.onDragOver] Cb for when the `dragover` event occurs * @param {dropCb} [props.onDrop] Cb for when the `drop` event occurs. * Note that this callback is invoked after the `getFilesFromEvent` callback is done. * * Files are accepted or rejected based on the `accept`, `multiple`, `minSize` and `maxSize` props. * `accept` must be an object with keys as a valid [MIME type](http://www.iana.org/assignments/media-types/media-types.xhtml) according to [input element specification](https://www.w3.org/wiki/HTML/Elements/input/file) and the value an array of file extensions (optional). * If `multiple` is set to false and additional files are dropped, * all files besides the first will be rejected. * Any file which does not have a size in the [`minSize`, `maxSize`] range, will be rejected as well. * * Note that the `onDrop` callback will always be invoked regardless if the dropped files were accepted or rejected. * If you'd like to react to a specific scenario, use the `onDropAccepted`/`onDropRejected` props. * * `onDrop` will provide you with an array of [File](https://developer.mozilla.org/en-US/docs/Web/API/File) objects which you can then process and send to a server. * For example, with [SuperAgent](https://github.com/visionmedia/superagent) as a http/ajax library: * * ```js * function onDrop(acceptedFiles) { * const req = request.post('/upload') * acceptedFiles.forEach(file => { * req.attach(file.name, file) * }) * req.end(callback) * } * ``` * @param {dropAcceptedCb} [props.onDropAccepted] * @param {dropRejectedCb} [props.onDropRejected] * @param {(error: Error) => void} [props.onError] * * @returns {DropzoneState & DropzoneMethods} */function useDropzone(){var props=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};var _defaultProps$props=_objectSpread(_objectSpread({},defaultProps),props),accept=_defaultProps$props.accept,disabled=_defaultProps$props.disabled,getFilesFromEvent=_defaultProps$props.getFilesFromEvent,maxSize=_defaultProps$props.maxSize,minSize=_defaultProps$props.minSize,multiple=_defaultProps$props.multiple,maxFiles=_defaultProps$props.maxFiles,onDragEnter=_defaultProps$props.onDragEnter,onDragLeave=_defaultProps$props.onDragLeave,onDragOver=_defaultProps$props.onDragOver,onDrop=_defaultProps$props.onDrop,onDropAccepted=_defaultProps$props.onDropAccepted,onDropRejected=_defaultProps$props.onDropRejected,onFileDialogCancel=_defaultProps$props.onFileDialogCancel,onFileDialogOpen=_defaultProps$props.onFileDialogOpen,useFsAccessApi=_defaultProps$props.useFsAccessApi,autoFocus=_defaultProps$props.autoFocus,preventDropOnDocument=_defaultProps$props.preventDropOnDocument,noClick=_defaultProps$props.noClick,noKeyboard=_defaultProps$props.noKeyboard,noDrag=_defaultProps$props.noDrag,noDragEventsBubbling=_defaultProps$props.noDragEventsBubbling,onError=_defaultProps$props.onError,validator=_defaultProps$props.validator;var acceptAttr=reactExports.useMemo(function(){return acceptPropAsAcceptAttr(accept);},[accept]);var pickerTypes=reactExports.useMemo(function(){return pickerOptionsFromAccept(accept);},[accept]);var onFileDialogOpenCb=reactExports.useMemo(function(){return typeof onFileDialogOpen==="function"?onFileDialogOpen:noop;},[onFileDialogOpen]);var onFileDialogCancelCb=reactExports.useMemo(function(){return typeof onFileDialogCancel==="function"?onFileDialogCancel:noop;},[onFileDialogCancel]);/** * @constant * @type {React.MutableRefObject} */var rootRef=reactExports.useRef(null);var inputRef=reactExports.useRef(null);var _useReducer=reactExports.useReducer(reducer,initialState),_useReducer2=_slicedToArray(_useReducer,2),state=_useReducer2[0],dispatch=_useReducer2[1];var isFocused=state.isFocused,isFileDialogActive=state.isFileDialogActive;var fsAccessApiWorksRef=reactExports.useRef(typeof window!=="undefined"&&window.isSecureContext&&useFsAccessApi&&canUseFileSystemAccessAPI());// Update file dialog active state when the window is focused on var onWindowFocus=function onWindowFocus(){// Execute the timeout only if the file dialog is opened in the browser if(!fsAccessApiWorksRef.current&&isFileDialogActive){setTimeout(function(){if(inputRef.current){var files=inputRef.current.files;if(!files.length){dispatch({type:"closeDialog"});onFileDialogCancelCb();}}},300);}};reactExports.useEffect(function(){window.addEventListener("focus",onWindowFocus,false);return function(){window.removeEventListener("focus",onWindowFocus,false);};},[inputRef,isFileDialogActive,onFileDialogCancelCb,fsAccessApiWorksRef]);var dragTargetsRef=reactExports.useRef([]);var onDocumentDrop=function onDocumentDrop(event){if(rootRef.current&&rootRef.current.contains(event.target)){// If we intercepted an event for our instance, let it propagate down to the instance's onDrop handler return;}event.preventDefault();dragTargetsRef.current=[];};reactExports.useEffect(function(){if(preventDropOnDocument){document.addEventListener("dragover",onDocumentDragOver,false);document.addEventListener("drop",onDocumentDrop,false);}return function(){if(preventDropOnDocument){document.removeEventListener("dragover",onDocumentDragOver);document.removeEventListener("drop",onDocumentDrop);}};},[rootRef,preventDropOnDocument]);// Auto focus the root when autoFocus is true reactExports.useEffect(function(){if(!disabled&&autoFocus&&rootRef.current){rootRef.current.focus();}return function(){};},[rootRef,autoFocus,disabled]);var onErrCb=reactExports.useCallback(function(e){if(onError){onError(e);}else {// Let the user know something's gone wrong if they haven't provided the onError cb. console.error(e);}},[onError]);var onDragEnterCb=reactExports.useCallback(function(event){event.preventDefault();// Persist here because we need the event later after getFilesFromEvent() is done event.persist();stopPropagation(event);dragTargetsRef.current=[].concat(_toConsumableArray$1(dragTargetsRef.current),[event.target]);if(isEvtWithFiles(event)){Promise.resolve(getFilesFromEvent(event)).then(function(files){if(isPropagationStopped(event)&&!noDragEventsBubbling){return;}var fileCount=files.length;var isDragAccept=fileCount>0&&allFilesAccepted({files:files,accept:acceptAttr,minSize:minSize,maxSize:maxSize,multiple:multiple,maxFiles:maxFiles,validator:validator});var isDragReject=fileCount>0&&!isDragAccept;dispatch({isDragAccept:isDragAccept,isDragReject:isDragReject,isDragActive:true,type:"setDraggedFiles"});if(onDragEnter){onDragEnter(event);}}).catch(function(e){return onErrCb(e);});}},[getFilesFromEvent,onDragEnter,onErrCb,noDragEventsBubbling,acceptAttr,minSize,maxSize,multiple,maxFiles,validator]);var onDragOverCb=reactExports.useCallback(function(event){event.preventDefault();event.persist();stopPropagation(event);var hasFiles=isEvtWithFiles(event);if(hasFiles&&event.dataTransfer){try{event.dataTransfer.dropEffect="copy";}catch(_unused){}/* eslint-disable-line no-empty */}if(hasFiles&&onDragOver){onDragOver(event);}return false;},[onDragOver,noDragEventsBubbling]);var onDragLeaveCb=reactExports.useCallback(function(event){event.preventDefault();event.persist();stopPropagation(event);// Only deactivate once the dropzone and all children have been left var targets=dragTargetsRef.current.filter(function(target){return rootRef.current&&rootRef.current.contains(target);});// Make sure to remove a target present multiple times only once // (Firefox may fire dragenter/dragleave multiple times on the same element) var targetIdx=targets.indexOf(event.target);if(targetIdx!==-1){targets.splice(targetIdx,1);}dragTargetsRef.current=targets;if(targets.length>0){return;}dispatch({type:"setDraggedFiles",isDragActive:false,isDragAccept:false,isDragReject:false});if(isEvtWithFiles(event)&&onDragLeave){onDragLeave(event);}},[rootRef,onDragLeave,noDragEventsBubbling]);var setFiles=reactExports.useCallback(function(files,event){var acceptedFiles=[];var fileRejections=[];files.forEach(function(file){var _fileAccepted=fileAccepted(file,acceptAttr),_fileAccepted2=_slicedToArray(_fileAccepted,2),accepted=_fileAccepted2[0],acceptError=_fileAccepted2[1];var _fileMatchSize=fileMatchSize(file,minSize,maxSize),_fileMatchSize2=_slicedToArray(_fileMatchSize,2),sizeMatch=_fileMatchSize2[0],sizeError=_fileMatchSize2[1];var customErrors=validator?validator(file):null;if(accepted&&sizeMatch&&!customErrors){acceptedFiles.push(file);}else {var errors=[acceptError,sizeError];if(customErrors){errors=errors.concat(customErrors);}fileRejections.push({file:file,errors:errors.filter(function(e){return e;})});}});if(!multiple&&acceptedFiles.length>1||multiple&&maxFiles>=1&&acceptedFiles.length>maxFiles){// Reject everything and empty accepted files acceptedFiles.forEach(function(file){fileRejections.push({file:file,errors:[TOO_MANY_FILES_REJECTION]});});acceptedFiles.splice(0);}dispatch({acceptedFiles:acceptedFiles,fileRejections:fileRejections,type:"setFiles"});if(onDrop){onDrop(acceptedFiles,fileRejections,event);}if(fileRejections.length>0&&onDropRejected){onDropRejected(fileRejections,event);}if(acceptedFiles.length>0&&onDropAccepted){onDropAccepted(acceptedFiles,event);}},[dispatch,multiple,acceptAttr,minSize,maxSize,maxFiles,onDrop,onDropAccepted,onDropRejected,validator]);var onDropCb=reactExports.useCallback(function(event){event.preventDefault();// Persist here because we need the event later after getFilesFromEvent() is done event.persist();stopPropagation(event);dragTargetsRef.current=[];if(isEvtWithFiles(event)){Promise.resolve(getFilesFromEvent(event)).then(function(files){if(isPropagationStopped(event)&&!noDragEventsBubbling){return;}setFiles(files,event);}).catch(function(e){return onErrCb(e);});}dispatch({type:"reset"});},[getFilesFromEvent,setFiles,onErrCb,noDragEventsBubbling]);// Fn for opening the file dialog programmatically var openFileDialog=reactExports.useCallback(function(){// No point to use FS access APIs if context is not secure // https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts#feature_detection if(fsAccessApiWorksRef.current){dispatch({type:"openDialog"});onFileDialogOpenCb();// https://developer.mozilla.org/en-US/docs/Web/API/window/showOpenFilePicker var opts={multiple:multiple,types:pickerTypes};window.showOpenFilePicker(opts).then(function(handles){return getFilesFromEvent(handles);}).then(function(files){setFiles(files,null);dispatch({type:"closeDialog"});}).catch(function(e){// AbortError means the user canceled if(isAbort(e)){onFileDialogCancelCb(e);dispatch({type:"closeDialog"});}else if(isSecurityError(e)){fsAccessApiWorksRef.current=false;// CORS, so cannot use this API // Try using the input if(inputRef.current){inputRef.current.value=null;inputRef.current.click();}else {onErrCb(new Error("Cannot open the file picker because the https://developer.mozilla.org/en-US/docs/Web/API/File_System_Access_API is not supported and no was provided."));}}else {onErrCb(e);}});return;}if(inputRef.current){dispatch({type:"openDialog"});onFileDialogOpenCb();inputRef.current.value=null;inputRef.current.click();}},[dispatch,onFileDialogOpenCb,onFileDialogCancelCb,useFsAccessApi,setFiles,onErrCb,pickerTypes,multiple]);// Cb to open the file dialog when SPACE/ENTER occurs on the dropzone var onKeyDownCb=reactExports.useCallback(function(event){// Ignore keyboard events bubbling up the DOM tree if(!rootRef.current||!rootRef.current.isEqualNode(event.target)){return;}if(event.key===" "||event.key==="Enter"||event.keyCode===32||event.keyCode===13){event.preventDefault();openFileDialog();}},[rootRef,openFileDialog]);// Update focus state for the dropzone var onFocusCb=reactExports.useCallback(function(){dispatch({type:"focus"});},[]);var onBlurCb=reactExports.useCallback(function(){dispatch({type:"blur"});},[]);// Cb to open the file dialog when click occurs on the dropzone var onClickCb=reactExports.useCallback(function(){if(noClick){return;}// In IE11/Edge the file-browser dialog is blocking, therefore, use setTimeout() // to ensure React can handle state changes // See: https://github.com/react-dropzone/react-dropzone/issues/450 if(isIeOrEdge()){setTimeout(openFileDialog,0);}else {openFileDialog();}},[noClick,openFileDialog]);var composeHandler=function composeHandler(fn){return disabled?null:fn;};var composeKeyboardHandler=function composeKeyboardHandler(fn){return noKeyboard?null:composeHandler(fn);};var composeDragHandler=function composeDragHandler(fn){return noDrag?null:composeHandler(fn);};var stopPropagation=function stopPropagation(event){if(noDragEventsBubbling){event.stopPropagation();}};var getRootProps=reactExports.useMemo(function(){return function(){var _ref2=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{},_ref2$refKey=_ref2.refKey,refKey=_ref2$refKey===void 0?"ref":_ref2$refKey,role=_ref2.role,onKeyDown=_ref2.onKeyDown,onFocus=_ref2.onFocus,onBlur=_ref2.onBlur,onClick=_ref2.onClick,onDragEnter=_ref2.onDragEnter,onDragOver=_ref2.onDragOver,onDragLeave=_ref2.onDragLeave,onDrop=_ref2.onDrop,rest=_objectWithoutProperties(_ref2,_excluded3);return _objectSpread(_objectSpread(_defineProperty$1({onKeyDown:composeKeyboardHandler(composeEventHandlers(onKeyDown,onKeyDownCb)),onFocus:composeKeyboardHandler(composeEventHandlers(onFocus,onFocusCb)),onBlur:composeKeyboardHandler(composeEventHandlers(onBlur,onBlurCb)),onClick:composeHandler(composeEventHandlers(onClick,onClickCb)),onDragEnter:composeDragHandler(composeEventHandlers(onDragEnter,onDragEnterCb)),onDragOver:composeDragHandler(composeEventHandlers(onDragOver,onDragOverCb)),onDragLeave:composeDragHandler(composeEventHandlers(onDragLeave,onDragLeaveCb)),onDrop:composeDragHandler(composeEventHandlers(onDrop,onDropCb)),role:typeof role==="string"&&role!==""?role:"presentation"},refKey,rootRef),!disabled&&!noKeyboard?{tabIndex:0}:{}),rest);};},[rootRef,onKeyDownCb,onFocusCb,onBlurCb,onClickCb,onDragEnterCb,onDragOverCb,onDragLeaveCb,onDropCb,noKeyboard,noDrag,disabled]);var onInputElementClick=reactExports.useCallback(function(event){event.stopPropagation();},[]);var getInputProps=reactExports.useMemo(function(){return function(){var _ref3=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{},_ref3$refKey=_ref3.refKey,refKey=_ref3$refKey===void 0?"ref":_ref3$refKey,onChange=_ref3.onChange,onClick=_ref3.onClick,rest=_objectWithoutProperties(_ref3,_excluded4);var inputProps=_defineProperty$1({accept:acceptAttr,multiple:multiple,type:"file",style:{display:"none"},onChange:composeHandler(composeEventHandlers(onChange,onDropCb)),onClick:composeHandler(composeEventHandlers(onClick,onInputElementClick)),tabIndex:-1},refKey,inputRef);return _objectSpread(_objectSpread({},inputProps),rest);};},[inputRef,accept,multiple,onDropCb,disabled]);return _objectSpread(_objectSpread({},state),{},{isFocused:isFocused&&!disabled,getRootProps:getRootProps,getInputProps:getInputProps,rootRef:rootRef,inputRef:inputRef,open:composeHandler(openFileDialog)});}/** * @param {DropzoneState} state * @param {{type: string} & DropzoneState} action * @returns {DropzoneState} */function reducer(state,action){/* istanbul ignore next */switch(action.type){case"focus":return _objectSpread(_objectSpread({},state),{},{isFocused:true});case"blur":return _objectSpread(_objectSpread({},state),{},{isFocused:false});case"openDialog":return _objectSpread(_objectSpread({},initialState),{},{isFileDialogActive:true});case"closeDialog":return _objectSpread(_objectSpread({},state),{},{isFileDialogActive:false});case"setDraggedFiles":return _objectSpread(_objectSpread({},state),{},{isDragActive:action.isDragActive,isDragAccept:action.isDragAccept,isDragReject:action.isDragReject});case"setFiles":return _objectSpread(_objectSpread({},state),{},{acceptedFiles:action.acceptedFiles,fileRejections:action.fileRejections});case"reset":return _objectSpread({},initialState);default:return state;}}function noop(){} var DefaultContext={color:undefined,size:undefined,className:undefined,style:undefined,attr:undefined};var IconContext=React.createContext&&/*#__PURE__*/React.createContext(DefaultContext); var __assign=window&&window.__assign||function(){__assign=Object.assign||function(t){for(var s,i=1,n=arguments.length;i (React.createElement("svg", Object.assign({}, props, { viewBox: "64 -65 897 897" }), React.createElement("g", null, React.createElement("path", { d: "M888 760v0v0v-753v0h-752v0v753v0h752zM888 832h-752q-30 0 -51 -21t-21 -51v-753q0 -29 21 -50.5t51 -21.5h753q29 0 50.5 21.5t21.5 50.5v753q0 30 -21.5 51t-51.5 21v0zM732 347h-442q-14 0 -25 10.5t-11 25.5v0q0 15 11 25.5t25 10.5h442q14 0 25 -10.5t11 -25.5v0\n q0 -15 -11 -25.5t-25 -10.5z" })))); const PlusSquareO = (props) => (React.createElement("svg", Object.assign({}, props, { viewBox: "64 -65 897 897" }), React.createElement("g", null, React.createElement("path", { d: "M888 760v0v0v-753v0h-752v0v753v0h752zM888 832h-752q-30 0 -51 -21t-21 -51v-753q0 -29 21 -50.5t51 -21.5h753q29 0 50.5 21.5t21.5 50.5v753q0 30 -21.5 51t-51.5 21v0zM732 420h-184v183q0 15 -10.5 25.5t-25.5 10.5v0q-14 0 -25 -10.5t-11 -25.5v-183h-184\n q-15 0 -25.5 -11t-10.5 -25v0q0 -15 10.5 -25.5t25.5 -10.5h184v-183q0 -15 11 -25.5t25 -10.5v0q15 0 25.5 10.5t10.5 25.5v183h184q15 0 25.5 10.5t10.5 25.5v0q0 14 -10.5 25t-25.5 11z" })))); const CloseSquareO = (props) => (React.createElement("svg", Object.assign({}, props, { viewBox: "64 -65 897 897" }), React.createElement("g", null, React.createElement("path", { d: "M717.5 589.5q-10.5 10.5 -25.5 10.5t-26 -10l-154 -155l-154 155q-11 10 -26 10t-25.5 -10.5t-10.5 -25.5t11 -25l154 -155l-154 -155q-11 -10 -11 -25t10.5 -25.5t25.5 -10.5t26 10l154 155l154 -155q11 -10 26 -10t25.5 10.5t10.5 25t-11 25.5l-154 155l154 155\n q11 10 11 25t-10.5 25.5zM888 760v0v0v-753v0h-752v0v753v0h752zM888 832h-752q-30 0 -51 -21t-21 -51v-753q0 -29 21 -50.5t51 -21.5h753q29 0 50.5 21.5t21.5 50.5v753q0 30 -21.5 51t-51.5 21v0z" })))); const LocationIcon = ``; const ZoomOutIcon = ``; const ZoomOutDoubleIcon = ``; const ZoomInIcon = ``; const SpaceIcon = ``; const getFolderIcon = (plugin, children, open) => { let setting = plugin.settings.folderIcon; let OpenFolderIcon = MinusSquareO; let InactiveOpenFolderIcon = CloseSquareO; let ClosedFolderIcon = PlusSquareO; if (setting === 'box-folder') { OpenFolderIcon = BiFolderMinus; InactiveOpenFolderIcon = BiFolder; ClosedFolderIcon = BiFolderPlus; } else if (setting === 'icomoon') { OpenFolderIcon = ImFolderMinus; InactiveOpenFolderIcon = ImFolder; ClosedFolderIcon = ImFolderPlus; } else if (setting === 'typicon') { OpenFolderIcon = TiFolderOpen; InactiveOpenFolderIcon = TiFolder; ClosedFolderIcon = TiFolder; } else if (setting === 'circle-gg') { OpenFolderIcon = CgRemove; InactiveOpenFolderIcon = CgCloseO; ClosedFolderIcon = CgAdd; } const Icon = children ? (open ? OpenFolderIcon : ClosedFolderIcon) : InactiveOpenFolderIcon; return Icon; }; var _createClass=function(){function defineProperties(target,props){for(var i=0;i1?_len2-1:0),_key2=1;_key2<_len2;_key2++){expressions[_key2-1]=arguments[_key2];}if(typeof strings==='function'){// if the first argument passed is a function, assume it is a template tag and return // an intermediary tag that processes the template using the aforementioned tag, passing the // result to our tag return _this.interimTag.bind(_this,strings);}if(typeof strings==='string'){// if the first argument passed is a string, just transform it return _this.transformEndResult(strings);}// else, return a transformed end result of processing the template with our tag strings=strings.map(_this.transformString.bind(_this));return _this.transformEndResult(strings.reduce(_this.processSubstitutions.bind(_this,expressions)));};// if first argument is an array, extrude it as a list of transformers if(transformers.length>0&&Array.isArray(transformers[0])){transformers=transformers[0];}// if any transformers are functions, this means they are not initiated - automatically initiate them this.transformers=transformers.map(function(transformer){return typeof transformer==='function'?transformer():transformer;});// return an ES2015 template tag return this.tag;}/** * Applies all transformers to a template literal tagged with this method. * If a function is passed as the first argument, assumes the function is a template tag * and applies it to the template, returning a template tag. * @param {(Function|String|Array)} strings - Either a template tag or an array containing template strings separated by identifier * @param {...*} ...expressions - Optional list of substitution values. * @return {(String|Function)} - Either an intermediary tag function or the results of processing the template. */_createClass(TemplateTag,[{key:'interimTag',/** * An intermediary template tag that receives a template tag and passes the result of calling the template with the received * template tag to our own template tag. * @param {Function} nextTag - the received template tag * @param {Array} template - the template to process * @param {...*} ...substitutions - `substitutions` is an array of all substitutions in the template * @return {*} - the final processed value */value:function interimTag(previousTag,template){for(var _len3=arguments.length,substitutions=Array(_len3>2?_len3-2:0),_key3=2;_key3<_len3;_key3++){substitutions[_key3-2]=arguments[_key3];}return this.tag(_templateObject,previousTag.apply(undefined,[template].concat(substitutions)));}/** * Performs bulk processing on the tagged template, transforming each substitution and then * concatenating the resulting values into a string. * @param {Array<*>} substitutions - an array of all remaining substitutions present in this template * @param {String} resultSoFar - this iteration's result string so far * @param {String} remainingPart - the template chunk after the current substitution * @return {String} - the result of joining this iteration's processed substitution with the result */},{key:'processSubstitutions',value:function processSubstitutions(substitutions,resultSoFar,remainingPart){var substitution=this.transformSubstitution(substitutions.shift(),resultSoFar);return ''.concat(resultSoFar,substitution,remainingPart);}/** * Iterate through each transformer, applying the transformer's `onString` method to the template * strings before all substitutions are processed. * @param {String} str - The input string * @return {String} - The final results of processing each transformer */},{key:'transformString',value:function transformString(str){var cb=function cb(res,transform){return transform.onString?transform.onString(res):res;};return this.transformers.reduce(cb,str);}/** * When a substitution is encountered, iterates through each transformer and applies the transformer's * `onSubstitution` method to the substitution. * @param {*} substitution - The current substitution * @param {String} resultSoFar - The result up to and excluding this substitution. * @return {*} - The final result of applying all substitution transformations. */},{key:'transformSubstitution',value:function transformSubstitution(substitution,resultSoFar){var cb=function cb(res,transform){return transform.onSubstitution?transform.onSubstitution(res,resultSoFar):res;};return this.transformers.reduce(cb,substitution);}/** * Iterates through each transformer, applying the transformer's `onEndResult` method to the * template literal after all substitutions have finished processing. * @param {String} endResult - The processed template, just before it is returned from the tag * @return {String} - The final results of processing each transformer */},{key:'transformEndResult',value:function transformEndResult(endResult){var cb=function cb(res,transform){return transform.onEndResult?transform.onEndResult(res):res;};return this.transformers.reduce(cb,endResult);}}]);return TemplateTag;}(); /** * TemplateTag transformer that trims whitespace on the end result of a tagged template * @param {String} side = '' - The side of the string to trim. Can be 'start' or 'end' (alternatively 'left' or 'right') * @return {Object} - a TemplateTag transformer */var trimResultTransformer=function trimResultTransformer(){var side=arguments.length>0&&arguments[0]!==undefined?arguments[0]:'';return {onEndResult:function onEndResult(endResult){if(side===''){return endResult.trim();}side=side.toLowerCase();if(side==='start'||side==='left'){return endResult.replace(/^\s*/,'');}if(side==='end'||side==='right'){return endResult.replace(/\s*$/,'');}throw new Error('Side not supported: '+side);}};}; function _toConsumableArray(arr){if(Array.isArray(arr)){for(var i=0,arr2=Array(arr.length);i0&&arguments[0]!==undefined?arguments[0]:'initial';return {onEndResult:function onEndResult(endResult){if(type==='initial'){// remove the shortest leading indentation from each line var match=endResult.match(/^[^\S\n]*(?=\S)/gm);var indent=match&&Math.min.apply(Math,_toConsumableArray(match.map(function(el){return el.length;})));if(indent){var regexp=new RegExp('^.{'+indent+'}','gm');return endResult.replace(regexp,'');}return endResult;}if(type==='all'){// remove all indentation from each line return endResult.replace(/^[^\S\n]+/gm,'');}throw new Error('Unknown type: '+type);}};}; /** * Replaces tabs, newlines and spaces with the chosen value when they occur in sequences * @param {(String|RegExp)} replaceWhat - the value or pattern that should be replaced * @param {*} replaceWith - the replacement value * @return {Object} - a TemplateTag transformer */var replaceResultTransformer=function replaceResultTransformer(replaceWhat,replaceWith){return {onEndResult:function onEndResult(endResult){if(replaceWhat==null||replaceWith==null){throw new Error('replaceResultTransformer requires at least 2 arguments.');}return endResult.replace(replaceWhat,replaceWith);}};}; var replaceSubstitutionTransformer=function replaceSubstitutionTransformer(replaceWhat,replaceWith){return {onSubstitution:function onSubstitution(substitution,resultSoFar){if(replaceWhat==null||replaceWith==null){throw new Error('replaceSubstitutionTransformer requires at least 2 arguments.');}// Do not touch if null or undefined if(substitution==null){return substitution;}else {return substitution.toString().replace(replaceWhat,replaceWith);}}};}; var defaults={separator:'',conjunction:'',serial:false};/** * Converts an array substitution to a string containing a list * @param {String} [opts.separator = ''] - the character that separates each item * @param {String} [opts.conjunction = ''] - replace the last separator with this * @param {Boolean} [opts.serial = false] - include the separator before the conjunction? (Oxford comma use-case) * * @return {Object} - a TemplateTag transformer */var inlineArrayTransformer=function inlineArrayTransformer(){var opts=arguments.length>0&&arguments[0]!==undefined?arguments[0]:defaults;return {onSubstitution:function onSubstitution(substitution,resultSoFar){// only operate on arrays if(Array.isArray(substitution)){var arrayLength=substitution.length;var separator=opts.separator;var conjunction=opts.conjunction;var serial=opts.serial;// join each item in the array into a string where each item is separated by separator // be sure to maintain indentation var indent=resultSoFar.match(/(\n?[^\S\n]+)$/);if(indent){substitution=substitution.join(separator+indent[1]);}else {substitution=substitution.join(separator+' ');}// if conjunction is set, replace the last separator with conjunction, but only if there is more than one substitution if(conjunction&&arrayLength>1){var separatorIndex=substitution.lastIndexOf(separator);substitution=substitution.slice(0,separatorIndex)+(serial?separator:'')+' '+conjunction+substitution.slice(separatorIndex+1);}}return substitution;}};}; var splitStringTransformer=function splitStringTransformer(splitBy){return {onSubstitution:function onSubstitution(substitution,resultSoFar){if(splitBy!=null&&typeof splitBy==='string'){if(typeof substitution==='string'&&substitution.includes(splitBy)){substitution=substitution.split(splitBy);}}else {throw new Error('You need to specify a string character to split by.');}return substitution;}};}; var isValidValue=function isValidValue(x){return x!=null&&!Number.isNaN(x)&&typeof x!=='boolean';};var removeNonPrintingValuesTransformer=function removeNonPrintingValuesTransformer(){return {onSubstitution:function onSubstitution(substitution){if(Array.isArray(substitution)){return substitution.filter(isValidValue);}if(isValidValue(substitution)){return substitution;}return '';}};}; new TemplateTag(inlineArrayTransformer({separator:','}),stripIndentTransformer,trimResultTransformer); new TemplateTag(inlineArrayTransformer({separator:',',conjunction:'and'}),stripIndentTransformer,trimResultTransformer); new TemplateTag(inlineArrayTransformer({separator:',',conjunction:'or'}),stripIndentTransformer,trimResultTransformer); new TemplateTag(splitStringTransformer('\n'),removeNonPrintingValuesTransformer,inlineArrayTransformer,stripIndentTransformer,trimResultTransformer); new TemplateTag(splitStringTransformer('\n'),inlineArrayTransformer,stripIndentTransformer,trimResultTransformer,replaceSubstitutionTransformer(/&/g,'&'),replaceSubstitutionTransformer(//g,'>'),replaceSubstitutionTransformer(/"/g,'"'),replaceSubstitutionTransformer(/'/g,'''),replaceSubstitutionTransformer(/`/g,'`')); new TemplateTag(replaceResultTransformer(/(?:\n(?:\s*))+/g,' '),trimResultTransformer); new TemplateTag(replaceResultTransformer(/(?:\n\s*)/g,''),trimResultTransformer); new TemplateTag(inlineArrayTransformer({separator:','}),replaceResultTransformer(/(?:\s+)/g,' '),trimResultTransformer); new TemplateTag(inlineArrayTransformer({separator:',',conjunction:'or'}),replaceResultTransformer(/(?:\s+)/g,' '),trimResultTransformer); new TemplateTag(inlineArrayTransformer({separator:',',conjunction:'and'}),replaceResultTransformer(/(?:\s+)/g,' '),trimResultTransformer); new TemplateTag(inlineArrayTransformer,stripIndentTransformer,trimResultTransformer); new TemplateTag(inlineArrayTransformer,replaceResultTransformer(/(?:\s+)/g,' '),trimResultTransformer); new TemplateTag(stripIndentTransformer,trimResultTransformer); var stripIndents=new TemplateTag(stripIndentTransformer('all'),trimResultTransformer); var dayjs_min = {exports: {}}; (function (module, exports) { !function(t,e){module.exports=e();}(commonjsGlobal,function(){var t=1e3,e=6e4,n=36e5,r="millisecond",i="second",s="minute",u="hour",a="day",o="week",c="month",f="quarter",h="year",d="date",l="Invalid Date",$=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,y=/\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,M={name:"en",weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),ordinal:function(t){var e=["th","st","nd","rd"],n=t%100;return "["+t+(e[(n-20)%10]||e[n]||e[0])+"]";}},m=function(t,e,n){var r=String(t);return !r||r.length>=e?t:""+Array(e+1-r.length).join(n)+t;},v={s:m,z:function(t){var e=-t.utcOffset(),n=Math.abs(e),r=Math.floor(n/60),i=n%60;return (e<=0?"+":"-")+m(r,2,"0")+":"+m(i,2,"0");},m:function t(e,n){if(e.date()1)return t(u[0]);}else {var a=e.name;D[a]=e,i=a;}return !r&&i&&(g=i),i||!r&&g;},O=function(t,e){if(S(t))return t.clone();var n="object"==typeof e?e:{};return n.date=t,n.args=arguments,new _(n);},b=v;b.l=w,b.i=S,b.w=function(t,e){return O(t,{locale:e.$L,utc:e.$u,x:e.$x,$offset:e.$offset});};var _=function(){function M(t){this.$L=w(t.locale,null,!0),this.parse(t),this.$x=this.$x||t.x||{},this[p]=!0;}var m=M.prototype;return m.parse=function(t){this.$d=function(t){var e=t.date,n=t.utc;if(null===e)return new Date(NaN);if(b.u(e))return new Date();if(e instanceof Date)return new Date(e);if("string"==typeof e&&!/Z$/i.test(e)){var r=e.match($);if(r){var i=r[2]-1||0,s=(r[7]||"0").substring(0,3);return n?new Date(Date.UTC(r[1],i,r[3]||1,r[4]||0,r[5]||0,r[6]||0,s)):new Date(r[1],i,r[3]||1,r[4]||0,r[5]||0,r[6]||0,s);}}return new Date(e);}(t),this.init();},m.init=function(){var t=this.$d;this.$y=t.getFullYear(),this.$M=t.getMonth(),this.$D=t.getDate(),this.$W=t.getDay(),this.$H=t.getHours(),this.$m=t.getMinutes(),this.$s=t.getSeconds(),this.$ms=t.getMilliseconds();},m.$utils=function(){return b;},m.isValid=function(){return !(this.$d.toString()===l);},m.isSame=function(t,e){var n=O(t);return this.startOf(e)<=n&&n<=this.endOf(e);},m.isAfter=function(t,e){return O(t) { const { file, app, newLeaf, leafBySplit } = props; let fileToOpen = app.vault.getAbstractFileByPath(file.path); if (!fileToOpen) return; let leaf = app.workspace.getLeaf(newLeaf); if (leafBySplit) leaf = app.workspace.createLeafBySplit(leaf, 'vertical'); app.workspace.setActiveLeaf(leaf, { focus: true, }); leaf.openFile(fileToOpen, { eState: { focus: true } }); }; const getFileCreateString = (params) => { const { plugin, fileName } = params; return stripIndents ` ${plugin.settings.createdYaml ? ` --- created: ${dayjs(new Date()).format('YYYY-MM-DD hh:mm:ss')} --- ` : ''} ${plugin.settings.fileNameIsHeader ? `# ${fileName}` : ''} `; }; const createNewMarkdownFile = (plugin, folder, newFileName, content) => __awaiter(void 0, void 0, void 0, function* () { // @ts-ignore const newFile = yield plugin.app.fileManager.createNewMarkdownFile(folder, newFileName); if (content && content !== '') yield plugin.app.vault.modify(newFile, content); openFile$1({ file: newFile, app: plugin.app, newLeaf: false }); let evt = new CustomEvent(eventTypes.activeFileChange, { detail: { filePath: newFile.path } }); window.dispatchEvent(evt); }); const openFileInNewTab = (app, file) => { openFile$1({ file: file, app: app, newLeaf: true }); }; const openFileInNewTabGroup = (app, file) => { openFile$1({ file: file, app: app, newLeaf: false, leafBySplit: true }); }; class ConfirmationModal extends obsidian.Modal { constructor(plugin, confirmationNote, callBackAfterConfirmation) { super(plugin.app); this.confirmationNote = confirmationNote; this.callBackAfterConfirmation = callBackAfterConfirmation; this.plugin = plugin; } onOpen() { let { contentEl } = this; let confirmationModal = this; const headerEl = contentEl.createEl('div', { text: this.confirmationNote }); headerEl.addClass('modal-title'); this.confirmButton = contentEl.createEl('button', { text: 'Confirm' }); const cancelButton = contentEl.createEl('button', { text: 'Cancel' }); cancelButton.style.cssText = 'float: right;'; cancelButton.addEventListener('click', () => { confirmationModal.close(); }); // Create Button Action and Assign to the Global Variable of the class this.onConfirmClickAction = (e) => { this.callBackAfterConfirmation(); this.close(); }; // Assign the event listener this.confirmButton.addEventListener('click', this.onConfirmClickAction); } onClose() { let { contentEl } = this; contentEl.empty(); this.confirmButton.removeEventListener('click', this.onConfirmClickAction); } } class VaultChangeModal extends obsidian.Modal { constructor(plugin, file, action) { super(plugin.app); this.file = file; this.action = action; this.plugin = plugin; } onOpen() { let { contentEl } = this; let myModal = this; // Header let headerText; if (this.action === 'rename') { headerText = 'Rename: Provide a New Name'; } else if (this.action === 'create folder') { headerText = 'Create Folder: Provide Name'; } else if (this.action === 'create note') { headerText = 'Create Note: Provide Name'; } const headerEl = contentEl.createEl('div', { text: headerText }); headerEl.addClass('modal-title'); // Input El const inputEl = contentEl.createEl('input'); inputEl.style.cssText = 'width: 100%; height: 2.5em; margin-bottom: 15px;'; if (this.action === 'rename') { // Manual Rename Handler For md Files if (this.file.path.endsWith('.md')) { if (this.file instanceof obsidian.TFolder || this.file instanceof obsidian.TAbstractFile) { inputEl.value = this.file.name.substring(0, this.file.name.lastIndexOf('.')); } else { inputEl.value = this.file.basename; } } else { if (this.file instanceof obsidian.TFolder || this.file instanceof obsidian.TAbstractFile) { inputEl.value = this.file.name; } else { inputEl.value = this.file.basename; } } } else if (this.action === 'create note' || this.action === 'create folder') { inputEl.value = 'Untitled'; inputEl.select(); } inputEl.focus(); // Buttons let changeButtonText; if (this.action === 'rename') { changeButtonText = 'Change Name'; } else if (this.action === 'create folder') { changeButtonText = 'Create Folder'; } else if (this.action === 'create note') { changeButtonText = 'Create Note'; } const changeButton = contentEl.createEl('button', { text: changeButtonText }); const cancelButton = contentEl.createEl('button', { text: 'Cancel' }); cancelButton.style.cssText = 'float: right;'; cancelButton.addEventListener('click', () => { myModal.close(); }); const onClickAction = () => __awaiter(this, void 0, void 0, function* () { let newName = inputEl.value; if (this.action === 'rename') { // Manual Rename Handler For md Files if (this.file.path.endsWith('.md')) { newName = newName + '.' + this.file.path.slice(this.file.path.lastIndexOf('.') + 1); } // Folder Note files to be updated if (this.file instanceof obsidian.TFolder && this.plugin.settings.folderNote) { let folderNoteFile = this.app.vault.getAbstractFileByPath(this.file.path + '/' + this.file.name + '.md'); if (folderNoteFile) this.app.fileManager.renameFile(folderNoteFile, this.file.path + '/' + newName + '.md'); } // Rename the destination file/folder name this.app.fileManager.renameFile(this.file instanceof obsidian.TFolder || this.file instanceof obsidian.TAbstractFile ? this.file : this.plugin.app.vault.getAbstractFileByPath(this.file.path), this.file.parent.path + '/' + newName); } else if (this.action === 'create folder') { this.app.vault.createFolder(this.file.path + '/' + newName); } else if (this.action === 'create note') { yield createNewMarkdownFile(this.plugin, this.file, newName, this.plugin.settings.createdYaml ? getFileCreateString({ plugin: this.plugin, fileName: newName }) : ''); } myModal.close(); }); // Event Listener changeButton.addEventListener('click', onClickAction); inputEl.addEventListener('keydown', (e) => { if (e.key === 'Enter') onClickAction(); }); } onClose() { let { contentEl } = this; contentEl.empty(); } } class MoveSuggestionModal extends obsidian.FuzzySuggestModal { constructor(app, fileOrFolderToMove) { super(app); this.fileOrFolderToMove = fileOrFolderToMove; } getItemText(item) { return item.path; } getItems() { return getAllFoldersInVault(this.app); } onChooseItem(item, evt) { let fileToRename = this.app.vault.getAbstractFileByPath(item.path); if (fileToRename) { this.app.vault.rename(fileToRename, item.path + '/' + fileToRename.name); } } } function getAllFoldersInVault(app) { let folders = []; let rootFolder = app.vault.getRoot(); folders.push(rootFolder); function recursiveFx(folder) { for (let child of folder.children) { if (child instanceof obsidian.TFolder) { let childFolder = child; folders.push(childFolder); if (childFolder.children) recursiveFx(childFolder); } } } recursiveFx(rootFolder); return folders; } // Helper Function To Get List of Files const getFilesUnderPath = (params) => { const { path, plugin, getAllFiles, excludedExtensions, excludedFolders } = params; var filesUnderPath = []; var showFilesFromSubFolders = getAllFiles ? true : plugin.settings.showFilesFromSubFolders; var folderObj = plugin.app.vault.getAbstractFileByPath(path); recursiveFx(folderObj, plugin.app); function recursiveFx(folderObj, app) { if (folderObj instanceof obsidian.TFolder && folderObj.children) { for (let child of folderObj.children) { if (child instanceof obsidian.TFile) { if (excludedExtensions.includes(child.extension) || (plugin.settings.hideAttachments && child.path.toLowerCase().includes(plugin.settings.attachmentsFolderName.toLowerCase())) || excludedFolders.includes(child.parent.path)) continue; filesUnderPath.push(TFile2OZFile(child)); } if (child instanceof obsidian.TFolder && showFilesFromSubFolders) recursiveFx(child); } } } return filesUnderPath; }; // Converted from TFile to OZFile const TFile2OZFile = (t) => { return { path: t.path, basename: t.basename, extension: t.extension, stat: { mtime: t.stat.mtime, ctime: t.stat.ctime, size: t.stat.size, }, parent: { path: t.parent.path, }, isFolderNote: isFolderNote(t), }; }; // Check if the file is a folder note const isFolderNote = (t) => { return t.extension === 'md' && t.basename === t.parent.name; }; // Helper Function to Create Folder Tree const createFolderTree = (params) => { const { startFolder, excludedFolders, plugin } = params; let fileTree = { folder: startFolder, children: [] }; function recursive(folder, object) { if (!(folder && folder.children)) return; for (let child of folder.children) { if (child instanceof obsidian.TFolder) { let childFolder = child; if ((plugin.settings.hideAttachments && childFolder.name === plugin.settings.attachmentsFolderName) || (excludedFolders.length > 0 && excludedFolders.contains(child.path))) { continue; } let newObj = { folder: childFolder, children: [] }; object.children.push(newObj); if (childFolder.children) recursive(childFolder, newObj); } } } recursive(startFolder, fileTree); return fileTree; }; // Create Folder File Count Map const getFolderNoteCountMap = (plugin) => { const counts = {}; let files; if (plugin.settings.folderCountOption === 'notes') { files = plugin.app.vault.getMarkdownFiles(); } else { files = plugin.app.vault.getFiles(); } // Filter Folder Note Files if (plugin.settings.folderNote) { files = files.filter((f) => f.extension !== 'md' || (f.extension === 'md' && f.basename !== f.parent.name)); } files.forEach((file) => { for (let folder = file.parent; folder != null; folder = folder.parent) { // -> Create object if doesn't exist if (!counts[folder.path]) counts[folder.path] = { open: 0, closed: 0 }; // -> Create number for open state if (folder == file.parent) counts[folder.path].open = 1 + counts[folder.path].open; // -> Create number for closed state counts[folder.path].closed = 1 + counts[folder.path].closed; } }); return counts; }; // Check if folder has child folder const hasChildFolder = (folder) => { let children = folder.children; for (let child of children) { if (child instanceof obsidian.TFolder) return true; } return false; }; // Files out of Md should be listed with extension badge - Md without extension const getFileNameAndExtension = (fullName) => { var index = fullName.lastIndexOf('.'); return { fileName: fullName.substring(0, index), extension: fullName.substring(index + 1), }; }; // Extracts the Folder Name from the Full Folder Path const getFolderName = (folderPath, app) => { if (folderPath === '/') return app.vault.getName(); let index = folderPath.lastIndexOf('/'); if (index !== -1) return folderPath.substring(index + 1); return folderPath; }; const internalPluginLoaded = (pluginName, app) => { var _a; // @ts-ignore return (_a = app.internalPlugins.plugins[pluginName]) === null || _a === void 0 ? void 0 : _a._loaded; }; const pluginIsLoaded = (app, pluginId) => { // @ts-ignore return app.plugins.getPlugin(pluginId); }; const createNewFile = (e, folderPath, plugin) => __awaiter(void 0, void 0, void 0, function* () { let targetFolder = plugin.app.vault.getAbstractFileByPath(folderPath); if (!targetFolder) return; let modal = new VaultChangeModal(plugin, targetFolder, 'create note'); modal.open(); }); const getBookmarksPluginItems = () => { return app.internalPlugins.plugins['bookmarks'].instance.items; }; const getBookmarkTitle = (title) => { let bookmarkItems = getBookmarksPluginItems(); let titleParts = title.split('/'); let currentItem = bookmarkItems.find((b) => b.title === titleParts[0]); for (let i = 1; i < titleParts.length; i++) { currentItem = currentItem.items.find((b) => b.title === titleParts[i]); } return currentItem; }; /** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format * @oncall recoil */function err(message){const error=new Error(message);// In V8, Error objects keep the closure scope chain alive until the // err.stack property is accessed. if(error.stack===undefined){// IE sets the stack only if error is thrown try{throw error;}catch(_){}// eslint-disable-line fb-www/no-unused-catch-bindings, no-empty }return error;}var err_1=err;// @oss-only var Recoil_err=err_1;/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format * @oncall recoil */ // Split declaration and implementation to allow this function to pretend to // check for actual instance of Promise instead of something with a `then` // method. // eslint-disable-next-line no-redeclare function isPromise(p){return !!p&&typeof p.then==='function';}var Recoil_isPromise=isPromise;function nullthrows(x,message){if(x!=null){return x;}throw Recoil_err(message!==null&&message!==void 0?message:'Got unexpected null or undefined');}var Recoil_nullthrows=nullthrows;function _defineProperty(obj,key,value){if(key in obj){Object.defineProperty(obj,key,{value:value,enumerable:true,configurable:true,writable:true});}else {obj[key]=value;}return obj;}class BaseLoadable{getValue(){throw Recoil_err('BaseLoadable');}toPromise(){throw Recoil_err('BaseLoadable');}valueMaybe(){throw Recoil_err('BaseLoadable');}valueOrThrow(){// $FlowFixMe[prop-missing] throw Recoil_err(`Loadable expected value, but in "${this.state}" state`);}promiseMaybe(){throw Recoil_err('BaseLoadable');}promiseOrThrow(){// $FlowFixMe[prop-missing] throw Recoil_err(`Loadable expected promise, but in "${this.state}" state`);}errorMaybe(){throw Recoil_err('BaseLoadable');}errorOrThrow(){// $FlowFixMe[prop-missing] throw Recoil_err(`Loadable expected error, but in "${this.state}" state`);}is(other){// $FlowFixMe[prop-missing] return other.state===this.state&&other.contents===this.contents;}map(_map){throw Recoil_err('BaseLoadable');}}class ValueLoadable extends BaseLoadable{constructor(value){super();_defineProperty(this,"state",'hasValue');_defineProperty(this,"contents",void 0);this.contents=value;}getValue(){return this.contents;}toPromise(){return Promise.resolve(this.contents);}valueMaybe(){return this.contents;}valueOrThrow(){return this.contents;}promiseMaybe(){return undefined;}errorMaybe(){return undefined;}map(map){try{const next=map(this.contents);return Recoil_isPromise(next)?loadableWithPromise(next):isLoadable(next)?next:loadableWithValue(next);}catch(e){return Recoil_isPromise(e)?// If we "suspended", then try again. // errors and subsequent retries will be handled in 'loading' case // $FlowFixMe[prop-missing] loadableWithPromise(e.next(()=>this.map(map))):loadableWithError(e);}}}class ErrorLoadable extends BaseLoadable{constructor(error){super();_defineProperty(this,"state",'hasError');_defineProperty(this,"contents",void 0);this.contents=error;}getValue(){throw this.contents;}toPromise(){return Promise.reject(this.contents);}valueMaybe(){return undefined;}promiseMaybe(){return undefined;}errorMaybe(){return this.contents;}errorOrThrow(){return this.contents;}map(_map){// $FlowIssue[incompatible-return] return this;}}class LoadingLoadable extends BaseLoadable{constructor(promise){super();_defineProperty(this,"state",'loading');_defineProperty(this,"contents",void 0);this.contents=promise;}getValue(){throw this.contents;}toPromise(){return this.contents;}valueMaybe(){return undefined;}promiseMaybe(){return this.contents;}promiseOrThrow(){return this.contents;}errorMaybe(){return undefined;}map(map){return loadableWithPromise(this.contents.then(value=>{const next=map(value);if(isLoadable(next)){const nextLoadable=next;switch(nextLoadable.state){case'hasValue':return nextLoadable.contents;case'hasError':throw nextLoadable.contents;case'loading':return nextLoadable.contents;}}// $FlowIssue[incompatible-return] return next;})// $FlowFixMe[incompatible-call] .catch(e=>{if(Recoil_isPromise(e)){// we were "suspended," try again return e.then(()=>this.map(map).contents);}throw e;}));}}function loadableWithValue(value){return Object.freeze(new ValueLoadable(value));}function loadableWithError(error){return Object.freeze(new ErrorLoadable(error));}function loadableWithPromise(promise){return Object.freeze(new LoadingLoadable(promise));}function loadableLoading(){return Object.freeze(new LoadingLoadable(new Promise(()=>{})));}function loadableAllArray(inputs){return inputs.every(i=>i.state==='hasValue')?loadableWithValue(inputs.map(i=>i.contents)):inputs.some(i=>i.state==='hasError')?loadableWithError(Recoil_nullthrows(inputs.find(i=>i.state==='hasError'),'Invalid loadable passed to loadableAll').contents):loadableWithPromise(Promise.all(inputs.map(i=>i.contents)));}function loadableAll(inputs){const unwrapedInputs=Array.isArray(inputs)?inputs:Object.getOwnPropertyNames(inputs).map(key=>inputs[key]);const normalizedInputs=unwrapedInputs.map(x=>isLoadable(x)?x:Recoil_isPromise(x)?loadableWithPromise(x):loadableWithValue(x));const output=loadableAllArray(normalizedInputs);return Array.isArray(inputs)?// $FlowIssue[incompatible-return] output:// Object.getOwnPropertyNames() has consistent key ordering with ES6 // $FlowIssue[incompatible-call] output.map(outputs=>Object.getOwnPropertyNames(inputs).reduce(// $FlowFixMe[invalid-computed-prop] (out,key,idx)=>({...out,[key]:outputs[idx]}),{}));}function isLoadable(x){return x instanceof BaseLoadable;}const LoadableStaticInterface={of:value=>Recoil_isPromise(value)?loadableWithPromise(value):isLoadable(value)?value:loadableWithValue(value),error:error=>loadableWithError(error),// $FlowIssue[incompatible-return] loading:()=>loadableLoading(),// $FlowIssue[unclear-type] all:loadableAll,isLoadable};var Recoil_Loadable={loadableWithValue,loadableWithError,loadableWithPromise,loadableLoading,loadableAll,isLoadable,RecoilLoadable:LoadableStaticInterface};var Recoil_Loadable_1=Recoil_Loadable.loadableWithValue;var Recoil_Loadable_2=Recoil_Loadable.loadableWithError;var Recoil_Loadable_3=Recoil_Loadable.loadableWithPromise;var Recoil_Loadable_4=Recoil_Loadable.loadableLoading;var Recoil_Loadable_5=Recoil_Loadable.loadableAll;var Recoil_Loadable_6=Recoil_Loadable.isLoadable;var Recoil_Loadable_7=Recoil_Loadable.RecoilLoadable;var Recoil_Loadable$1=/*#__PURE__*/Object.freeze({__proto__:null,loadableWithValue:Recoil_Loadable_1,loadableWithError:Recoil_Loadable_2,loadableWithPromise:Recoil_Loadable_3,loadableLoading:Recoil_Loadable_4,loadableAll:Recoil_Loadable_5,isLoadable:Recoil_Loadable_6,RecoilLoadable:Recoil_Loadable_7});const env={RECOIL_DUPLICATE_ATOM_KEY_CHECKING_ENABLED:true,// Note: RECOIL_GKS_ENABLED settings will only be honored in OSS builds of Recoil RECOIL_GKS_ENABLED:new Set(['recoil_hamt_2020','recoil_sync_external_store','recoil_suppress_rerender_in_callback','recoil_memory_managament_2020'])};function readProcessEnvBooleanFlag(name,set){var _process$env$name,_process$env$name$toL;const sanitizedValue=(_process$env$name=process.env[name])===null||_process$env$name===void 0?void 0:(_process$env$name$toL=_process$env$name.toLowerCase())===null||_process$env$name$toL===void 0?void 0:_process$env$name$toL.trim();if(sanitizedValue==null||sanitizedValue===''){return;}const allowedValues=['true','false'];if(!allowedValues.includes(sanitizedValue)){throw Recoil_err(`process.env.${name} value must be 'true', 'false', or empty: ${sanitizedValue}`);}set(sanitizedValue==='true');}function readProcessEnvStringArrayFlag(name,set){var _process$env$name2;const sanitizedValue=(_process$env$name2=process.env[name])===null||_process$env$name2===void 0?void 0:_process$env$name2.trim();if(sanitizedValue==null||sanitizedValue===''){return;}set(sanitizedValue.split(/\s*,\s*|\s+/));}/** * Allow NodeJS/NextJS/etc to set the initial state through process.env variable * Note: we don't assume 'process' is available in all runtime environments * * @see https://github.com/facebookexperimental/Recoil/issues/733 */function applyProcessEnvFlagOverrides(){var _process;// note: this check is needed in addition to the check below, runtime error will occur without it! // eslint-disable-next-line fb-www/typeof-undefined if(typeof process==='undefined'){return;}if(((_process=process)===null||_process===void 0?void 0:_process.env)==null){return;}readProcessEnvBooleanFlag('RECOIL_DUPLICATE_ATOM_KEY_CHECKING_ENABLED',value=>{env.RECOIL_DUPLICATE_ATOM_KEY_CHECKING_ENABLED=value;});readProcessEnvStringArrayFlag('RECOIL_GKS_ENABLED',value=>{value.forEach(gk=>{env.RECOIL_GKS_ENABLED.add(gk);});});}applyProcessEnvFlagOverrides();var Recoil_RecoilEnv=env;function Recoil_gkx_OSS(gk){return Recoil_RecoilEnv.RECOIL_GKS_ENABLED.has(gk);}Recoil_gkx_OSS.setPass=gk=>{Recoil_RecoilEnv.RECOIL_GKS_ENABLED.add(gk);};Recoil_gkx_OSS.setFail=gk=>{Recoil_RecoilEnv.RECOIL_GKS_ENABLED.delete(gk);};Recoil_gkx_OSS.clear=()=>{Recoil_RecoilEnv.RECOIL_GKS_ENABLED.clear();};var Recoil_gkx=Recoil_gkx_OSS;// @oss-only /** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format * @oncall recoil */function recoverableViolation(message,_projectName,{error}={}){return null;}var recoverableViolation_1=recoverableViolation;// @oss-only var Recoil_recoverableViolation=recoverableViolation_1;var _createMutableSource,_useMutableSource,_useSyncExternalStore;const createMutableSource=// flowlint-next-line unclear-type:off (_createMutableSource=React.createMutableSource)!==null&&_createMutableSource!==void 0?_createMutableSource:React.unstable_createMutableSource;const useMutableSource=// flowlint-next-line unclear-type:off (_useMutableSource=React.useMutableSource)!==null&&_useMutableSource!==void 0?_useMutableSource:React.unstable_useMutableSource;// https://github.com/reactwg/react-18/discussions/86 const useSyncExternalStore=// flowlint-next-line unclear-type:off (_useSyncExternalStore=React.useSyncExternalStore)!==null&&_useSyncExternalStore!==void 0?_useSyncExternalStore:// flowlint-next-line unclear-type:off React.unstable_useSyncExternalStore;// Since React goes through a proxy dispatcher and the current renderer can // change we can't simply check if `React.useSyncExternalStore()` is defined. function currentRendererSupportsUseSyncExternalStore(){var _ReactCurrentDispatch;// $FlowFixMe[incompatible-use] const{ReactCurrentDispatcher,ReactCurrentOwner}=/* $FlowFixMe[prop-missing] This workaround was approved as a safer mechanism * to detect if the current renderer supports useSyncExternalStore() * https://fb.workplace.com/groups/reactjs/posts/9558682330846963/ */React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;const dispatcher=(_ReactCurrentDispatch=ReactCurrentDispatcher===null||ReactCurrentDispatcher===void 0?void 0:ReactCurrentDispatcher.current)!==null&&_ReactCurrentDispatch!==void 0?_ReactCurrentDispatch:ReactCurrentOwner.currentDispatcher;const isUseSyncExternalStoreSupported=dispatcher.useSyncExternalStore!=null;return isUseSyncExternalStoreSupported;}/** * mode: The React API and approach to use for syncing state with React * early: Re-renders from Recoil updates occur: * 1) earlier * 2) in sync with React updates in the same batch * 3) before transaction observers instead of after. * concurrent: Is the current mode compatible with Concurrent Mode and useTransition() */function reactMode(){// NOTE: This mode is currently broken with some Suspense cases // see Recoil_selector-test.js if(Recoil_gkx('recoil_transition_support')){return {mode:'TRANSITION_SUPPORT',early:true,concurrent:true};}if(Recoil_gkx('recoil_sync_external_store')&&useSyncExternalStore!=null){return {mode:'SYNC_EXTERNAL_STORE',early:true,concurrent:false};}if(Recoil_gkx('recoil_mutable_source')&&useMutableSource!=null&&typeof window!=='undefined'&&!window.$disableRecoilValueMutableSource_TEMP_HACK_DO_NOT_USE){return Recoil_gkx('recoil_suppress_rerender_in_callback')?{mode:'MUTABLE_SOURCE',early:true,concurrent:true}:{mode:'MUTABLE_SOURCE',early:false,concurrent:false};}return Recoil_gkx('recoil_suppress_rerender_in_callback')?{mode:'LEGACY',early:true,concurrent:false}:{mode:'LEGACY',early:false,concurrent:false};}// TODO Need to figure out if there is a standard/open-source equivalent to see if hot module replacement is happening: function isFastRefreshEnabled(){// @fb-only: const {isAcceptingUpdate} = require('__debug'); // @fb-only: return typeof isAcceptingUpdate === 'function' && isAcceptingUpdate(); return false;// @oss-only }var Recoil_ReactMode={createMutableSource,useMutableSource,useSyncExternalStore,currentRendererSupportsUseSyncExternalStore,reactMode,isFastRefreshEnabled};/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format * @oncall recoil */ // eslint-disable-next-line no-unused-vars class AbstractRecoilValue{constructor(newKey){_defineProperty(this,"key",void 0);this.key=newKey;}toJSON(){return {key:this.key};}}class RecoilState extends AbstractRecoilValue{}class RecoilValueReadOnly extends AbstractRecoilValue{}function isRecoilValue(x){return x instanceof RecoilState||x instanceof RecoilValueReadOnly;}var Recoil_RecoilValue={AbstractRecoilValue,RecoilState,RecoilValueReadOnly,isRecoilValue};var Recoil_RecoilValue_1=Recoil_RecoilValue.AbstractRecoilValue;var Recoil_RecoilValue_2=Recoil_RecoilValue.RecoilState;var Recoil_RecoilValue_3=Recoil_RecoilValue.RecoilValueReadOnly;var Recoil_RecoilValue_4=Recoil_RecoilValue.isRecoilValue;var Recoil_RecoilValue$1=/*#__PURE__*/Object.freeze({__proto__:null,AbstractRecoilValue:Recoil_RecoilValue_1,RecoilState:Recoil_RecoilValue_2,RecoilValueReadOnly:Recoil_RecoilValue_3,isRecoilValue:Recoil_RecoilValue_4});/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format * @oncall recoil */ /** * Creates a new iterable whose output is generated by passing the input * iterable's values through the mapper function. */function mapIterable(iterable,callback){// Use generator to create iterable/iterator return function*(){let index=0;for(const value of iterable){yield callback(value,index++);}}();}var Recoil_mapIterable=mapIterable;class DefaultValue{}const DEFAULT_VALUE=new DefaultValue();// flowlint-next-line unclear-type:off const nodes=new Map();// flowlint-next-line unclear-type:off const recoilValues=new Map();/* eslint-disable no-redeclare */function recoilValuesForKeys(keys){return Recoil_mapIterable(keys,key=>Recoil_nullthrows(recoilValues.get(key)));}function checkForDuplicateAtomKey(key){if(nodes.has(key)){const message=`Duplicate atom key "${key}". This is a FATAL ERROR in production. But it is safe to ignore this warning if it occurred because of hot module replacement.`;{// @fb-only: recoverableViolation(message, 'recoil'); console.warn(message);// @oss-only }}}function registerNode(node){if(Recoil_RecoilEnv.RECOIL_DUPLICATE_ATOM_KEY_CHECKING_ENABLED){checkForDuplicateAtomKey(node.key);}nodes.set(node.key,node);const recoilValue=node.set==null?new Recoil_RecoilValue$1.RecoilValueReadOnly(node.key):new Recoil_RecoilValue$1.RecoilState(node.key);recoilValues.set(node.key,recoilValue);return recoilValue;}/* eslint-enable no-redeclare */class NodeMissingError extends Error{}// flowlint-next-line unclear-type:off function getNode(key){const node=nodes.get(key);if(node==null){throw new NodeMissingError(`Missing definition for RecoilValue: "${key}""`);}return node;}// flowlint-next-line unclear-type:off function getNodeMaybe(key){return nodes.get(key);}const configDeletionHandlers=new Map();function deleteNodeConfigIfPossible(key){var _node$shouldDeleteCon;if(!Recoil_gkx('recoil_memory_managament_2020')){return;}const node=nodes.get(key);if(node!==null&&node!==void 0&&(_node$shouldDeleteCon=node.shouldDeleteConfigOnRelease)!==null&&_node$shouldDeleteCon!==void 0&&_node$shouldDeleteCon.call(node)){var _getConfigDeletionHan;nodes.delete(key);(_getConfigDeletionHan=getConfigDeletionHandler(key))===null||_getConfigDeletionHan===void 0?void 0:_getConfigDeletionHan();configDeletionHandlers.delete(key);}}function setConfigDeletionHandler(key,fn){if(!Recoil_gkx('recoil_memory_managament_2020')){return;}if(fn===undefined){configDeletionHandlers.delete(key);}else {configDeletionHandlers.set(key,fn);}}function getConfigDeletionHandler(key){return configDeletionHandlers.get(key);}var Recoil_Node={nodes,recoilValues,registerNode,getNode,getNodeMaybe,deleteNodeConfigIfPossible,setConfigDeletionHandler,getConfigDeletionHandler,recoilValuesForKeys,NodeMissingError,DefaultValue,DEFAULT_VALUE};/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format * @oncall recoil */function enqueueExecution(s,f){f();}var Recoil_Queue={enqueueExecution};function createCommonjsModule(fn,module){return module={exports:{}},fn(module,module.exports),module.exports;}var hamt_1=createCommonjsModule(function(module){var _typeof=typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"?function(obj){return typeof obj;}:function(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj;};/** @fileOverview Hash Array Mapped Trie. Code based on: https://github.com/exclipy/pdata */var hamt={};// export /* Configuration ******************************************************************************/var SIZE=5;var BUCKET_SIZE=Math.pow(2,SIZE);var MASK=BUCKET_SIZE-1;var MAX_INDEX_NODE=BUCKET_SIZE/2;var MIN_ARRAY_NODE=BUCKET_SIZE/4;/* ******************************************************************************/var nothing={};var constant=function constant(x){return function(){return x;};};/** Get 32 bit hash of string. Based on: http://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript-jquery */var hash=hamt.hash=function(str){var type=typeof str==='undefined'?'undefined':_typeof(str);if(type==='number')return str;if(type!=='string')str+='';var hash=0;for(var i=0,len=str.length;i>1&0x55555555;x=(x&0x33333333)+(x>>2&0x33333333);x=x+(x>>4)&0x0f0f0f0f;x+=x>>8;x+=x>>16;return x&0x7f;};var hashFragment=function hashFragment(shift,h){return h>>>shift&MASK;};var toBitmap=function toBitmap(x){return 1<=at){arr[_i--]=arr[_i];}arr[at]=v;return arr;}var i=0,g=0;var out=new Array(len+1);while(i>>=1;}arr[frag]=child;return ArrayNode(edit,count+1,arr);};/** Collapse an array node into a indexed node. @param edit Current edit. @param count Number of elements in new array. @param removed Index of removed element. @param elements Array node children before remove. */var pack=function pack(edit,count,removed,elements){var children=new Array(count-1);var g=0;var bitmap=0;for(var i=0,len=elements.length;i1?Collision(edit,this.hash,list):list[0];// collapse single element collision list }var v=f();if(v===nothing)return this;++size.value;return mergeLeaves(edit,shift,this.hash,this,h,Leaf(edit,h,k,v));};var IndexedNode__modify=function IndexedNode__modify(edit,keyEq,shift,f,h,k,size){var mask=this.mask;var children=this.children;var frag=hashFragment(shift,h);var bit=toBitmap(frag);var indx=fromBitmap(mask,bit);var exists=mask&bit;var current=exists?children[indx]:empty;var child=current._modify(edit,keyEq,shift+SIZE,f,h,k,size);if(current===child)return this;var canEdit=canEditNode(edit,this);var bitmap=mask;var newChildren=void 0;if(exists&&isEmptyNode(child)){// remove bitmap&=~bit;if(!bitmap)return empty;if(children.length<=2&&isLeaf(children[indx^1]))return children[indx^1];// collapse newChildren=arraySpliceOut(canEdit,indx,children);}else if(!exists&&!isEmptyNode(child)){// add if(children.length>=MAX_INDEX_NODE)return expand(edit,frag,child,mask,children);bitmap|=bit;newChildren=arraySpliceIn(canEdit,indx,child,children);}else {// modify newChildren=arrayUpdate(canEdit,indx,child,children);}if(canEdit){this.mask=bitmap;this.children=newChildren;return this;}return IndexedNode(edit,bitmap,newChildren);};var ArrayNode__modify=function ArrayNode__modify(edit,keyEq,shift,f,h,k,size){var count=this.size;var children=this.children;var frag=hashFragment(shift,h);var child=children[frag];var newChild=(child||empty)._modify(edit,keyEq,shift+SIZE,f,h,k,size);if(child===newChild)return this;var canEdit=canEditNode(edit,this);var newChildren=void 0;if(isEmptyNode(child)&&!isEmptyNode(newChild)){// add ++count;newChildren=arrayUpdate(canEdit,frag,newChild,children);}else if(!isEmptyNode(child)&&isEmptyNode(newChild)){// remove --count;if(count<=MIN_ARRAY_NODE)return pack(edit,count,frag,children);newChildren=arrayUpdate(canEdit,frag,empty,children);}else {// modify newChildren=arrayUpdate(canEdit,frag,newChild,children);}if(canEdit){this.size=count;this.children=newChildren;return this;}return ArrayNode(edit,count,newChildren);};empty._modify=function(edit,keyEq,shift,f,h,k,size){var v=f();if(v===nothing)return empty;++size.value;return Leaf(edit,h,k,v);};/* ******************************************************************************/function Map(editable,edit,config,root,size){this._editable=editable;this._edit=edit;this._config=config;this._root=root;this._size=size;}Map.prototype.setTree=function(newRoot,newSize){if(this._editable){this._root=newRoot;this._size=newSize;return this;}return newRoot===this._root?this:new Map(this._editable,this._edit,this._config,newRoot,newSize);};/* Queries ******************************************************************************/ /** Lookup the value for `key` in `map` using a custom `hash`. Returns the value or `alt` if none. */var tryGetHash=hamt.tryGetHash=function(alt,hash,key,map){var node=map._root;var shift=0;var keyEq=map._config.keyEq;while(true){switch(node.type){case LEAF:{return keyEq(key,node.key)?node.value:alt;}case COLLISION:{if(hash===node.hash){var children=node.children;for(var i=0,len=children.length;i. // $FlowIssue constructor(existing){_defineProperty(this,"_hamt",hamt_1.empty.beginMutation());if(existing instanceof HashArrayMappedTrieMap){const h=existing._hamt.endMutation();existing._hamt=h.beginMutation();this._hamt=h.beginMutation();}else if(existing){for(const[k,v]of existing.entries()){this._hamt.set(k,v);}}}keys(){return this._hamt.keys();}entries(){return this._hamt.entries();}get(k){return this._hamt.get(k);}has(k){return this._hamt.has(k);}set(k,v){this._hamt.set(k,v);return this;}delete(k){this._hamt.delete(k);return this;}clone(){return persistentMap(this);}toMap(){return new Map(this._hamt);}}function persistentMap(existing){if(Recoil_gkx('recoil_hamt_2020')){return new HashArrayMappedTrieMap(existing);}else {return new BuiltInMap(existing);}}var Recoil_PersistentMap={persistentMap};var Recoil_PersistentMap_1=Recoil_PersistentMap.persistentMap;var Recoil_PersistentMap$1=/*#__PURE__*/Object.freeze({__proto__:null,persistentMap:Recoil_PersistentMap_1});/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format * @oncall recoil */ /** * Returns a set containing all of the values from the first set that are not * present in any of the subsequent sets. * * Note: this is written procedurally (i.e., without filterSet) for performant * use in tight loops. */function differenceSets(set,...setsWithValuesToRemove){const ret=new Set();FIRST:for(const value of set){for(const otherSet of setsWithValuesToRemove){if(otherSet.has(value)){continue FIRST;}}ret.add(value);}return ret;}var Recoil_differenceSets=differenceSets;/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format * @oncall recoil */ /** * Returns a new Map object with the same keys as the original, but with the * values replaced with the output of the given callback function. */function mapMap(map,callback){const result=new Map();map.forEach((value,key)=>{result.set(key,callback(value,key));});return result;}var Recoil_mapMap=mapMap;function makeGraph(){return {nodeDeps:new Map(),nodeToNodeSubscriptions:new Map()};}function cloneGraph(graph){return {nodeDeps:Recoil_mapMap(graph.nodeDeps,s=>new Set(s)),nodeToNodeSubscriptions:Recoil_mapMap(graph.nodeToNodeSubscriptions,s=>new Set(s))};}// Note that this overwrites the deps of existing nodes, rather than unioning // the new deps with the old deps. function mergeDepsIntoGraph(key,newDeps,graph,// If olderGraph is given then we will not overwrite changes made to the given // graph compared with olderGraph: olderGraph){const{nodeDeps,nodeToNodeSubscriptions}=graph;const oldDeps=nodeDeps.get(key);if(oldDeps&&olderGraph&&oldDeps!==olderGraph.nodeDeps.get(key)){return;}// Update nodeDeps: nodeDeps.set(key,newDeps);// Add new deps to nodeToNodeSubscriptions: const addedDeps=oldDeps==null?newDeps:Recoil_differenceSets(newDeps,oldDeps);for(const dep of addedDeps){if(!nodeToNodeSubscriptions.has(dep)){nodeToNodeSubscriptions.set(dep,new Set());}const existing=Recoil_nullthrows(nodeToNodeSubscriptions.get(dep));existing.add(key);}// Remove removed deps from nodeToNodeSubscriptions: if(oldDeps){const removedDeps=Recoil_differenceSets(oldDeps,newDeps);for(const dep of removedDeps){if(!nodeToNodeSubscriptions.has(dep)){return;}const existing=Recoil_nullthrows(nodeToNodeSubscriptions.get(dep));existing.delete(key);if(existing.size===0){nodeToNodeSubscriptions.delete(dep);}}}}function saveDepsToStore(key,deps,store,version){var _storeState$nextTree,_storeState$previousT,_storeState$previousT2,_storeState$previousT3;const storeState=store.getState();if(!(version===storeState.currentTree.version||version===((_storeState$nextTree=storeState.nextTree)===null||_storeState$nextTree===void 0?void 0:_storeState$nextTree.version)||version===((_storeState$previousT=storeState.previousTree)===null||_storeState$previousT===void 0?void 0:_storeState$previousT.version)));// Merge the dependencies discovered into the store's dependency map // for the version that was read: const graph=store.getGraph(version);mergeDepsIntoGraph(key,deps,graph);// If this version is not the latest version, also write these dependencies // into later versions if they don't already have their own: if(version===((_storeState$previousT2=storeState.previousTree)===null||_storeState$previousT2===void 0?void 0:_storeState$previousT2.version)){const currentGraph=store.getGraph(storeState.currentTree.version);mergeDepsIntoGraph(key,deps,currentGraph,graph);}if(version===((_storeState$previousT3=storeState.previousTree)===null||_storeState$previousT3===void 0?void 0:_storeState$previousT3.version)||version===storeState.currentTree.version){var _storeState$nextTree2;const nextVersion=(_storeState$nextTree2=storeState.nextTree)===null||_storeState$nextTree2===void 0?void 0:_storeState$nextTree2.version;if(nextVersion!==undefined){const nextGraph=store.getGraph(nextVersion);mergeDepsIntoGraph(key,deps,nextGraph,graph);}}}var Recoil_Graph={cloneGraph,graph:makeGraph,saveDepsToStore};/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format * @oncall recoil */let nextTreeStateVersion=0;const getNextTreeStateVersion=()=>nextTreeStateVersion++;let nextStoreID=0;const getNextStoreID=()=>nextStoreID++;let nextComponentID=0;const getNextComponentID=()=>nextComponentID++;var Recoil_Keys={getNextTreeStateVersion,getNextStoreID,getNextComponentID};const{persistentMap:persistentMap$1}=Recoil_PersistentMap$1;const{graph}=Recoil_Graph;const{getNextTreeStateVersion:getNextTreeStateVersion$1}=Recoil_Keys;function makeEmptyTreeState(){const version=getNextTreeStateVersion$1();return {version,stateID:version,transactionMetadata:{},dirtyAtoms:new Set(),atomValues:persistentMap$1(),nonvalidatedAtoms:persistentMap$1()};}function makeEmptyStoreState(){const currentTree=makeEmptyTreeState();return {currentTree,nextTree:null,previousTree:null,commitDepth:0,knownAtoms:new Set(),knownSelectors:new Set(),transactionSubscriptions:new Map(),nodeTransactionSubscriptions:new Map(),nodeToComponentSubscriptions:new Map(),queuedComponentCallbacks_DEPRECATED:[],suspendedComponentResolvers:new Set(),graphsByVersion:new Map().set(currentTree.version,graph()),retention:{referenceCounts:new Map(),nodesRetainedByZone:new Map(),retainablesToCheckForRelease:new Set()},nodeCleanupFunctions:new Map()};}var Recoil_State={makeEmptyTreeState,makeEmptyStoreState,getNextTreeStateVersion:getNextTreeStateVersion$1};/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format * @oncall recoil */class RetentionZone{}function retentionZone(){return new RetentionZone();}var Recoil_RetentionZone={RetentionZone,retentionZone};/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * Utilities for working with built-in Maps and Sets without mutating them. * * * @format * @oncall recoil */function setByAddingToSet(set,v){const next=new Set(set);next.add(v);return next;}function setByDeletingFromSet(set,v){const next=new Set(set);next.delete(v);return next;}function mapBySettingInMap(map,k,v){const next=new Map(map);next.set(k,v);return next;}function mapByUpdatingInMap(map,k,updater){const next=new Map(map);next.set(k,updater(next.get(k)));return next;}function mapByDeletingFromMap(map,k){const next=new Map(map);next.delete(k);return next;}function mapByDeletingMultipleFromMap(map,ks){const next=new Map(map);ks.forEach(k=>next.delete(k));return next;}var Recoil_CopyOnWrite={setByAddingToSet,setByDeletingFromSet,mapBySettingInMap,mapByUpdatingInMap,mapByDeletingFromMap,mapByDeletingMultipleFromMap};/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format * @oncall recoil */ /** * Creates a new iterable whose output is generated by passing the input * iterable's values through the filter function. */function*filterIterable(iterable,predicate){// Use generator to create iterable/iterator let index=0;for(const value of iterable){if(predicate(value,index++)){yield value;}}}var Recoil_filterIterable=filterIterable;/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format * @oncall recoil */ /** * Return a proxy object based on the provided base and factories objects. * The proxy will include all properties of the base object as-is. * The factories object contains callbacks to obtain the values of the properies * for its keys. * * This is useful for providing users an object where some properties may be * lazily computed only on first access. */ // $FlowIssue[unclear-type] function lazyProxy(base,factories){const proxy=new Proxy(base,{// Compute and cache lazy property if not already done. get:(target,prop)=>{if(!(prop in target)&&prop in factories){target[prop]=factories[prop]();}return target[prop];},// This method allows user to iterate keys as normal ownKeys:target=>{return Object.keys(target);}});// $FlowIssue[incompatible-return] return proxy;}var Recoil_lazyProxy=lazyProxy;const{getNode:getNode$1,getNodeMaybe:getNodeMaybe$1,recoilValuesForKeys:recoilValuesForKeys$1}=Recoil_Node;const{RetentionZone:RetentionZone$1}=Recoil_RetentionZone;const{setByAddingToSet:setByAddingToSet$1}=Recoil_CopyOnWrite;// flowlint-next-line unclear-type:off const emptySet=Object.freeze(new Set());class ReadOnlyRecoilValueError extends Error{}function initializeRetentionForNode(store,nodeKey,retainedBy){if(!Recoil_gkx('recoil_memory_managament_2020')){return ()=>undefined;}const{nodesRetainedByZone}=store.getState().retention;function addToZone(zone){let set=nodesRetainedByZone.get(zone);if(!set){nodesRetainedByZone.set(zone,set=new Set());}set.add(nodeKey);}if(retainedBy instanceof RetentionZone$1){addToZone(retainedBy);}else if(Array.isArray(retainedBy)){for(const zone of retainedBy){addToZone(zone);}}return ()=>{if(!Recoil_gkx('recoil_memory_managament_2020')){return;}const{retention}=store.getState();function deleteFromZone(zone){const set=retention.nodesRetainedByZone.get(zone);set===null||set===void 0?void 0:set.delete(nodeKey);if(set&&set.size===0){retention.nodesRetainedByZone.delete(zone);}}if(retainedBy instanceof RetentionZone$1){deleteFromZone(retainedBy);}else if(Array.isArray(retainedBy)){for(const zone of retainedBy){deleteFromZone(zone);}}};}function initializeNodeIfNewToStore(store,treeState,key,trigger){const storeState=store.getState();if(storeState.nodeCleanupFunctions.has(key)){return;}const node=getNode$1(key);const retentionCleanup=initializeRetentionForNode(store,key,node.retainedBy);const nodeCleanup=node.init(store,treeState,trigger);storeState.nodeCleanupFunctions.set(key,()=>{nodeCleanup();retentionCleanup();});}function initializeNode(store,key,trigger){initializeNodeIfNewToStore(store,store.getState().currentTree,key,trigger);}function cleanUpNode(store,key){var _state$nodeCleanupFun;const state=store.getState();(_state$nodeCleanupFun=state.nodeCleanupFunctions.get(key))===null||_state$nodeCleanupFun===void 0?void 0:_state$nodeCleanupFun();state.nodeCleanupFunctions.delete(key);}// Get the current value loadable of a node and update the state. // Update dependencies and subscriptions for selectors. // Update saved value validation for atoms. function getNodeLoadable(store,state,key){initializeNodeIfNewToStore(store,state,key,'get');return getNode$1(key).get(store,state);}// Peek at the current value loadable for a node without any evaluation or state change function peekNodeLoadable(store,state,key){return getNode$1(key).peek(store,state);}// Write value directly to state bypassing the Node interface as the node // definitions may not have been loaded yet when processing the initial snapshot. function setUnvalidatedAtomValue_DEPRECATED(state,key,newValue){var _node$invalidate;const node=getNodeMaybe$1(key);node===null||node===void 0?void 0:(_node$invalidate=node.invalidate)===null||_node$invalidate===void 0?void 0:_node$invalidate.call(node,state);return {...state,atomValues:state.atomValues.clone().delete(key),nonvalidatedAtoms:state.nonvalidatedAtoms.clone().set(key,newValue),dirtyAtoms:setByAddingToSet$1(state.dirtyAtoms,key)};}// Return the discovered dependencies and values to be written by setting // a node value. (Multiple values may be written due to selectors getting to // set upstreams; deps may be discovered because of reads in updater functions.) function setNodeValue(store,state,key,newValue){const node=getNode$1(key);if(node.set==null){throw new ReadOnlyRecoilValueError(`Attempt to set read-only RecoilValue: ${key}`);}const set=node.set;// so flow doesn't lose the above refinement. initializeNodeIfNewToStore(store,state,key,'set');return set(store,state,newValue);}function peekNodeInfo(store,state,key){const storeState=store.getState();const graph=store.getGraph(state.version);const type=getNode$1(key).nodeType;return Recoil_lazyProxy({type},{// $FlowFixMe[underconstrained-implicit-instantiation] loadable:()=>peekNodeLoadable(store,state,key),isActive:()=>storeState.knownAtoms.has(key)||storeState.knownSelectors.has(key),isSet:()=>type==='selector'?false:state.atomValues.has(key),isModified:()=>state.dirtyAtoms.has(key),// Report current dependencies. If the node hasn't been evaluated, then // dependencies may be missing based on the current state. deps:()=>{var _graph$nodeDeps$get;return recoilValuesForKeys$1((_graph$nodeDeps$get=graph.nodeDeps.get(key))!==null&&_graph$nodeDeps$get!==void 0?_graph$nodeDeps$get:[]);},// Reports all "current" subscribers. Evaluating other nodes or // previous in-progress async evaluations may introduce new subscribers. subscribers:()=>{var _storeState$nodeToCom,_storeState$nodeToCom2;return {nodes:recoilValuesForKeys$1(Recoil_filterIterable(getDownstreamNodes(store,state,new Set([key])),nodeKey=>nodeKey!==key)),components:Recoil_mapIterable((_storeState$nodeToCom=(_storeState$nodeToCom2=storeState.nodeToComponentSubscriptions.get(key))===null||_storeState$nodeToCom2===void 0?void 0:_storeState$nodeToCom2.values())!==null&&_storeState$nodeToCom!==void 0?_storeState$nodeToCom:[],([name])=>({name}))};}});}// Find all of the recursively dependent nodes function getDownstreamNodes(store,state,keys){const visitedNodes=new Set();const visitingNodes=Array.from(keys);const graph=store.getGraph(state.version);for(let key=visitingNodes.pop();key;key=visitingNodes.pop()){var _graph$nodeToNodeSubs;visitedNodes.add(key);const subscribedNodes=(_graph$nodeToNodeSubs=graph.nodeToNodeSubscriptions.get(key))!==null&&_graph$nodeToNodeSubs!==void 0?_graph$nodeToNodeSubs:emptySet;for(const downstreamNode of subscribedNodes){if(!visitedNodes.has(downstreamNode)){visitingNodes.push(downstreamNode);}}}return visitedNodes;}var Recoil_FunctionalCore={getNodeLoadable,peekNodeLoadable,setNodeValue,initializeNode,cleanUpNode,setUnvalidatedAtomValue_DEPRECATED,peekNodeInfo,getDownstreamNodes};/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format * @oncall recoil */let _invalidateMemoizedSnapshot=null;function setInvalidateMemoizedSnapshot(invalidate){_invalidateMemoizedSnapshot=invalidate;}function invalidateMemoizedSnapshot(){var _invalidateMemoizedSn;(_invalidateMemoizedSn=_invalidateMemoizedSnapshot)===null||_invalidateMemoizedSn===void 0?void 0:_invalidateMemoizedSn();}var Recoil_SnapshotCache={setInvalidateMemoizedSnapshot,invalidateMemoizedSnapshot};const{getDownstreamNodes:getDownstreamNodes$1,getNodeLoadable:getNodeLoadable$1,setNodeValue:setNodeValue$1}=Recoil_FunctionalCore;const{getNextComponentID:getNextComponentID$1}=Recoil_Keys;const{getNode:getNode$2,getNodeMaybe:getNodeMaybe$2}=Recoil_Node;const{DefaultValue:DefaultValue$1}=Recoil_Node;const{reactMode:reactMode$1}=Recoil_ReactMode;const{AbstractRecoilValue:AbstractRecoilValue$1,RecoilState:RecoilState$1,RecoilValueReadOnly:RecoilValueReadOnly$1,isRecoilValue:isRecoilValue$1}=Recoil_RecoilValue$1;const{invalidateMemoizedSnapshot:invalidateMemoizedSnapshot$1}=Recoil_SnapshotCache;function getRecoilValueAsLoadable(store,{key},treeState=store.getState().currentTree){var _storeState$nextTree,_storeState$previousT;// Reading from an older tree can cause bugs because the dependencies that we // discover during the read are lost. const storeState=store.getState();if(!(treeState.version===storeState.currentTree.version||treeState.version===((_storeState$nextTree=storeState.nextTree)===null||_storeState$nextTree===void 0?void 0:_storeState$nextTree.version)||treeState.version===((_storeState$previousT=storeState.previousTree)===null||_storeState$previousT===void 0?void 0:_storeState$previousT.version)));const loadable=getNodeLoadable$1(store,treeState,key);if(loadable.state==='loading'){loadable.contents.catch(()=>{/** * HACK: intercept thrown error here to prevent an uncaught promise exception. Ideally this would happen closer to selector * execution (perhaps introducing a new ERROR class to be resolved by async selectors that are in an error state) */return;});}return loadable;}function applyAtomValueWrites(atomValues,writes){const result=atomValues.clone();writes.forEach((v,k)=>{if(v.state==='hasValue'&&v.contents instanceof DefaultValue$1){result.delete(k);}else {result.set(k,v);}});return result;}function valueFromValueOrUpdater(store,state,{key},valueOrUpdater){if(typeof valueOrUpdater==='function'){// Updater form: pass in the current value. Throw if the current value // is unavailable (namely when updating an async selector that's // pending or errored): const current=getNodeLoadable$1(store,state,key);if(current.state==='loading'){const msg=`Tried to set atom or selector "${key}" using an updater function while the current state is pending, this is not currently supported.`;throw Recoil_err(msg);}else if(current.state==='hasError'){throw current.contents;}// T itself may be a function, so our refinement is not sufficient: return valueOrUpdater(current.contents);// flowlint-line unclear-type:off }else {return valueOrUpdater;}}function applyAction(store,state,action){if(action.type==='set'){const{recoilValue,valueOrUpdater}=action;const newValue=valueFromValueOrUpdater(store,state,recoilValue,valueOrUpdater);const writes=setNodeValue$1(store,state,recoilValue.key,newValue);for(const[key,loadable]of writes.entries()){writeLoadableToTreeState(state,key,loadable);}}else if(action.type==='setLoadable'){const{recoilValue:{key},loadable}=action;writeLoadableToTreeState(state,key,loadable);}else if(action.type==='markModified'){const{recoilValue:{key}}=action;state.dirtyAtoms.add(key);}else if(action.type==='setUnvalidated'){var _node$invalidate;// Write value directly to state bypassing the Node interface as the node // definitions may not have been loaded yet when processing the initial snapshot. const{recoilValue:{key},unvalidatedValue}=action;const node=getNodeMaybe$2(key);node===null||node===void 0?void 0:(_node$invalidate=node.invalidate)===null||_node$invalidate===void 0?void 0:_node$invalidate.call(node,state);state.atomValues.delete(key);state.nonvalidatedAtoms.set(key,unvalidatedValue);state.dirtyAtoms.add(key);}else {Recoil_recoverableViolation(`Unknown action ${action.type}`);}}function writeLoadableToTreeState(state,key,loadable){if(loadable.state==='hasValue'&&loadable.contents instanceof DefaultValue$1){state.atomValues.delete(key);}else {state.atomValues.set(key,loadable);}state.dirtyAtoms.add(key);state.nonvalidatedAtoms.delete(key);}function applyActionsToStore(store,actions){store.replaceState(state=>{const newState=copyTreeState(state);for(const action of actions){applyAction(store,newState,action);}invalidateDownstreams(store,newState);invalidateMemoizedSnapshot$1();return newState;});}function queueOrPerformStateUpdate(store,action){if(batchStack.length){const actionsByStore=batchStack[batchStack.length-1];let actions=actionsByStore.get(store);if(!actions){actionsByStore.set(store,actions=[]);}actions.push(action);}else {applyActionsToStore(store,[action]);}}const batchStack=[];function batchStart(){const actionsByStore=new Map();batchStack.push(actionsByStore);return ()=>{for(const[store,actions]of actionsByStore){applyActionsToStore(store,actions);}batchStack.pop();};}function copyTreeState(state){return {...state,atomValues:state.atomValues.clone(),nonvalidatedAtoms:state.nonvalidatedAtoms.clone(),dirtyAtoms:new Set(state.dirtyAtoms)};}function invalidateDownstreams(store,state){// Inform any nodes that were changed or downstream of changes so that they // can clear out any caches as needed due to the update: const downstreams=getDownstreamNodes$1(store,state,state.dirtyAtoms);for(const key of downstreams){var _getNodeMaybe,_getNodeMaybe$invalid;(_getNodeMaybe=getNodeMaybe$2(key))===null||_getNodeMaybe===void 0?void 0:(_getNodeMaybe$invalid=_getNodeMaybe.invalidate)===null||_getNodeMaybe$invalid===void 0?void 0:_getNodeMaybe$invalid.call(_getNodeMaybe,state);}}function setRecoilValue(store,recoilValue,valueOrUpdater){queueOrPerformStateUpdate(store,{type:'set',recoilValue,valueOrUpdater});}function setRecoilValueLoadable(store,recoilValue,loadable){if(loadable instanceof DefaultValue$1){return setRecoilValue(store,recoilValue,loadable);}queueOrPerformStateUpdate(store,{type:'setLoadable',recoilValue,loadable:loadable});}function markRecoilValueModified(store,recoilValue){queueOrPerformStateUpdate(store,{type:'markModified',recoilValue});}function setUnvalidatedRecoilValue(store,recoilValue,unvalidatedValue){queueOrPerformStateUpdate(store,{type:'setUnvalidated',recoilValue,unvalidatedValue});}function subscribeToRecoilValue(store,{key},callback,componentDebugName=null){const subID=getNextComponentID$1();const storeState=store.getState();if(!storeState.nodeToComponentSubscriptions.has(key)){storeState.nodeToComponentSubscriptions.set(key,new Map());}Recoil_nullthrows(storeState.nodeToComponentSubscriptions.get(key)).set(subID,[componentDebugName!==null&&componentDebugName!==void 0?componentDebugName:'',callback]);// Handle the case that, during the same tick that we are subscribing, an atom // has been updated by some effect handler. Otherwise we will miss the update. const mode=reactMode$1();if(mode.early&&(mode.mode==='LEGACY'||mode.mode==='MUTABLE_SOURCE')){const nextTree=store.getState().nextTree;if(nextTree&&nextTree.dirtyAtoms.has(key)){callback(nextTree);}}return {release:()=>{const releaseStoreState=store.getState();const subs=releaseStoreState.nodeToComponentSubscriptions.get(key);if(subs===undefined||!subs.has(subID)){return;}subs.delete(subID);if(subs.size===0){releaseStoreState.nodeToComponentSubscriptions.delete(key);}}};}function refreshRecoilValue(store,recoilValue){var _node$clearCache;const{currentTree}=store.getState();const node=getNode$2(recoilValue.key);(_node$clearCache=node.clearCache)===null||_node$clearCache===void 0?void 0:_node$clearCache.call(node,store,currentTree);}var Recoil_RecoilValueInterface={RecoilValueReadOnly:RecoilValueReadOnly$1,AbstractRecoilValue:AbstractRecoilValue$1,RecoilState:RecoilState$1,getRecoilValueAsLoadable,setRecoilValue,setRecoilValueLoadable,markRecoilValueModified,setUnvalidatedRecoilValue,subscribeToRecoilValue,isRecoilValue:isRecoilValue$1,applyAtomValueWrites,// TODO Remove export when deprecating initialStoreState_DEPRECATED in RecoilRoot batchStart,writeLoadableToTreeState,invalidateDownstreams,copyTreeState,refreshRecoilValue};/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format * @oncall recoil */ /** * The someSet() method tests whether some elements in the given Set pass the * test implemented by the provided function. */function someSet(set,callback,context){const iterator=set.entries();let current=iterator.next();while(!current.done){const entry=current.value;if(callback.call(context,entry[1],entry[0],set)){return true;}current=iterator.next();}return false;}var Recoil_someSet=someSet;const{cleanUpNode:cleanUpNode$1}=Recoil_FunctionalCore;const{deleteNodeConfigIfPossible:deleteNodeConfigIfPossible$1,getNode:getNode$3}=Recoil_Node;const{RetentionZone:RetentionZone$2}=Recoil_RetentionZone;// Components that aren't mounted after suspending for this long will be assumed // to be discarded and their resources released. const SUSPENSE_TIMEOUT_MS=120000;const emptySet$1=new Set();function releaseRetainablesNowOnCurrentTree(store,retainables){const storeState=store.getState();const treeState=storeState.currentTree;if(storeState.nextTree){return;// leak memory rather than erase something that's about to be used. }const nodes=new Set();for(const r of retainables){if(r instanceof RetentionZone$2){for(const n of nodesRetainedByZone(storeState,r)){nodes.add(n);}}else {nodes.add(r);}}const releasableNodes=findReleasableNodes(store,nodes);for(const node of releasableNodes){releaseNode(store,treeState,node);}}function findReleasableNodes(store,searchFromNodes){const storeState=store.getState();const treeState=storeState.currentTree;const graph=store.getGraph(treeState.version);const releasableNodes=new Set();// mutated to collect answer const nonReleasableNodes=new Set();findReleasableNodesInner(searchFromNodes);return releasableNodes;function findReleasableNodesInner(searchFromNodes){const releasableNodesFoundThisIteration=new Set();const downstreams=getDownstreamNodesInTopologicalOrder(store,treeState,searchFromNodes,releasableNodes,// don't descend into these nonReleasableNodes// don't descend into these );// Find which of the downstream nodes are releasable and which are not: for(const node of downstreams){var _storeState$retention;// Not releasable if configured to be retained forever: if(getNode$3(node).retainedBy==='recoilRoot'){nonReleasableNodes.add(node);continue;}// Not releasable if retained directly by a component: if(((_storeState$retention=storeState.retention.referenceCounts.get(node))!==null&&_storeState$retention!==void 0?_storeState$retention:0)>0){nonReleasableNodes.add(node);continue;}// Not releasable if retained by a zone: if(zonesThatCouldRetainNode(node).some(z=>storeState.retention.referenceCounts.get(z))){nonReleasableNodes.add(node);continue;}// Not releasable if it has a non-releasable child (which will already be in // nonReleasableNodes because we are going in topological order): const nodeChildren=graph.nodeToNodeSubscriptions.get(node);if(nodeChildren&&Recoil_someSet(nodeChildren,child=>nonReleasableNodes.has(child))){nonReleasableNodes.add(node);continue;}releasableNodes.add(node);releasableNodesFoundThisIteration.add(node);}// If we found any releasable nodes, we need to walk UP from those nodes to // find whether their parents can now be released as well: const parents=new Set();for(const node of releasableNodesFoundThisIteration){for(const parent of (_graph$nodeDeps$get=graph.nodeDeps.get(node))!==null&&_graph$nodeDeps$get!==void 0?_graph$nodeDeps$get:emptySet$1){var _graph$nodeDeps$get;if(!releasableNodes.has(parent)){parents.add(parent);}}}if(parents.size){findReleasableNodesInner(parents);}}}// Children before parents function getDownstreamNodesInTopologicalOrder(store,treeState,nodes,// Mutable set is destroyed in place doNotDescendInto1,doNotDescendInto2){const graph=store.getGraph(treeState.version);const answer=[];const visited=new Set();while(nodes.size>0){visit(Recoil_nullthrows(nodes.values().next().value));}return answer;function visit(node){if(doNotDescendInto1.has(node)||doNotDescendInto2.has(node)){nodes.delete(node);return;}if(visited.has(node)){return;}const children=graph.nodeToNodeSubscriptions.get(node);if(children){for(const child of children){visit(child);}}visited.add(node);nodes.delete(node);answer.push(node);}}function releaseNode(store,treeState,node){if(!Recoil_gkx('recoil_memory_managament_2020')){return;}// Atom effects, in-closure caches, etc.: cleanUpNode$1(store,node);// Delete from store state: const storeState=store.getState();storeState.knownAtoms.delete(node);storeState.knownSelectors.delete(node);storeState.nodeTransactionSubscriptions.delete(node);storeState.retention.referenceCounts.delete(node);const zones=zonesThatCouldRetainNode(node);for(const zone of zones){var _storeState$retention2;(_storeState$retention2=storeState.retention.nodesRetainedByZone.get(zone))===null||_storeState$retention2===void 0?void 0:_storeState$retention2.delete(node);}// Note that we DO NOT delete from nodeToComponentSubscriptions because this // already happens when the last component that was retaining the node unmounts, // and this could happen either before or after that. // Delete from TreeState and dep graph: treeState.atomValues.delete(node);treeState.dirtyAtoms.delete(node);treeState.nonvalidatedAtoms.delete(node);const graph=storeState.graphsByVersion.get(treeState.version);if(graph){const deps=graph.nodeDeps.get(node);if(deps!==undefined){graph.nodeDeps.delete(node);for(const dep of deps){var _graph$nodeToNodeSubs;(_graph$nodeToNodeSubs=graph.nodeToNodeSubscriptions.get(dep))===null||_graph$nodeToNodeSubs===void 0?void 0:_graph$nodeToNodeSubs.delete(node);}}// No need to delete sub's deps as there should be no subs at this point. // But an invariant would require deleting nodes in topological order. graph.nodeToNodeSubscriptions.delete(node);}// Node config (for family members only as their configs can be recreated, and // only if they are not retained within any other Stores): deleteNodeConfigIfPossible$1(node);}function nodesRetainedByZone(storeState,zone){var _storeState$retention3;return (_storeState$retention3=storeState.retention.nodesRetainedByZone.get(zone))!==null&&_storeState$retention3!==void 0?_storeState$retention3:emptySet$1;}function zonesThatCouldRetainNode(node){const retainedBy=getNode$3(node).retainedBy;if(retainedBy===undefined||retainedBy==='components'||retainedBy==='recoilRoot'){return [];}else if(retainedBy instanceof RetentionZone$2){return [retainedBy];}else {return retainedBy;// it's an array of zones }}function scheduleOrPerformPossibleReleaseOfRetainable(store,retainable){const state=store.getState();if(state.nextTree){state.retention.retainablesToCheckForRelease.add(retainable);}else {releaseRetainablesNowOnCurrentTree(store,new Set([retainable]));}}function updateRetainCount(store,retainable,delta){var _map$get;if(!Recoil_gkx('recoil_memory_managament_2020')){return;}const map=store.getState().retention.referenceCounts;const newCount=((_map$get=map.get(retainable))!==null&&_map$get!==void 0?_map$get:0)+delta;if(newCount===0){updateRetainCountToZero(store,retainable);}else {map.set(retainable,newCount);}}function updateRetainCountToZero(store,retainable){if(!Recoil_gkx('recoil_memory_managament_2020')){return;}const map=store.getState().retention.referenceCounts;map.delete(retainable);scheduleOrPerformPossibleReleaseOfRetainable(store,retainable);}function releaseScheduledRetainablesNow(store){if(!Recoil_gkx('recoil_memory_managament_2020')){return;}const state=store.getState();releaseRetainablesNowOnCurrentTree(store,state.retention.retainablesToCheckForRelease);state.retention.retainablesToCheckForRelease.clear();}function retainedByOptionWithDefault(r){// The default will change from 'recoilRoot' to 'components' in the future. return r===undefined?'recoilRoot':r;}var Recoil_Retention={SUSPENSE_TIMEOUT_MS,updateRetainCount,updateRetainCountToZero,releaseScheduledRetainablesNow,retainedByOptionWithDefault};/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * This is to export esstiential functions from react-dom * for our web build * * * @format * @oncall recoil */const{unstable_batchedUpdates}=reactDom;var ReactBatchedUpdates={unstable_batchedUpdates};/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * This is to export esstiential functions from react-dom * for our web build * * * @format * @oncall recoil */ // @fb-only: const {unstable_batchedUpdates} = require('ReactDOMComet'); // prettier-ignore const{unstable_batchedUpdates:unstable_batchedUpdates$1}=ReactBatchedUpdates;// @oss-only var Recoil_ReactBatchedUpdates={unstable_batchedUpdates:unstable_batchedUpdates$1};/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format * @oncall recoil */const{batchStart:batchStart$1}=Recoil_RecoilValueInterface;const{unstable_batchedUpdates:unstable_batchedUpdates$2}=Recoil_ReactBatchedUpdates;// flowlint-next-line unclear-type:off /* * During SSR, unstable_batchedUpdates may be undefined so this * falls back to a basic function that executes the batch */let batcher=unstable_batchedUpdates$2||(batchFn=>batchFn());/** * Sets the provided batcher function as the batcher function used by Recoil. * * Set the batcher to a custom batcher for your renderer, * if you use a renderer other than React DOM or React Native. */const setBatcher=newBatcher=>{batcher=newBatcher;};/** * Returns the current batcher function. */const getBatcher=()=>batcher;/** * Calls the current batcher function and passes the * provided callback function. */const batchUpdates=callback=>{batcher(()=>{let batchEnd=()=>undefined;try{batchEnd=batchStart$1();callback();}finally{batchEnd();}});};var Recoil_Batching={getBatcher,setBatcher,batchUpdates};/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format * @oncall recoil */ /** * Combines multiple Iterables into a single Iterable. * Traverses the input Iterables in the order provided and maintains the order * of their elements. * * Example: * ``` * const r = Array.from(concatIterables(['a', 'b'], ['c'], ['d', 'e', 'f'])); * r == ['a', 'b', 'c', 'd', 'e', 'f']; * ``` */function*concatIterables(iters){for(const iter of iters){for(const val of iter){yield val;}}}var Recoil_concatIterables=concatIterables;/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format * @oncall recoil */ /* eslint-disable fb-www/typeof-undefined */const isSSR=// $FlowFixMe(site=recoil) Window does not have a FlowType definition https://github.com/facebook/flow/issues/6709 typeof Window==='undefined'||typeof window==='undefined';/* eslint-enable fb-www/typeof-undefined */const isWindow=value=>!isSSR&&(// $FlowFixMe(site=recoil) Window does not have a FlowType definition https://github.com/facebook/flow/issues/6709 value===window||value instanceof Window);const isReactNative=typeof navigator!=='undefined'&&navigator.product==='ReactNative';// eslint-disable-line fb-www/typeof-undefined var Recoil_Environment={isSSR,isReactNative,isWindow};/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format * @oncall recoil */ /** * Caches a function's results based on the key returned by the passed * hashFunction. */function memoizeWithArgsHash(fn,hashFunction){let cache;return (...args)=>{if(!cache){cache={};}const key=hashFunction(...args);if(!Object.hasOwnProperty.call(cache,key)){cache[key]=fn(...args);}return cache[key];};}/** * Caches a function's results based on a comparison of the arguments. * Only caches the last return of the function. * Defaults to reference equality */function memoizeOneWithArgsHash(fn,hashFunction){let lastKey;let lastResult;// breaking cache when arguments change return (...args)=>{const key=hashFunction(...args);if(lastKey===key){return lastResult;}lastKey=key;lastResult=fn(...args);return lastResult;};}/** * Caches a function's results based on a comparison of the arguments. * Only caches the last return of the function. * Defaults to reference equality */function memoizeOneWithArgsHashAndInvalidation(fn,hashFunction){let lastKey;let lastResult;// breaking cache when arguments change const memoizedFn=(...args)=>{const key=hashFunction(...args);if(lastKey===key){return lastResult;}lastKey=key;lastResult=fn(...args);return lastResult;};const invalidate=()=>{lastKey=null;};return [memoizedFn,invalidate];}var Recoil_Memoize={memoizeWithArgsHash,memoizeOneWithArgsHash,memoizeOneWithArgsHashAndInvalidation};const{batchUpdates:batchUpdates$1}=Recoil_Batching;const{initializeNode:initializeNode$1,peekNodeInfo:peekNodeInfo$1}=Recoil_FunctionalCore;const{graph:graph$1}=Recoil_Graph;const{getNextStoreID:getNextStoreID$1}=Recoil_Keys;const{DEFAULT_VALUE:DEFAULT_VALUE$1,recoilValues:recoilValues$1,recoilValuesForKeys:recoilValuesForKeys$2}=Recoil_Node;const{AbstractRecoilValue:AbstractRecoilValue$2,getRecoilValueAsLoadable:getRecoilValueAsLoadable$1,setRecoilValue:setRecoilValue$1,setUnvalidatedRecoilValue:setUnvalidatedRecoilValue$1}=Recoil_RecoilValueInterface;const{updateRetainCount:updateRetainCount$1}=Recoil_Retention;const{setInvalidateMemoizedSnapshot:setInvalidateMemoizedSnapshot$1}=Recoil_SnapshotCache;const{getNextTreeStateVersion:getNextTreeStateVersion$2,makeEmptyStoreState:makeEmptyStoreState$1}=Recoil_State;const{isSSR:isSSR$1}=Recoil_Environment;const{memoizeOneWithArgsHashAndInvalidation:memoizeOneWithArgsHashAndInvalidation$1}=Recoil_Memoize;// Opaque at this surface because it's part of the public API from here. // However, the data-flow-graph and selector values may evolve as selector // evaluation functions are executed and async selectors resolve. class Snapshot{// eslint-disable-next-line fb-www/no-uninitialized-properties constructor(storeState,parentStoreID){_defineProperty(this,"_store",void 0);_defineProperty(this,"_refCount",1);_defineProperty(this,"getLoadable",recoilValue=>{this.checkRefCount_INTERNAL();return getRecoilValueAsLoadable$1(this._store,recoilValue);});_defineProperty(this,"getPromise",recoilValue=>{this.checkRefCount_INTERNAL();return this.getLoadable(recoilValue).toPromise();});_defineProperty(this,"getNodes_UNSTABLE",opt=>{this.checkRefCount_INTERNAL();// TODO Deal with modified selectors if((opt===null||opt===void 0?void 0:opt.isModified)===true){if((opt===null||opt===void 0?void 0:opt.isInitialized)===false){return [];}const state=this._store.getState().currentTree;return recoilValuesForKeys$2(state.dirtyAtoms);}const knownAtoms=this._store.getState().knownAtoms;const knownSelectors=this._store.getState().knownSelectors;return (opt===null||opt===void 0?void 0:opt.isInitialized)==null?recoilValues$1.values():opt.isInitialized===true?recoilValuesForKeys$2(Recoil_concatIterables([knownAtoms,knownSelectors])):Recoil_filterIterable(recoilValues$1.values(),({key})=>!knownAtoms.has(key)&&!knownSelectors.has(key));});_defineProperty(this,"getInfo_UNSTABLE",({key})=>{this.checkRefCount_INTERNAL();return peekNodeInfo$1(this._store,this._store.getState().currentTree,key);});_defineProperty(this,"map",mapper=>{this.checkRefCount_INTERNAL();const mutableSnapshot=new MutableSnapshot(this,batchUpdates$1);mapper(mutableSnapshot);// if removing batchUpdates from `set` add it here return mutableSnapshot;});_defineProperty(this,"asyncMap",async mapper=>{this.checkRefCount_INTERNAL();const mutableSnapshot=new MutableSnapshot(this,batchUpdates$1);mutableSnapshot.retain();// Retain new snapshot during async mapper await mapper(mutableSnapshot);// Continue to retain the new snapshot for the user, but auto-release it // after the next tick, the same as a new synchronous snapshot. mutableSnapshot.autoRelease_INTERNAL();return mutableSnapshot;});this._store={storeID:getNextStoreID$1(),parentStoreID,getState:()=>storeState,replaceState:replacer=>{// no batching, so nextTree is never active storeState.currentTree=replacer(storeState.currentTree);},getGraph:version=>{const graphs=storeState.graphsByVersion;if(graphs.has(version)){return Recoil_nullthrows(graphs.get(version));}const newGraph=graph$1();graphs.set(version,newGraph);return newGraph;},subscribeToTransactions:()=>({release:()=>{}}),addTransactionMetadata:()=>{throw Recoil_err('Cannot subscribe to Snapshots');}};// Initialize any nodes that are live in the parent store (primarily so that // this snapshot gets counted towards the node's live stores count). // TODO Optimize this when cloning snapshots for callbacks for(const nodeKey of this._store.getState().knownAtoms){initializeNode$1(this._store,nodeKey,'get');updateRetainCount$1(this._store,nodeKey,1);}this.autoRelease_INTERNAL();}retain(){if(this._refCount<=0);this._refCount++;let released=false;return ()=>{if(!released){released=true;this._release();}};}/** * Release the snapshot on the next tick. This means the snapshot is retained * during the execution of the current function using it. */autoRelease_INTERNAL(){if(!isSSR$1){// Use timeout of 10 to workaround Firefox issue: https://github.com/facebookexperimental/Recoil/issues/1936 window.setTimeout(()=>this._release(),10);}}_release(){this._refCount--;if(this._refCount===0){this._store.getState().nodeCleanupFunctions.forEach(cleanup=>cleanup());this._store.getState().nodeCleanupFunctions.clear();if(!Recoil_gkx('recoil_memory_managament_2020')){return;}// Temporarily nerfing this to allow us to find broken call sites without // actually breaking anybody yet. // for (const k of this._store.getState().knownAtoms) { // updateRetainCountToZero(this._store, k); // } }else if(this._refCount<0);}isRetained(){return this._refCount>0;}checkRefCount_INTERNAL(){if(Recoil_gkx('recoil_memory_managament_2020')&&this._refCount<=0);}getStore_INTERNAL(){this.checkRefCount_INTERNAL();return this._store;}getID(){this.checkRefCount_INTERNAL();return this._store.getState().currentTree.stateID;}getStoreID(){this.checkRefCount_INTERNAL();return this._store.storeID;}// We want to allow the methods to be destructured and used as accessors /* eslint-disable fb-www/extra-arrow-initializer */ /* eslint-enable fb-www/extra-arrow-initializer */}function cloneStoreState(store,treeState,bumpVersion=false){const storeState=store.getState();const version=bumpVersion?getNextTreeStateVersion$2():treeState.version;return {// Always clone the TreeState to isolate stores from accidental mutations. // For example, reading a selector from a cloned snapshot shouldn't cache // in the original treestate which may cause the original to skip // initialization of upstream atoms. currentTree:{// TODO snapshots shouldn't really have versions because a new version number // is always assigned when the snapshot is gone to. version:bumpVersion?version:treeState.version,stateID:bumpVersion?version:treeState.stateID,transactionMetadata:{...treeState.transactionMetadata},dirtyAtoms:new Set(treeState.dirtyAtoms),atomValues:treeState.atomValues.clone(),nonvalidatedAtoms:treeState.nonvalidatedAtoms.clone()},commitDepth:0,nextTree:null,previousTree:null,knownAtoms:new Set(storeState.knownAtoms),// FIXME here's a copy knownSelectors:new Set(storeState.knownSelectors),// FIXME here's a copy transactionSubscriptions:new Map(),nodeTransactionSubscriptions:new Map(),nodeToComponentSubscriptions:new Map(),queuedComponentCallbacks_DEPRECATED:[],suspendedComponentResolvers:new Set(),graphsByVersion:new Map().set(version,store.getGraph(treeState.version)),retention:{referenceCounts:new Map(),nodesRetainedByZone:new Map(),retainablesToCheckForRelease:new Set()},// FIXME here's a copy // Create blank cleanup handlers for atoms so snapshots don't re-run // atom effects. nodeCleanupFunctions:new Map(Recoil_mapIterable(storeState.nodeCleanupFunctions.entries(),([key])=>[key,()=>{}]))};}// Factory to build a fresh snapshot function freshSnapshot(initializeState){const snapshot=new Snapshot(makeEmptyStoreState$1());return initializeState!=null?snapshot.map(initializeState):snapshot;}// Factory to clone a snapshot state const[memoizedCloneSnapshot,invalidateMemoizedSnapshot$2]=memoizeOneWithArgsHashAndInvalidation$1(// $FlowFixMe[missing-local-annot] (store,version)=>{var _storeState$nextTree;const storeState=store.getState();const treeState=version==='latest'?(_storeState$nextTree=storeState.nextTree)!==null&&_storeState$nextTree!==void 0?_storeState$nextTree:storeState.currentTree:Recoil_nullthrows(storeState.previousTree);return new Snapshot(cloneStoreState(store,treeState),store.storeID);},(store,version)=>{var _store$getState$nextT,_store$getState$previ;return String(version)+String(store.storeID)+String((_store$getState$nextT=store.getState().nextTree)===null||_store$getState$nextT===void 0?void 0:_store$getState$nextT.version)+String(store.getState().currentTree.version)+String((_store$getState$previ=store.getState().previousTree)===null||_store$getState$previ===void 0?void 0:_store$getState$previ.version);});// Avoid circular dependencies setInvalidateMemoizedSnapshot$1(invalidateMemoizedSnapshot$2);function cloneSnapshot(store,version='latest'){const snapshot=memoizedCloneSnapshot(store,version);if(!snapshot.isRetained()){invalidateMemoizedSnapshot$2();return memoizedCloneSnapshot(store,version);}return snapshot;}class MutableSnapshot extends Snapshot{constructor(snapshot,batch){super(cloneStoreState(snapshot.getStore_INTERNAL(),snapshot.getStore_INTERNAL().getState().currentTree,true),snapshot.getStoreID());_defineProperty(this,"_batch",void 0);_defineProperty(this,"set",(recoilState,newValueOrUpdater)=>{this.checkRefCount_INTERNAL();const store=this.getStore_INTERNAL();// This batchUpdates ensures this `set` is applied immediately and you can // read the written value after calling `set`. I would like to remove this // behavior and only batch in `Snapshot.map`, but this would be a breaking // change potentially. this._batch(()=>{updateRetainCount$1(store,recoilState.key,1);setRecoilValue$1(this.getStore_INTERNAL(),recoilState,newValueOrUpdater);});});_defineProperty(this,"reset",recoilState=>{this.checkRefCount_INTERNAL();const store=this.getStore_INTERNAL();// See note at `set` about batched updates. this._batch(()=>{updateRetainCount$1(store,recoilState.key,1);setRecoilValue$1(this.getStore_INTERNAL(),recoilState,DEFAULT_VALUE$1);});});_defineProperty(this,"setUnvalidatedAtomValues_DEPRECATED",values=>{this.checkRefCount_INTERNAL();const store=this.getStore_INTERNAL();// See note at `set` about batched updates. batchUpdates$1(()=>{for(const[k,v]of values.entries()){updateRetainCount$1(store,k,1);setUnvalidatedRecoilValue$1(store,new AbstractRecoilValue$2(k),v);}});});this._batch=batch;}}var Recoil_Snapshot={Snapshot,MutableSnapshot,freshSnapshot,cloneSnapshot};var Recoil_Snapshot_1=Recoil_Snapshot.Snapshot;var Recoil_Snapshot_2=Recoil_Snapshot.MutableSnapshot;var Recoil_Snapshot_3=Recoil_Snapshot.freshSnapshot;var Recoil_Snapshot_4=Recoil_Snapshot.cloneSnapshot;var Recoil_Snapshot$1=/*#__PURE__*/Object.freeze({__proto__:null,Snapshot:Recoil_Snapshot_1,MutableSnapshot:Recoil_Snapshot_2,freshSnapshot:Recoil_Snapshot_3,cloneSnapshot:Recoil_Snapshot_4});/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format * @oncall recoil */function unionSets(...sets){const result=new Set();for(const set of sets){for(const value of set){result.add(value);}}return result;}var Recoil_unionSets=unionSets;const{useRef}=React;/** * The same as `useRef()` except that if a function is specified then it will * call that function to get the value to initialize the reference with. * This is similar to how `useState()` behaves when given a function. It allows * the user to avoid generating the initial value for subsequent renders. * The tradeoff is that to set the reference to a function itself you need to * nest it: useRefInitOnce(() => () => {...}); */function useRefInitOnce(initialValue){// $FlowExpectedError[incompatible-call] const ref=useRef(initialValue);if(ref.current===initialValue&&typeof initialValue==='function'){// $FlowExpectedError[incompatible-use] ref.current=initialValue();}return ref;}var Recoil_useRefInitOnce=useRefInitOnce;// @fb-only: const RecoilusagelogEvent = require('RecoilusagelogEvent'); // @fb-only: const RecoilUsageLogFalcoEvent = require('RecoilUsageLogFalcoEvent'); // @fb-only: const URI = require('URI'); const{getNextTreeStateVersion:getNextTreeStateVersion$3,makeEmptyStoreState:makeEmptyStoreState$2}=Recoil_State;const{cleanUpNode:cleanUpNode$2,getDownstreamNodes:getDownstreamNodes$2,initializeNode:initializeNode$2,setNodeValue:setNodeValue$2,setUnvalidatedAtomValue_DEPRECATED:setUnvalidatedAtomValue_DEPRECATED$1}=Recoil_FunctionalCore;const{graph:graph$2}=Recoil_Graph;const{cloneGraph:cloneGraph$1}=Recoil_Graph;const{getNextStoreID:getNextStoreID$2}=Recoil_Keys;const{createMutableSource:createMutableSource$1,reactMode:reactMode$2}=Recoil_ReactMode;const{applyAtomValueWrites:applyAtomValueWrites$1}=Recoil_RecoilValueInterface;const{releaseScheduledRetainablesNow:releaseScheduledRetainablesNow$1}=Recoil_Retention;const{freshSnapshot:freshSnapshot$1}=Recoil_Snapshot$1;const{useCallback,useContext,useEffect,useMemo,useRef:useRef$1,useState}=React;function notInAContext(){throw Recoil_err('This component must be used inside a component.');}const defaultStore=Object.freeze({storeID:getNextStoreID$2(),getState:notInAContext,replaceState:notInAContext,getGraph:notInAContext,subscribeToTransactions:notInAContext,addTransactionMetadata:notInAContext});let stateReplacerIsBeingExecuted=false;function startNextTreeIfNeeded(store){if(stateReplacerIsBeingExecuted){throw Recoil_err('An atom update was triggered within the execution of a state updater function. State updater functions provided to Recoil must be pure functions.');}const storeState=store.getState();if(storeState.nextTree===null){if(Recoil_gkx('recoil_memory_managament_2020')&&Recoil_gkx('recoil_release_on_cascading_update_killswitch_2021')){// If this is a cascading update (that is, rendering due to one state change // invokes a second state change), we won't have cleaned up retainables yet // because this normally happens after notifying components. Do it before // proceeding with the cascading update so that it remains predictable: if(storeState.commitDepth>0){releaseScheduledRetainablesNow$1(store);}}const version=storeState.currentTree.version;const nextVersion=getNextTreeStateVersion$3();storeState.nextTree={...storeState.currentTree,version:nextVersion,stateID:nextVersion,dirtyAtoms:new Set(),transactionMetadata:{}};storeState.graphsByVersion.set(nextVersion,cloneGraph$1(Recoil_nullthrows(storeState.graphsByVersion.get(version))));}}const AppContext=/*#__PURE__*/React.createContext({current:defaultStore});const useStoreRef=()=>useContext(AppContext);// $FlowExpectedError[incompatible-call] const MutableSourceContext=/*#__PURE__*/React.createContext(null);function useRecoilMutableSource(){const mutableSource=useContext(MutableSourceContext);return mutableSource;}function notifyComponents(store,storeState,treeState){const dependentNodes=getDownstreamNodes$2(store,treeState,treeState.dirtyAtoms);for(const key of dependentNodes){const comps=storeState.nodeToComponentSubscriptions.get(key);if(comps){for(const[_subID,[_debugName,callback]]of comps){callback(treeState);}}}}function sendEndOfBatchNotifications(store){const storeState=store.getState();const treeState=storeState.currentTree;// Inform transaction subscribers of the transaction: const dirtyAtoms=treeState.dirtyAtoms;if(dirtyAtoms.size){// Execute Node-specific subscribers before global subscribers for(const[key,subscriptions]of storeState.nodeTransactionSubscriptions){if(dirtyAtoms.has(key)){for(const[_,subscription]of subscriptions){subscription(store);}}}for(const[_,subscription]of storeState.transactionSubscriptions){subscription(store);}if(!reactMode$2().early||storeState.suspendedComponentResolvers.size>0){// Notifying components is needed to wake from suspense, even when using // early rendering. notifyComponents(store,storeState,treeState);// Wake all suspended components so the right one(s) can try to re-render. // We need to wake up components not just when some asynchronous selector // resolved, but also when changing synchronous values because this may cause // a selector to change from asynchronous to synchronous, in which case there // would be no follow-up asynchronous resolution to wake us up. // TODO OPTIMIZATION Only wake up related downstream components storeState.suspendedComponentResolvers.forEach(cb=>cb());storeState.suspendedComponentResolvers.clear();}}// Special behavior ONLY invoked by useInterface. // FIXME delete queuedComponentCallbacks_DEPRECATED when deleting useInterface. storeState.queuedComponentCallbacks_DEPRECATED.forEach(cb=>cb(treeState));storeState.queuedComponentCallbacks_DEPRECATED.splice(0,storeState.queuedComponentCallbacks_DEPRECATED.length);}function endBatch(store){const storeState=store.getState();storeState.commitDepth++;try{const{nextTree}=storeState;// Ignore commits that are not because of Recoil transactions -- namely, // because something above RecoilRoot re-rendered: if(nextTree==null){return;}// nextTree is now committed -- note that copying and reset occurs when // a transaction begins, in startNextTreeIfNeeded: storeState.previousTree=storeState.currentTree;storeState.currentTree=nextTree;storeState.nextTree=null;sendEndOfBatchNotifications(store);if(storeState.previousTree!=null){storeState.graphsByVersion.delete(storeState.previousTree.version);}else {Recoil_recoverableViolation('Ended batch with no previous state, which is unexpected','recoil');}storeState.previousTree=null;if(Recoil_gkx('recoil_memory_managament_2020')){// Only release retainables if there were no writes during the end of the // batch. This avoids releasing something we might be about to use. if(nextTree==null){releaseScheduledRetainablesNow$1(store);}}}finally{storeState.commitDepth--;}}/* * The purpose of the Batcher is to observe when React batches end so that * Recoil state changes can be batched. Whenever Recoil state changes, we call * setState on the batcher. Then we wait for that change to be committed, which * signifies the end of the batch. That's when we respond to the Recoil change. */function Batcher({setNotifyBatcherOfChange}){const storeRef=useStoreRef();const[,setState]=useState([]);// $FlowFixMe[incompatible-call] setNotifyBatcherOfChange(()=>setState({}));useEffect(()=>{// $FlowFixMe[incompatible-call] setNotifyBatcherOfChange(()=>setState({}));// If an asynchronous selector resolves after the Batcher is unmounted, // notifyBatcherOfChange will still be called. An error gets thrown whenever // setState is called after a component is already unmounted, so this sets // notifyBatcherOfChange to be a no-op. return ()=>{setNotifyBatcherOfChange(()=>{});};},[setNotifyBatcherOfChange]);useEffect(()=>{// enqueueExecution runs this function immediately; it is only used to // manipulate the order of useEffects during tests, since React seems to // call useEffect in an unpredictable order sometimes. Recoil_Queue.enqueueExecution('Batcher',()=>{endBatch(storeRef.current);});});return null;}// which will no longer be needed. function initialStoreState_DEPRECATED(store,initializeState){const initial=makeEmptyStoreState$2();initializeState({set:(atom,value)=>{const state=initial.currentTree;const writes=setNodeValue$2(store,state,atom.key,value);const writtenNodes=new Set(writes.keys());const nonvalidatedAtoms=state.nonvalidatedAtoms.clone();for(const n of writtenNodes){nonvalidatedAtoms.delete(n);}initial.currentTree={...state,dirtyAtoms:Recoil_unionSets(state.dirtyAtoms,writtenNodes),atomValues:applyAtomValueWrites$1(state.atomValues,writes),// NB: PLEASE un-export applyAtomValueWrites when deleting this code nonvalidatedAtoms};},setUnvalidatedAtomValues:atomValues=>{// FIXME replace this with a mutative loop atomValues.forEach((v,k)=>{initial.currentTree=setUnvalidatedAtomValue_DEPRECATED$1(initial.currentTree,k,v);});}});return initial;}// Initialize state snapshot for for the initializeState prop. // Atom effect initialization takes precedence over this prop. // Any atom effects will be run before initialization, but then cleaned up, // they are then re-run when used as part of rendering. These semantics are // compatible with React StrictMode where effects may be re-run multiple times // but state initialization only happens once the first time. function initialStoreState(initializeState){// Initialize a snapshot and get its store const snapshot=freshSnapshot$1(initializeState);const storeState=snapshot.getStore_INTERNAL().getState();// Counteract the snapshot auto-release snapshot.retain();// Cleanup any effects run during initialization and clear the handlers so // they will re-initialize if used during rendering. This allows atom effect // initialization to take precedence over initializeState and be compatible // with StrictMode semantics. storeState.nodeCleanupFunctions.forEach(cleanup=>cleanup());storeState.nodeCleanupFunctions.clear();return storeState;}let nextID=0;function RecoilRoot_INTERNAL({initializeState_DEPRECATED,initializeState,store_INTERNAL:storeProp,// For use with React "context bridging" children}){// prettier-ignore // @fb-only: useEffect(() => { // @fb-only: if (gkx('recoil_usage_logging')) { // @fb-only: try { // @fb-only: RecoilUsageLogFalcoEvent.log(() => ({ // @fb-only: type: RecoilusagelogEvent.RECOIL_ROOT_MOUNTED, // @fb-only: path: URI.getRequestURI().getPath(), // @fb-only: })); // @fb-only: } catch { // @fb-only: recoverableViolation( // @fb-only: 'Error when logging Recoil Usage event', // @fb-only: 'recoil', // @fb-only: ); // @fb-only: } // @fb-only: } // @fb-only: }, []); let storeStateRef;// eslint-disable-line prefer-const const getGraph=version=>{const graphs=storeStateRef.current.graphsByVersion;if(graphs.has(version)){return Recoil_nullthrows(graphs.get(version));}const newGraph=graph$2();graphs.set(version,newGraph);return newGraph;};const subscribeToTransactions=(callback,key)=>{if(key==null){// Global transaction subscriptions const{transactionSubscriptions}=storeRef.current.getState();const id=nextID++;transactionSubscriptions.set(id,callback);return {release:()=>{transactionSubscriptions.delete(id);}};}else {// Node-specific transaction subscriptions: const{nodeTransactionSubscriptions}=storeRef.current.getState();if(!nodeTransactionSubscriptions.has(key)){nodeTransactionSubscriptions.set(key,new Map());}const id=nextID++;Recoil_nullthrows(nodeTransactionSubscriptions.get(key)).set(id,callback);return {release:()=>{const subs=nodeTransactionSubscriptions.get(key);if(subs){subs.delete(id);if(subs.size===0){nodeTransactionSubscriptions.delete(key);}}}};}};const addTransactionMetadata=metadata=>{startNextTreeIfNeeded(storeRef.current);for(const k of Object.keys(metadata)){Recoil_nullthrows(storeRef.current.getState().nextTree).transactionMetadata[k]=metadata[k];}};const replaceState=replacer=>{startNextTreeIfNeeded(storeRef.current);// Use replacer to get the next state: const nextTree=Recoil_nullthrows(storeStateRef.current.nextTree);let replaced;try{stateReplacerIsBeingExecuted=true;replaced=replacer(nextTree);}finally{stateReplacerIsBeingExecuted=false;}if(replaced===nextTree){return;}storeStateRef.current.nextTree=replaced;if(reactMode$2().early){notifyComponents(storeRef.current,storeStateRef.current,replaced);}Recoil_nullthrows(notifyBatcherOfChange.current)();};const notifyBatcherOfChange=useRef$1(null);const setNotifyBatcherOfChange=useCallback(x=>{notifyBatcherOfChange.current=x;},[notifyBatcherOfChange]);const storeRef=Recoil_useRefInitOnce(()=>storeProp!==null&&storeProp!==void 0?storeProp:{storeID:getNextStoreID$2(),getState:()=>storeStateRef.current,replaceState,getGraph,subscribeToTransactions,addTransactionMetadata});if(storeProp!=null){storeRef.current=storeProp;}storeStateRef=Recoil_useRefInitOnce(()=>initializeState_DEPRECATED!=null?initialStoreState_DEPRECATED(storeRef.current,initializeState_DEPRECATED):initializeState!=null?initialStoreState(initializeState):makeEmptyStoreState$2());const mutableSource=useMemo(()=>createMutableSource$1===null||createMutableSource$1===void 0?void 0:createMutableSource$1(storeStateRef,()=>storeStateRef.current.currentTree.version),[storeStateRef]);// Cleanup when the is unmounted useEffect(()=>{// React is free to call effect cleanup handlers and effects at will, the // deps array is only an optimization. For example, React strict mode // will execute each effect twice for testing. Therefore, we need symmetry // to re-initialize all known atoms after they were cleaned up. const store=storeRef.current;for(const atomKey of new Set(store.getState().knownAtoms)){initializeNode$2(store,atomKey,'get');}return ()=>{for(const atomKey of store.getState().knownAtoms){cleanUpNode$2(store,atomKey);}};},[storeRef]);return/*#__PURE__*/React.createElement(AppContext.Provider,{value:storeRef},/*#__PURE__*/React.createElement(MutableSourceContext.Provider,{value:mutableSource},/*#__PURE__*/React.createElement(Batcher,{setNotifyBatcherOfChange:setNotifyBatcherOfChange}),children));}function RecoilRoot(props){const{override,...propsExceptOverride}=props;const ancestorStoreRef=useStoreRef();if(override===false&&ancestorStoreRef.current!==defaultStore){// If ancestorStoreRef.current !== defaultStore, it means that this // RecoilRoot is not nested within another. return props.children;}return/*#__PURE__*/React.createElement(RecoilRoot_INTERNAL,propsExceptOverride);}function useRecoilStoreID(){return useStoreRef().current.storeID;}var Recoil_RecoilRoot={RecoilRoot,useStoreRef,useRecoilMutableSource,useRecoilStoreID,notifyComponents_FOR_TESTING:notifyComponents,sendEndOfBatchNotifications_FOR_TESTING:sendEndOfBatchNotifications};/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format * @oncall recoil */function shallowArrayEqual(a,b){if(a===b){return true;}if(a.length!==b.length){return false;}for(let i=0,l=a.length;i{// $FlowFixMe[incompatible-type] ref.current=value;});return ref.current;}var Recoil_usePrevious=usePrevious;const{useStoreRef:useStoreRef$1}=Recoil_RecoilRoot;const{SUSPENSE_TIMEOUT_MS:SUSPENSE_TIMEOUT_MS$1}=Recoil_Retention;const{updateRetainCount:updateRetainCount$2}=Recoil_Retention;const{RetentionZone:RetentionZone$3}=Recoil_RetentionZone;const{useEffect:useEffect$2,useRef:useRef$3}=React;const{isSSR:isSSR$2}=Recoil_Environment;// I don't see a way to avoid the any type here because we want to accept readable // and writable values with any type parameter, but normally with writable ones // RecoilState is not a subtype of RecoilState. // flowlint-line unclear-type:off function useRetain(toRetain){if(!Recoil_gkx('recoil_memory_managament_2020')){return;}// eslint-disable-next-line fb-www/react-hooks return useRetain_ACTUAL(toRetain);}function useRetain_ACTUAL(toRetain){const array=Array.isArray(toRetain)?toRetain:[toRetain];const retainables=array.map(a=>a instanceof RetentionZone$3?a:a.key);const storeRef=useStoreRef$1();useEffect$2(()=>{if(!Recoil_gkx('recoil_memory_managament_2020')){return;}const store=storeRef.current;if(timeoutID.current&&!isSSR$2){// Already performed a temporary retain on render, simply cancel the release // of that temporary retain. window.clearTimeout(timeoutID.current);timeoutID.current=null;}else {for(const r of retainables){updateRetainCount$2(store,r,1);}}return ()=>{for(const r of retainables){updateRetainCount$2(store,r,-1);}};// eslint-disable-next-line fb-www/react-hooks-deps },[storeRef,...retainables]);// We want to retain if the component suspends. This is terrible but the Suspense // API affords us no better option. If we suspend and never commit after some // seconds, then release. The 'actual' retain/release in the effect above // cancels this. const timeoutID=useRef$3();const previousRetainables=Recoil_usePrevious(retainables);if(!isSSR$2&&(previousRetainables===undefined||!Recoil_shallowArrayEqual(previousRetainables,retainables))){const store=storeRef.current;for(const r of retainables){updateRetainCount$2(store,r,1);}if(previousRetainables){for(const r of previousRetainables){updateRetainCount$2(store,r,-1);}}if(timeoutID.current){window.clearTimeout(timeoutID.current);}timeoutID.current=window.setTimeout(()=>{timeoutID.current=null;for(const r of retainables){updateRetainCount$2(store,r,-1);}},SUSPENSE_TIMEOUT_MS$1);}}var Recoil_useRetain=useRetain;/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format * @oncall recoil */ /** * THIS CODE HAS BEEN COMMENTED OUT INTENTIONALLY * * This technique of getting the component name is imperfect, since it both only * works in a non-minified code base, and more importantly introduces performance * problems since it relies in throwing errors which is an expensive operation. * * At some point we may want to reevaluate this technique hence why we have commented * this code out, rather than delete it all together. */ // const {useRef} = require('react'); // const gkx = require('recoil-shared/util/Recoil_gkx'); // const stackTraceParser = require('recoil-shared/util/Recoil_stackTraceParser'); function useComponentName(){// const nameRef = useRef(); // if (__DEV__) { // if (gkx('recoil_infer_component_names')) { // if (nameRef.current === undefined) { // // There is no blessed way to determine the calling React component from // // within a hook. This hack uses the fact that hooks must start with 'use' // // and that hooks are either called by React Components or other hooks. It // // follows therefore, that to find the calling component, you simply need // // to look down the stack and find the first function which doesn't start // // with 'use'. We are only enabling this in dev for now, since once the // // codebase is minified, the naming assumptions no longer hold true. // // eslint-disable-next-line fb-www/no-new-error // const frames = stackTraceParser(new Error().stack); // for (const {methodName} of frames) { // // I observed cases where the frame was of the form 'Object.useXXX' // // hence why I'm searching for hooks following a word boundary // if (!methodName.match(/\buse[^\b]+$/)) { // return (nameRef.current = methodName); // } // } // nameRef.current = null; // } // return nameRef.current ?? ''; // } // } // @fb-only: return ""; return '';// @oss-only }var Recoil_useComponentName=useComponentName;const{batchUpdates:batchUpdates$2}=Recoil_Batching;const{DEFAULT_VALUE:DEFAULT_VALUE$2}=Recoil_Node;const{currentRendererSupportsUseSyncExternalStore:currentRendererSupportsUseSyncExternalStore$1,reactMode:reactMode$3,useMutableSource:useMutableSource$1,useSyncExternalStore:useSyncExternalStore$1}=Recoil_ReactMode;const{useRecoilMutableSource:useRecoilMutableSource$1,useStoreRef:useStoreRef$2}=Recoil_RecoilRoot;const{AbstractRecoilValue:AbstractRecoilValue$3,getRecoilValueAsLoadable:getRecoilValueAsLoadable$2,setRecoilValue:setRecoilValue$2,setUnvalidatedRecoilValue:setUnvalidatedRecoilValue$2,subscribeToRecoilValue:subscribeToRecoilValue$1}=Recoil_RecoilValueInterface;const{useCallback:useCallback$1,useEffect:useEffect$3,useMemo:useMemo$1,useRef:useRef$4,useState:useState$1}=React;const{setByAddingToSet:setByAddingToSet$2}=Recoil_CopyOnWrite;const{isSSR:isSSR$3}=Recoil_Environment;function handleLoadable(loadable,recoilValue,storeRef){// We can't just throw the promise we are waiting on to Suspense. If the // upstream dependencies change it may produce a state in which the component // can render, but it would still be suspended on a Promise that may never resolve. if(loadable.state==='hasValue'){return loadable.contents;}else if(loadable.state==='loading'){const promise=new Promise(resolve=>{const suspendedComponentResolvers=storeRef.current.getState().suspendedComponentResolvers;suspendedComponentResolvers.add(resolve);// SSR should clear out the wake-up resolver if the Promise is resolved // to avoid infinite loops. (See https://github.com/facebookexperimental/Recoil/pull/2073) if(isSSR$3&&Recoil_isPromise(loadable.contents)){loadable.contents.finally(()=>{suspendedComponentResolvers.delete(resolve);});}});// $FlowExpectedError Flow(prop-missing) for integrating with tools that inspect thrown promises @fb-only // @fb-only: promise.displayName = `Recoil State: ${recoilValue.key}`; throw promise;}else if(loadable.state==='hasError'){throw loadable.contents;}else {throw Recoil_err(`Invalid value of loadable atom "${recoilValue.key}"`);}}/** * Various things are broken with useRecoilInterface, particularly concurrent * mode, React strict mode, and memory management. They will not be fixed. * */function useRecoilInterface_DEPRECATED(){const componentName=Recoil_useComponentName();const storeRef=useStoreRef$2();// eslint-disable-next-line fb-www/react-no-unused-state-hook const[,forceUpdate]=useState$1([]);const recoilValuesUsed=useRef$4(new Set());recoilValuesUsed.current=new Set();// Track the RecoilValues used just during this render const previousSubscriptions=useRef$4(new Set());const subscriptions=useRef$4(new Map());const unsubscribeFrom=useCallback$1(key=>{const sub=subscriptions.current.get(key);if(sub){sub.release();subscriptions.current.delete(key);}},[subscriptions]);const updateState=useCallback$1((_state,key)=>{if(subscriptions.current.has(key)){forceUpdate([]);}},[]);// Effect to add/remove subscriptions as nodes are used useEffect$3(()=>{const store=storeRef.current;Recoil_differenceSets(recoilValuesUsed.current,previousSubscriptions.current).forEach(key=>{if(subscriptions.current.has(key)){return;}const sub=subscribeToRecoilValue$1(store,new AbstractRecoilValue$3(key),state=>updateState(state,key),componentName);subscriptions.current.set(key,sub);/** * Since we're subscribing in an effect we need to update to the latest * value of the atom since it may have changed since we rendered. We can * go ahead and do that now, unless we're in the middle of a batch -- * in which case we should do it at the end of the batch, due to the * following edge case: Suppose an atom is updated in another useEffect * of this same component. Then the following sequence of events occur: * 1. Atom is updated and subs fired (but we may not be subscribed * yet depending on order of effects, so we miss this) Updated value * is now in nextTree, but not currentTree. * 2. This effect happens. We subscribe and update. * 3. From the update we re-render and read currentTree, with old value. * 4. Batcher's effect sets currentTree to nextTree. * In this sequence we miss the update. To avoid that, add the update * to queuedComponentCallback if a batch is in progress. */ // FIXME delete queuedComponentCallbacks_DEPRECATED when deleting useInterface. const state=store.getState();if(state.nextTree){store.getState().queuedComponentCallbacks_DEPRECATED.push(()=>{updateState(store.getState(),key);});}else {updateState(store.getState(),key);}});Recoil_differenceSets(previousSubscriptions.current,recoilValuesUsed.current).forEach(key=>{unsubscribeFrom(key);});previousSubscriptions.current=recoilValuesUsed.current;});// Effect to unsubscribe from all when unmounting useEffect$3(()=>{const currentSubscriptions=subscriptions.current;// Restore subscriptions that were cleared due to StrictMode running this effect twice Recoil_differenceSets(recoilValuesUsed.current,new Set(currentSubscriptions.keys())).forEach(key=>{const sub=subscribeToRecoilValue$1(storeRef.current,new AbstractRecoilValue$3(key),state=>updateState(state,key),componentName);currentSubscriptions.set(key,sub);});return ()=>currentSubscriptions.forEach((_,key)=>unsubscribeFrom(key));},[componentName,storeRef,unsubscribeFrom,updateState]);return useMemo$1(()=>{// eslint-disable-next-line no-shadow function useSetRecoilState(recoilState){return newValueOrUpdater=>{setRecoilValue$2(storeRef.current,recoilState,newValueOrUpdater);};}// eslint-disable-next-line no-shadow function useResetRecoilState(recoilState){return ()=>setRecoilValue$2(storeRef.current,recoilState,DEFAULT_VALUE$2);}// eslint-disable-next-line no-shadow function useRecoilValueLoadable(recoilValue){var _storeState$nextTree;if(!recoilValuesUsed.current.has(recoilValue.key)){recoilValuesUsed.current=setByAddingToSet$2(recoilValuesUsed.current,recoilValue.key);}// TODO Restore optimization to memoize lookup const storeState=storeRef.current.getState();return getRecoilValueAsLoadable$2(storeRef.current,recoilValue,reactMode$3().early?(_storeState$nextTree=storeState.nextTree)!==null&&_storeState$nextTree!==void 0?_storeState$nextTree:storeState.currentTree:storeState.currentTree);}// eslint-disable-next-line no-shadow function useRecoilValue(recoilValue){const loadable=useRecoilValueLoadable(recoilValue);return handleLoadable(loadable,recoilValue,storeRef);}// eslint-disable-next-line no-shadow function useRecoilState(recoilState){return [useRecoilValue(recoilState),useSetRecoilState(recoilState)];}// eslint-disable-next-line no-shadow function useRecoilStateLoadable(recoilState){return [useRecoilValueLoadable(recoilState),useSetRecoilState(recoilState)];}return {getRecoilValue:useRecoilValue,getRecoilValueLoadable:useRecoilValueLoadable,getRecoilState:useRecoilState,getRecoilStateLoadable:useRecoilStateLoadable,getSetRecoilState:useSetRecoilState,getResetRecoilState:useResetRecoilState};},[recoilValuesUsed,storeRef]);}const recoilComponentGetRecoilValueCount_FOR_TESTING={current:0};function useRecoilValueLoadable_SYNC_EXTERNAL_STORE(recoilValue){const storeRef=useStoreRef$2();const componentName=Recoil_useComponentName();const getSnapshot=useCallback$1(()=>{var _storeState$nextTree2;const store=storeRef.current;const storeState=store.getState();const treeState=reactMode$3().early?(_storeState$nextTree2=storeState.nextTree)!==null&&_storeState$nextTree2!==void 0?_storeState$nextTree2:storeState.currentTree:storeState.currentTree;const loadable=getRecoilValueAsLoadable$2(store,recoilValue,treeState);return {loadable,key:recoilValue.key};},[storeRef,recoilValue]);// Memoize the state to avoid unnecessary rerenders const memoizePreviousSnapshot=useCallback$1(getState=>{let prevState;return ()=>{var _prevState,_prevState2;const nextState=getState();if((_prevState=prevState)!==null&&_prevState!==void 0&&_prevState.loadable.is(nextState.loadable)&&((_prevState2=prevState)===null||_prevState2===void 0?void 0:_prevState2.key)===nextState.key){return prevState;}prevState=nextState;return nextState;};},[]);const getMemoizedSnapshot=useMemo$1(()=>memoizePreviousSnapshot(getSnapshot),[getSnapshot,memoizePreviousSnapshot]);const subscribe=useCallback$1(notify=>{const store=storeRef.current;const subscription=subscribeToRecoilValue$1(store,recoilValue,notify,componentName);return subscription.release;},[storeRef,recoilValue,componentName]);return useSyncExternalStore$1(subscribe,getMemoizedSnapshot,// getSnapshot() getMemoizedSnapshot// getServerSnapshot() for SSR support ).loadable;}function useRecoilValueLoadable_MUTABLE_SOURCE(recoilValue){const storeRef=useStoreRef$2();const getLoadable=useCallback$1(()=>{var _storeState$nextTree3;const store=storeRef.current;const storeState=store.getState();const treeState=reactMode$3().early?(_storeState$nextTree3=storeState.nextTree)!==null&&_storeState$nextTree3!==void 0?_storeState$nextTree3:storeState.currentTree:storeState.currentTree;return getRecoilValueAsLoadable$2(store,recoilValue,treeState);},[storeRef,recoilValue]);const getLoadableWithTesting=useCallback$1(()=>{return getLoadable();},[getLoadable]);const componentName=Recoil_useComponentName();const subscribe=useCallback$1((_storeState,notify)=>{const store=storeRef.current;const subscription=subscribeToRecoilValue$1(store,recoilValue,()=>{if(!Recoil_gkx('recoil_suppress_rerender_in_callback')){return notify();}// Only re-render if the value has changed. // This will evaluate the atom/selector now as well as when the // component renders, but that may help with prefetching. const newLoadable=getLoadable();if(!prevLoadableRef.current.is(newLoadable)){notify();}// If the component is suspended then the effect setting prevLoadableRef // will not run. So, set the previous value here when its subscription // is fired to wake it up. We can't just rely on this, though, because // this only executes when an atom/selector is dirty and the atom/selector // passed to the hook can dynamically change. prevLoadableRef.current=newLoadable;},componentName);return subscription.release;},[storeRef,recoilValue,componentName,getLoadable]);const source=useRecoilMutableSource$1();if(source==null){throw Recoil_err('Recoil hooks must be used in components contained within a component.');}const loadable=useMutableSource$1(source,getLoadableWithTesting,subscribe);const prevLoadableRef=useRef$4(loadable);useEffect$3(()=>{prevLoadableRef.current=loadable;});return loadable;}function useRecoilValueLoadable_TRANSITION_SUPPORT(recoilValue){const storeRef=useStoreRef$2();const componentName=Recoil_useComponentName();// Accessors to get the current state const getLoadable=useCallback$1(()=>{var _storeState$nextTree4;const store=storeRef.current;const storeState=store.getState();const treeState=reactMode$3().early?(_storeState$nextTree4=storeState.nextTree)!==null&&_storeState$nextTree4!==void 0?_storeState$nextTree4:storeState.currentTree:storeState.currentTree;return getRecoilValueAsLoadable$2(store,recoilValue,treeState);},[storeRef,recoilValue]);const getState=useCallback$1(()=>({loadable:getLoadable(),key:recoilValue.key}),[getLoadable,recoilValue.key]);// Memoize state snapshots const updateState=useCallback$1(prevState=>{const nextState=getState();return prevState.loadable.is(nextState.loadable)&&prevState.key===nextState.key?prevState:nextState;},[getState]);// Subscribe to Recoil state changes useEffect$3(()=>{const subscription=subscribeToRecoilValue$1(storeRef.current,recoilValue,_state=>{setState(updateState);},componentName);// Update state in case we are using a different key setState(updateState);return subscription.release;},[componentName,recoilValue,storeRef,updateState]);// Get the current state const[state,setState]=useState$1(getState);// If we changed keys, then return the state for the new key. // This is important in case the old key would cause the component to suspend. // We don't have to set the new state here since the subscribing effect above // will do that. return state.key!==recoilValue.key?getState().loadable:state.loadable;}function useRecoilValueLoadable_LEGACY(recoilValue){const storeRef=useStoreRef$2();// eslint-disable-next-line fb-www/react-no-unused-state-hook const[,forceUpdate]=useState$1([]);const componentName=Recoil_useComponentName();const getLoadable=useCallback$1(()=>{var _storeState$nextTree5;const store=storeRef.current;const storeState=store.getState();const treeState=reactMode$3().early?(_storeState$nextTree5=storeState.nextTree)!==null&&_storeState$nextTree5!==void 0?_storeState$nextTree5:storeState.currentTree:storeState.currentTree;return getRecoilValueAsLoadable$2(store,recoilValue,treeState);},[storeRef,recoilValue]);const loadable=getLoadable();const prevLoadableRef=useRef$4(loadable);useEffect$3(()=>{prevLoadableRef.current=loadable;});useEffect$3(()=>{const store=storeRef.current;const storeState=store.getState();const subscription=subscribeToRecoilValue$1(store,recoilValue,_state=>{var _prevLoadableRef$curr;if(!Recoil_gkx('recoil_suppress_rerender_in_callback')){return forceUpdate([]);}const newLoadable=getLoadable();if(!((_prevLoadableRef$curr=prevLoadableRef.current)!==null&&_prevLoadableRef$curr!==void 0&&_prevLoadableRef$curr.is(newLoadable))){// $FlowFixMe[incompatible-call] forceUpdate(newLoadable);}prevLoadableRef.current=newLoadable;},componentName);/** * Since we're subscribing in an effect we need to update to the latest * value of the atom since it may have changed since we rendered. We can * go ahead and do that now, unless we're in the middle of a batch -- * in which case we should do it at the end of the batch, due to the * following edge case: Suppose an atom is updated in another useEffect * of this same component. Then the following sequence of events occur: * 1. Atom is updated and subs fired (but we may not be subscribed * yet depending on order of effects, so we miss this) Updated value * is now in nextTree, but not currentTree. * 2. This effect happens. We subscribe and update. * 3. From the update we re-render and read currentTree, with old value. * 4. Batcher's effect sets currentTree to nextTree. * In this sequence we miss the update. To avoid that, add the update * to queuedComponentCallback if a batch is in progress. */if(storeState.nextTree){store.getState().queuedComponentCallbacks_DEPRECATED.push(()=>{// $FlowFixMe[incompatible-type] prevLoadableRef.current=null;forceUpdate([]);});}else {var _prevLoadableRef$curr2;if(!Recoil_gkx('recoil_suppress_rerender_in_callback')){return forceUpdate([]);}const newLoadable=getLoadable();if(!((_prevLoadableRef$curr2=prevLoadableRef.current)!==null&&_prevLoadableRef$curr2!==void 0&&_prevLoadableRef$curr2.is(newLoadable))){// $FlowFixMe[incompatible-call] forceUpdate(newLoadable);}prevLoadableRef.current=newLoadable;}return subscription.release;},[componentName,getLoadable,recoilValue,storeRef]);return loadable;}/** Like useRecoilValue(), but either returns the value if available or just undefined if not available for any reason, such as pending or error. */function useRecoilValueLoadable(recoilValue){if(Recoil_gkx('recoil_memory_managament_2020')){// eslint-disable-next-line fb-www/react-hooks Recoil_useRetain(recoilValue);}return {TRANSITION_SUPPORT:useRecoilValueLoadable_TRANSITION_SUPPORT,// Recoil will attemp to detect if `useSyncExternalStore()` is supported with // `reactMode()` before calling it. However, sometimes the host React // environment supports it but uses additional React renderers (such as with // `react-three-fiber`) which do not. While this is technically a user issue // by using a renderer with React 18+ that doesn't fully support React 18 we // don't want to break users if it can be avoided. As the current renderer can // change at runtime, we need to dynamically check and fallback if necessary. SYNC_EXTERNAL_STORE:currentRendererSupportsUseSyncExternalStore$1()?useRecoilValueLoadable_SYNC_EXTERNAL_STORE:useRecoilValueLoadable_TRANSITION_SUPPORT,MUTABLE_SOURCE:useRecoilValueLoadable_MUTABLE_SOURCE,LEGACY:useRecoilValueLoadable_LEGACY}[reactMode$3().mode](recoilValue);}/** Returns the value represented by the RecoilValue. If the value is pending, it will throw a Promise to suspend the component, if the value is an error it will throw it for the nearest React error boundary. This will also subscribe the component for any updates in the value. */function useRecoilValue(recoilValue){const storeRef=useStoreRef$2();const loadable=useRecoilValueLoadable(recoilValue);return handleLoadable(loadable,recoilValue,storeRef);}/** Returns a function that allows the value of a RecoilState to be updated, but does not subscribe the component to changes to that RecoilState. */function useSetRecoilState(recoilState){const storeRef=useStoreRef$2();return useCallback$1(newValueOrUpdater=>{setRecoilValue$2(storeRef.current,recoilState,newValueOrUpdater);},[storeRef,recoilState]);}/** Returns a function that will reset the value of a RecoilState to its default */function useResetRecoilState(recoilState){const storeRef=useStoreRef$2();return useCallback$1(()=>{setRecoilValue$2(storeRef.current,recoilState,DEFAULT_VALUE$2);},[storeRef,recoilState]);}/** Equivalent to useState(). Allows the value of the RecoilState to be read and written. Subsequent updates to the RecoilState will cause the component to re-render. If the RecoilState is pending, this will suspend the component and initiate the retrieval of the value. If evaluating the RecoilState resulted in an error, this will throw the error so that the nearest React error boundary can catch it. */function useRecoilState(recoilState){return [useRecoilValue(recoilState),useSetRecoilState(recoilState)];}/** Like useRecoilState(), but does not cause Suspense or React error handling. Returns an object that indicates whether the RecoilState is available, pending, or unavailable due to an error. */function useRecoilStateLoadable(recoilState){return [useRecoilValueLoadable(recoilState),useSetRecoilState(recoilState)];}function useSetUnvalidatedAtomValues(){const storeRef=useStoreRef$2();return (values,transactionMetadata={})=>{batchUpdates$2(()=>{storeRef.current.addTransactionMetadata(transactionMetadata);values.forEach((value,key)=>setUnvalidatedRecoilValue$2(storeRef.current,new AbstractRecoilValue$3(key),value));});};}/** * Experimental variants of hooks with support for useTransition() */function useRecoilValueLoadable_TRANSITION_SUPPORT_UNSTABLE(recoilValue){if(Recoil_gkx('recoil_memory_managament_2020')){// eslint-disable-next-line fb-www/react-hooks Recoil_useRetain(recoilValue);}return useRecoilValueLoadable_TRANSITION_SUPPORT(recoilValue);}function useRecoilValue_TRANSITION_SUPPORT_UNSTABLE(recoilValue){const storeRef=useStoreRef$2();const loadable=useRecoilValueLoadable_TRANSITION_SUPPORT_UNSTABLE(recoilValue);return handleLoadable(loadable,recoilValue,storeRef);}function useRecoilState_TRANSITION_SUPPORT_UNSTABLE(recoilState){return [useRecoilValue_TRANSITION_SUPPORT_UNSTABLE(recoilState),useSetRecoilState(recoilState)];}var Recoil_Hooks={recoilComponentGetRecoilValueCount_FOR_TESTING,useRecoilInterface:useRecoilInterface_DEPRECATED,useRecoilState,useRecoilStateLoadable,useRecoilValue,useRecoilValueLoadable,useResetRecoilState,useSetRecoilState,useSetUnvalidatedAtomValues,useRecoilValueLoadable_TRANSITION_SUPPORT_UNSTABLE,useRecoilValue_TRANSITION_SUPPORT_UNSTABLE,useRecoilState_TRANSITION_SUPPORT_UNSTABLE};/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format * @oncall recoil */ /** * Returns a map containing all of the keys + values from the original map where * the given callback returned true. */function filterMap(map,callback){const result=new Map();for(const[key,value]of map){if(callback(value,key)){result.set(key,value);}}return result;}var Recoil_filterMap=filterMap;/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format * @oncall recoil */ /** * Returns a set containing all of the values from the original set where * the given callback returned true. */function filterSet(set,callback){const result=new Set();for(const value of set){if(callback(value)){result.add(value);}}return result;}var Recoil_filterSet=filterSet;/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format * @oncall recoil */function mergeMaps(...maps){const result=new Map();for(let i=0;i{const sub=storeRef.current.subscribeToTransactions(callback);return sub.release;},[callback,storeRef]);}function externallyVisibleAtomValuesInState(state){const atomValues=state.atomValues.toMap();const persistedAtomContentsValues=Recoil_mapMap(Recoil_filterMap(atomValues,(v,k)=>{const node=getNode$4(k);const persistence=node.persistence_UNSTABLE;return persistence!=null&&persistence.type!=='none'&&v.state==='hasValue';}),v=>v.contents);// Merge in nonvalidated atoms; we may not have defs for them but they will // all have persistence on or they wouldn't be there in the first place. return Recoil_mergeMaps(state.nonvalidatedAtoms.toMap(),persistedAtomContentsValues);}/** Calls the given callback after any atoms have been modified and the consequent component re-renders have been committed. This is intended for persisting the values of the atoms to storage. The stored values can then be restored using the useSetUnvalidatedAtomValues hook. The callback receives the following info: atomValues: The current value of every atom that is both persistable (persistence type not set to 'none') and whose value is available (not in an error or loading state). previousAtomValues: The value of every persistable and available atom before the transaction began. atomInfo: A map containing the persistence settings for each atom. Every key that exists in atomValues will also exist in atomInfo. modifiedAtoms: The set of atoms that were written to during the transaction. transactionMetadata: Arbitrary information that was added via the useSetUnvalidatedAtomValues hook. Useful for ignoring the useSetUnvalidatedAtomValues transaction, to avoid loops. */function useTransactionObservation_DEPRECATED(callback){useTransactionSubscription(useCallback$2(store=>{let previousTree=store.getState().previousTree;const currentTree=store.getState().currentTree;if(!previousTree){previousTree=store.getState().currentTree;// attempt to trundle on }const atomValues=externallyVisibleAtomValuesInState(currentTree);const previousAtomValues=externallyVisibleAtomValuesInState(previousTree);const atomInfo=Recoil_mapMap(nodes$1,node=>{var _node$persistence_UNS,_node$persistence_UNS2,_node$persistence_UNS3,_node$persistence_UNS4;return {persistence_UNSTABLE:{type:(_node$persistence_UNS=(_node$persistence_UNS2=node.persistence_UNSTABLE)===null||_node$persistence_UNS2===void 0?void 0:_node$persistence_UNS2.type)!==null&&_node$persistence_UNS!==void 0?_node$persistence_UNS:'none',backButton:(_node$persistence_UNS3=(_node$persistence_UNS4=node.persistence_UNSTABLE)===null||_node$persistence_UNS4===void 0?void 0:_node$persistence_UNS4.backButton)!==null&&_node$persistence_UNS3!==void 0?_node$persistence_UNS3:false}};});// Filter on existance in atomValues so that externally-visible rules // are also applied to modified atoms (specifically exclude selectors): const modifiedAtoms=Recoil_filterSet(currentTree.dirtyAtoms,k=>atomValues.has(k)||previousAtomValues.has(k));callback({atomValues,previousAtomValues,atomInfo,modifiedAtoms,transactionMetadata:{...currentTree.transactionMetadata}});},[callback]));}function useRecoilTransactionObserver(callback){useTransactionSubscription(useCallback$2(store=>{const snapshot=cloneSnapshot$1(store,'latest');const previousSnapshot=cloneSnapshot$1(store,'previous');callback({snapshot,previousSnapshot});},[callback]));}// Return a snapshot of the current state and subscribe to all state changes function useRecoilSnapshot(){const storeRef=useStoreRef$3();const[snapshot,setSnapshot]=useState$2(()=>cloneSnapshot$1(storeRef.current));const previousSnapshot=Recoil_usePrevious(snapshot);const timeoutID=useRef$5();const releaseRef=useRef$5();useTransactionSubscription(useCallback$2(store=>setSnapshot(cloneSnapshot$1(store)),[]));// Retain snapshot for duration component is mounted useEffect$4(()=>{const release=snapshot.retain();// Release the retain from the rendering call if(timeoutID.current&&!isSSR$4){var _releaseRef$current;window.clearTimeout(timeoutID.current);timeoutID.current=null;(_releaseRef$current=releaseRef.current)===null||_releaseRef$current===void 0?void 0:_releaseRef$current.call(releaseRef);releaseRef.current=null;}return ()=>{// Defer the release. If "Fast Refresh"" is used then the component may // re-render with the same state. The previous cleanup will then run and // then the new effect will run. We don't want the snapshot to be released // by that cleanup before the new effect has a chance to retain it again. // Use timeout of 10 to workaround Firefox issue: https://github.com/facebookexperimental/Recoil/issues/1936 window.setTimeout(release,10);};},[snapshot]);// Retain snapshot until above effect is run. // Release after a threshold in case component is suspended. if(previousSnapshot!==snapshot&&!isSSR$4){// Release the previous snapshot if(timeoutID.current){var _releaseRef$current2;window.clearTimeout(timeoutID.current);timeoutID.current=null;(_releaseRef$current2=releaseRef.current)===null||_releaseRef$current2===void 0?void 0:_releaseRef$current2.call(releaseRef);releaseRef.current=null;}releaseRef.current=snapshot.retain();timeoutID.current=window.setTimeout(()=>{var _releaseRef$current3;timeoutID.current=null;(_releaseRef$current3=releaseRef.current)===null||_releaseRef$current3===void 0?void 0:_releaseRef$current3.call(releaseRef);releaseRef.current=null;},SUSPENSE_TIMEOUT_MS$2);}return snapshot;}function gotoSnapshot(store,snapshot){var _storeState$nextTree;const storeState=store.getState();const prev=(_storeState$nextTree=storeState.nextTree)!==null&&_storeState$nextTree!==void 0?_storeState$nextTree:storeState.currentTree;const next=snapshot.getStore_INTERNAL().getState().currentTree;batchUpdates$3(()=>{const keysToUpdate=new Set();for(const keys of [prev.atomValues.keys(),next.atomValues.keys()]){for(const key of keys){var _prev$atomValues$get,_next$atomValues$get;if(((_prev$atomValues$get=prev.atomValues.get(key))===null||_prev$atomValues$get===void 0?void 0:_prev$atomValues$get.contents)!==((_next$atomValues$get=next.atomValues.get(key))===null||_next$atomValues$get===void 0?void 0:_next$atomValues$get.contents)&&getNode$4(key).shouldRestoreFromSnapshots){keysToUpdate.add(key);}}}keysToUpdate.forEach(key=>{setRecoilValueLoadable$1(store,new AbstractRecoilValue$4(key),next.atomValues.has(key)?Recoil_nullthrows(next.atomValues.get(key)):DEFAULT_VALUE$3);});store.replaceState(state=>({...state,stateID:snapshot.getID()}));});}function useGotoRecoilSnapshot(){const storeRef=useStoreRef$3();return useCallback$2(snapshot=>gotoSnapshot(storeRef.current,snapshot),[storeRef]);}var Recoil_SnapshotHooks={useRecoilSnapshot,gotoSnapshot,useGotoRecoilSnapshot,useRecoilTransactionObserver,useTransactionObservation_DEPRECATED,useTransactionSubscription_DEPRECATED:useTransactionSubscription};const{peekNodeInfo:peekNodeInfo$2}=Recoil_FunctionalCore;const{useStoreRef:useStoreRef$4}=Recoil_RecoilRoot;function useGetRecoilValueInfo(){const storeRef=useStoreRef$4();// $FlowFixMe[incompatible-return] return ({key})=>peekNodeInfo$2(storeRef.current,storeRef.current.getState().currentTree,key);}var Recoil_useGetRecoilValueInfo=useGetRecoilValueInfo;const{reactMode:reactMode$4}=Recoil_ReactMode;const{RecoilRoot:RecoilRoot$1,useStoreRef:useStoreRef$5}=Recoil_RecoilRoot;const{useMemo:useMemo$2}=React;function useRecoilBridgeAcrossReactRoots(){// The test fails when using useMutableSource(), but only if act() is used // for the nested root. So, this may only be a testing environment issue. if(reactMode$4().mode==='MUTABLE_SOURCE'){// eslint-disable-next-line fb-www/no-console console.warn('Warning: There are known issues using useRecoilBridgeAcrossReactRoots() in recoil_mutable_source rendering mode. Please consider upgrading to recoil_sync_external_store mode.');}const store=useStoreRef$5().current;return useMemo$2(()=>{// eslint-disable-next-line no-shadow function RecoilBridge({children}){return/*#__PURE__*/React.createElement(RecoilRoot$1,{store_INTERNAL:store},children);}return RecoilBridge;},[store]);}var Recoil_useRecoilBridgeAcrossReactRoots=useRecoilBridgeAcrossReactRoots;const{loadableWithValue:loadableWithValue$1}=Recoil_Loadable$1;const{initializeNode:initializeNode$3}=Recoil_FunctionalCore;const{DEFAULT_VALUE:DEFAULT_VALUE$4,getNode:getNode$5}=Recoil_Node;const{copyTreeState:copyTreeState$1,getRecoilValueAsLoadable:getRecoilValueAsLoadable$3,invalidateDownstreams:invalidateDownstreams$1,writeLoadableToTreeState:writeLoadableToTreeState$1}=Recoil_RecoilValueInterface;function isAtom(recoilValue){return getNode$5(recoilValue.key).nodeType==='atom';}class TransactionInterfaceImpl{constructor(store,treeState){_defineProperty(this,"_store",void 0);_defineProperty(this,"_treeState",void 0);_defineProperty(this,"_changes",void 0);_defineProperty(this,"get",recoilValue=>{if(this._changes.has(recoilValue.key)){// $FlowIssue[incompatible-return] return this._changes.get(recoilValue.key);}if(!isAtom(recoilValue)){throw Recoil_err('Reading selectors within atomicUpdate is not supported');}const loadable=getRecoilValueAsLoadable$3(this._store,recoilValue,this._treeState);if(loadable.state==='hasValue'){return loadable.contents;}else if(loadable.state==='hasError'){throw loadable.contents;}else {throw Recoil_err(`Expected Recoil atom ${recoilValue.key} to have a value, but it is in a loading state.`);}});_defineProperty(this,"set",(recoilState,valueOrUpdater)=>{if(!isAtom(recoilState)){throw Recoil_err('Setting selectors within atomicUpdate is not supported');}if(typeof valueOrUpdater==='function'){const current=this.get(recoilState);this._changes.set(recoilState.key,valueOrUpdater(current));// flowlint-line unclear-type:off }else {// Initialize atom and run effects if not initialized yet initializeNode$3(this._store,recoilState.key,'set');this._changes.set(recoilState.key,valueOrUpdater);}});_defineProperty(this,"reset",recoilState=>{this.set(recoilState,DEFAULT_VALUE$4);});this._store=store;this._treeState=treeState;this._changes=new Map();}// Allow destructing // eslint-disable-next-line fb-www/extra-arrow-initializer newTreeState_INTERNAL(){if(this._changes.size===0){return this._treeState;}const newState=copyTreeState$1(this._treeState);for(const[k,v]of this._changes){writeLoadableToTreeState$1(newState,k,loadableWithValue$1(v));}invalidateDownstreams$1(this._store,newState);return newState;}}function atomicUpdater(store){return fn=>{store.replaceState(treeState=>{const changeset=new TransactionInterfaceImpl(store,treeState);fn(changeset);return changeset.newTreeState_INTERNAL();});};}var Recoil_AtomicUpdates={atomicUpdater};var Recoil_AtomicUpdates_1=Recoil_AtomicUpdates.atomicUpdater;var Recoil_AtomicUpdates$1=/*#__PURE__*/Object.freeze({__proto__:null,atomicUpdater:Recoil_AtomicUpdates_1});/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format * @oncall recoil */function invariant(condition,message){if(!condition){throw new Error(message);}}var invariant_1=invariant;// @oss-only var Recoil_invariant=invariant_1;const{atomicUpdater:atomicUpdater$1}=Recoil_AtomicUpdates$1;const{batchUpdates:batchUpdates$4}=Recoil_Batching;const{DEFAULT_VALUE:DEFAULT_VALUE$5}=Recoil_Node;const{useStoreRef:useStoreRef$6}=Recoil_RecoilRoot;const{refreshRecoilValue:refreshRecoilValue$1,setRecoilValue:setRecoilValue$3}=Recoil_RecoilValueInterface;const{cloneSnapshot:cloneSnapshot$2}=Recoil_Snapshot$1;const{gotoSnapshot:gotoSnapshot$1}=Recoil_SnapshotHooks;const{useCallback:useCallback$3}=React;class Sentinel{}const SENTINEL=new Sentinel();function recoilCallback(store,fn,args,extraInterface){let ret=SENTINEL;let releaseSnapshot;batchUpdates$4(()=>{const errMsg='useRecoilCallback() expects a function that returns a function: '+'it accepts a function of the type (RecoilInterface) => (Args) => ReturnType '+'and returns a callback function (Args) => ReturnType, where RecoilInterface is '+'an object {snapshot, set, ...} and Args and ReturnType are the argument and return '+'types of the callback you want to create. Please see the docs '+'at recoiljs.org for details.';if(typeof fn!=='function'){throw Recoil_err(errMsg);}// Clone the snapshot lazily to avoid overhead if the callback does not use it. // Note that this means the snapshot may represent later state from when // the callback was called if it first accesses the snapshot asynchronously. const callbackInterface=Recoil_lazyProxy({...(extraInterface!==null&&extraInterface!==void 0?extraInterface:{}),// flowlint-line unclear-type:off // $FlowFixMe[missing-local-annot] set:(node,newValue)=>setRecoilValue$3(store,node,newValue),// $FlowFixMe[missing-local-annot] reset:node=>setRecoilValue$3(store,node,DEFAULT_VALUE$5),// $FlowFixMe[missing-local-annot] refresh:node=>refreshRecoilValue$1(store,node),gotoSnapshot:snapshot=>gotoSnapshot$1(store,snapshot),transact_UNSTABLE:transaction=>atomicUpdater$1(store)(transaction)},{snapshot:()=>{const snapshot=cloneSnapshot$2(store);releaseSnapshot=snapshot.retain();return snapshot;}});const callback=fn(callbackInterface);if(typeof callback!=='function'){throw Recoil_err(errMsg);}ret=callback(...args);});!!(ret instanceof Sentinel)?Recoil_invariant(false):void 0;if(Recoil_isPromise(ret)){ret=ret.finally(()=>{var _releaseSnapshot;(_releaseSnapshot=releaseSnapshot)===null||_releaseSnapshot===void 0?void 0:_releaseSnapshot();});}else {var _releaseSnapshot2;(_releaseSnapshot2=releaseSnapshot)===null||_releaseSnapshot2===void 0?void 0:_releaseSnapshot2();}return ret;}function useRecoilCallback(fn,deps){const storeRef=useStoreRef$6();return useCallback$3(// $FlowIssue[incompatible-call] (...args)=>{return recoilCallback(storeRef.current,fn,args);},deps!=null?[...deps,storeRef]:undefined// eslint-disable-line fb-www/react-hooks-deps );}var Recoil_useRecoilCallback={recoilCallback,useRecoilCallback};const{useStoreRef:useStoreRef$7}=Recoil_RecoilRoot;const{refreshRecoilValue:refreshRecoilValue$2}=Recoil_RecoilValueInterface;const{useCallback:useCallback$4}=React;function useRecoilRefresher(recoilValue){const storeRef=useStoreRef$7();return useCallback$4(()=>{const store=storeRef.current;refreshRecoilValue$2(store,recoilValue);},[recoilValue,storeRef]);}var Recoil_useRecoilRefresher=useRecoilRefresher;const{atomicUpdater:atomicUpdater$2}=Recoil_AtomicUpdates$1;const{useStoreRef:useStoreRef$8}=Recoil_RecoilRoot;const{useMemo:useMemo$3}=React;function useRecoilTransaction(fn,deps){const storeRef=useStoreRef$8();return useMemo$3(()=>(...args)=>{const atomicUpdate=atomicUpdater$2(storeRef.current);atomicUpdate(transactionInterface=>{fn(transactionInterface)(...args);});},deps!=null?[...deps,storeRef]:undefined// eslint-disable-line fb-www/react-hooks-deps );}var Recoil_useRecoilTransaction=useRecoilTransaction;/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format * @oncall recoil */class WrappedValue{constructor(value){_defineProperty(this,"value",void 0);this.value=value;}}var Recoil_Wrapper={WrappedValue};var Recoil_Wrapper_1=Recoil_Wrapper.WrappedValue;var Recoil_Wrapper$1=/*#__PURE__*/Object.freeze({__proto__:null,WrappedValue:Recoil_Wrapper_1});const{isFastRefreshEnabled:isFastRefreshEnabled$2}=Recoil_ReactMode;class ChangedPathError extends Error{}class TreeCache{// $FlowIssue[unclear-type] constructor(options){var _options$onHit,_options$onSet,_options$mapNodeValue;_defineProperty(this,"_name",void 0);_defineProperty(this,"_numLeafs",void 0);_defineProperty(this,"_root",void 0);_defineProperty(this,"_onHit",void 0);_defineProperty(this,"_onSet",void 0);_defineProperty(this,"_mapNodeValue",void 0);this._name=options===null||options===void 0?void 0:options.name;this._numLeafs=0;this._root=null;this._onHit=(_options$onHit=options===null||options===void 0?void 0:options.onHit)!==null&&_options$onHit!==void 0?_options$onHit:()=>{};this._onSet=(_options$onSet=options===null||options===void 0?void 0:options.onSet)!==null&&_options$onSet!==void 0?_options$onSet:()=>{};this._mapNodeValue=(_options$mapNodeValue=options===null||options===void 0?void 0:options.mapNodeValue)!==null&&_options$mapNodeValue!==void 0?_options$mapNodeValue:val=>val;}size(){return this._numLeafs;}// $FlowIssue[unclear-type] root(){return this._root;}get(getNodeValue,handlers){var _this$getLeafNode;return (_this$getLeafNode=this.getLeafNode(getNodeValue,handlers))===null||_this$getLeafNode===void 0?void 0:_this$getLeafNode.value;}getLeafNode(getNodeValue,handlers){if(this._root==null){return undefined;}// Iterate down the tree based on the current node values until we hit a leaf // $FlowIssue[unclear-type] let node=this._root;while(node){handlers===null||handlers===void 0?void 0:handlers.onNodeVisit(node);if(node.type==='leaf'){this._onHit(node);return node;}const nodeValue=this._mapNodeValue(getNodeValue(node.nodeKey));node=node.branches.get(nodeValue);}return undefined;}set(route,value,handlers){const addLeaf=()=>{var _node2,_node3,_this$_root2,_handlers$onNodeVisit2;// First, setup the branch nodes for the route: // Iterate down the tree to find or add branch nodes following the route let node;let branchKey;for(const[nodeKey,nodeValue]of route){var _node,_handlers$onNodeVisit,_this$_root;// If the previous root was a leaf, while we not have a get(), it means // the selector has inconsistent values or implementation changed. const root=this._root;if((root===null||root===void 0?void 0:root.type)==='leaf'){throw this.invalidCacheError();}// node now refers to the next node down in the tree const parent=node;// $FlowFixMe[prop-missing] // $FlowFixMe[incompatible-type] node=parent?parent.branches.get(branchKey):root;// $FlowFixMe[prop-missing] // $FlowFixMe[incompatible-type] node=(_node=node)!==null&&_node!==void 0?_node:{type:'branch',nodeKey,parent,branches:new Map(),branchKey};// If we found an existing node, confirm it has a consistent value if(node.type!=='branch'||node.nodeKey!==nodeKey){throw this.invalidCacheError();}// Add the branch node to the tree parent===null||parent===void 0?void 0:parent.branches.set(branchKey,node);handlers===null||handlers===void 0?void 0:(_handlers$onNodeVisit=handlers.onNodeVisit)===null||_handlers$onNodeVisit===void 0?void 0:_handlers$onNodeVisit.call(handlers,node);// Prepare for next iteration and install root if it is new. branchKey=this._mapNodeValue(nodeValue);this._root=(_this$_root=this._root)!==null&&_this$_root!==void 0?_this$_root:node;}// Second, setup the leaf node: // If there is an existing leaf for this route confirm it is consistent const oldLeaf=node?(_node2=node)===null||_node2===void 0?void 0:_node2.branches.get(branchKey):this._root;if(oldLeaf!=null&&(oldLeaf.type!=='leaf'||oldLeaf.branchKey!==branchKey)){throw this.invalidCacheError();}// Create a new or replacement leaf. const leafNode={type:'leaf',value,parent:node,branchKey};// Install the leaf and call handlers (_node3=node)===null||_node3===void 0?void 0:_node3.branches.set(branchKey,leafNode);this._root=(_this$_root2=this._root)!==null&&_this$_root2!==void 0?_this$_root2:leafNode;this._numLeafs++;this._onSet(leafNode);handlers===null||handlers===void 0?void 0:(_handlers$onNodeVisit2=handlers.onNodeVisit)===null||_handlers$onNodeVisit2===void 0?void 0:_handlers$onNodeVisit2.call(handlers,leafNode);};try{addLeaf();}catch(error){// If the cache was stale or observed inconsistent values, such as with // Fast Refresh, then clear it and rebuild with the new values. if(error instanceof ChangedPathError){this.clear();addLeaf();}else {throw error;}}}// Returns true if leaf was actually deleted from the tree delete(leaf){const root=this.root();if(!root){return false;}if(leaf===root){this._root=null;this._numLeafs=0;return true;}// Iterate up from the leaf deleteing it from it's parent's branches. let node=leaf.parent;let branchKey=leaf.branchKey;while(node){var _node4;node.branches.delete(branchKey);// Stop iterating if we hit the root. if(node===root){if(node.branches.size===0){this._root=null;this._numLeafs=0;}else {this._numLeafs--;}return true;}// Stop iterating if there are other branches since we don't need to // remove any more nodes. if(node.branches.size>0){break;}// Iterate up to our parent branchKey=(_node4=node)===null||_node4===void 0?void 0:_node4.branchKey;node=node.parent;}// Confirm that the leaf we are deleting is actually attached to our tree for(;node!==root;node=node.parent){if(node==null){return false;}}this._numLeafs--;return true;}clear(){this._numLeafs=0;this._root=null;}invalidCacheError(){const CHANGED_PATH_ERROR_MESSAGE=isFastRefreshEnabled$2()?'Possible Fast Refresh module reload detected. '+'This may also be caused by an selector returning inconsistent values. '+'Resetting cache.':'Invalid cache values. This happens when selectors do not return '+'consistent values for the same input dependency values. That may also '+'be caused when using Fast Refresh to change a selector implementation. '+'Resetting cache.';Recoil_recoverableViolation(CHANGED_PATH_ERROR_MESSAGE+(this._name!=null?` - ${this._name}`:''));throw new ChangedPathError();}}var Recoil_TreeCache={TreeCache};var Recoil_TreeCache_1=Recoil_TreeCache.TreeCache;var Recoil_TreeCache$1=/*#__PURE__*/Object.freeze({__proto__:null,TreeCache:Recoil_TreeCache_1});class LRUCache{constructor(options){var _options$mapKey;_defineProperty(this,"_maxSize",void 0);_defineProperty(this,"_size",void 0);_defineProperty(this,"_head",void 0);_defineProperty(this,"_tail",void 0);_defineProperty(this,"_map",void 0);_defineProperty(this,"_keyMapper",void 0);this._maxSize=options.maxSize;this._size=0;this._head=null;this._tail=null;this._map=new Map();this._keyMapper=(_options$mapKey=options.mapKey)!==null&&_options$mapKey!==void 0?_options$mapKey:v=>v;}head(){return this._head;}tail(){return this._tail;}size(){return this._size;}maxSize(){return this._maxSize;}has(key){return this._map.has(this._keyMapper(key));}get(key){const mappedKey=this._keyMapper(key);const node=this._map.get(mappedKey);if(!node){return undefined;}this.set(key,node.value);return node.value;}set(key,val){const mappedKey=this._keyMapper(key);const existingNode=this._map.get(mappedKey);if(existingNode){this.delete(key);}const head=this.head();const node={key,right:head,left:null,value:val};if(head){head.left=node;}else {this._tail=node;}this._map.set(mappedKey,node);this._head=node;this._size++;this._maybeDeleteLRU();}_maybeDeleteLRU(){if(this.size()>this.maxSize()){this.deleteLru();}}deleteLru(){const tail=this.tail();if(tail){this.delete(tail.key);}}delete(key){const mappedKey=this._keyMapper(key);if(!this._size||!this._map.has(mappedKey)){return;}const node=Recoil_nullthrows(this._map.get(mappedKey));const right=node.right;const left=node.left;if(right){right.left=node.left;}if(left){left.right=node.right;}if(node===this.head()){this._head=right;}if(node===this.tail()){this._tail=left;}this._map.delete(mappedKey);this._size--;}clear(){this._size=0;this._head=null;this._tail=null;this._map=new Map();}}var Recoil_LRUCache={LRUCache};var Recoil_LRUCache_1=Recoil_LRUCache.LRUCache;var Recoil_LRUCache$1=/*#__PURE__*/Object.freeze({__proto__:null,LRUCache:Recoil_LRUCache_1});const{LRUCache:LRUCache$1}=Recoil_LRUCache$1;const{TreeCache:TreeCache$1}=Recoil_TreeCache$1;function treeCacheLRU({name,maxSize,mapNodeValue=v=>v}){const lruCache=new LRUCache$1({maxSize});const cache=new TreeCache$1({name,mapNodeValue,onHit:node=>{lruCache.set(node,true);},onSet:node=>{const lruNode=lruCache.tail();lruCache.set(node,true);if(lruNode&&cache.size()>maxSize){// $FlowFixMe[incompatible-call] cache.delete(lruNode.key);}}});return cache;}var Recoil_treeCacheLRU=treeCacheLRU;function stringify(x,opt,key){// A optimization to avoid the more expensive JSON.stringify() for simple strings // This may lose protection for u2028 and u2029, though. if(typeof x==='string'&&!x.includes('"')&&!x.includes('\\')){return `"${x}"`;}// Handle primitive types switch(typeof x){case'undefined':return '';// JSON.stringify(undefined) returns undefined, but we always want to return a string case'boolean':return x?'true':'false';case'number':case'symbol':// case 'bigint': // BigInt is not supported in www return String(x);case'string':// Add surrounding quotes and escape internal quotes return JSON.stringify(x);case'function':if((opt===null||opt===void 0?void 0:opt.allowFunctions)!==true){throw Recoil_err('Attempt to serialize function in a Recoil cache key');}return `__FUNCTION(${x.name})__`;}if(x===null){return 'null';}// Fallback case for unknown types if(typeof x!=='object'){var _JSON$stringify;return (_JSON$stringify=JSON.stringify(x))!==null&&_JSON$stringify!==void 0?_JSON$stringify:'';}// Deal with all promises as equivalent for now. if(Recoil_isPromise(x)){return '__PROMISE__';}// Arrays handle recursive stringification if(Array.isArray(x)){// $FlowFixMe[missing-local-annot] return `[${x.map((v,i)=>stringify(v,opt,i.toString()))}]`;}// If an object defines a toJSON() method, then use that to override the // serialization. This matches the behavior of JSON.stringify(). // Pass the key for compatibility. // Immutable.js collections define this method to allow us to serialize them. if(typeof x.toJSON==='function'){// flowlint-next-line unclear-type: off return stringify(x.toJSON(key),opt,key);}// For built-in Maps, sort the keys in a stable order instead of the // default insertion order. Support non-string keys. if(x instanceof Map){const obj={};for(const[k,v]of x){// Stringify will escape any nested quotes obj[typeof k==='string'?k:stringify(k,opt)]=v;}return stringify(obj,opt,key);}// For built-in Sets, sort the keys in a stable order instead of the // default insertion order. if(x instanceof Set){return stringify(// $FlowFixMe[missing-local-annot] Array.from(x).sort((a,b)=>stringify(a,opt).localeCompare(stringify(b,opt))),opt,key);}// Anything else that is iterable serialize as an Array. if(Symbol!==undefined&&x[Symbol.iterator]!=null&&typeof x[Symbol.iterator]==='function'){// flowlint-next-line unclear-type: off return stringify(Array.from(x),opt,key);}// For all other Objects, sort the keys in a stable order. return `{${Object.keys(x).filter(k=>x[k]!==undefined).sort()// stringify the key to add quotes and escape any nested slashes or quotes. .map(k=>`${stringify(k,opt)}:${stringify(x[k],opt,k)}`).join(',')}}`;}// Utility similar to JSON.stringify() except: // * Serialize built-in Sets as an Array // * Serialize built-in Maps as an Object. Supports non-string keys. // * Serialize other iterables as arrays // * Sort the keys of Objects and Maps to have a stable order based on string conversion. // This overrides their default insertion order. // * Still uses toJSON() of any object to override serialization // * Support Symbols (though don't guarantee uniqueness) // * We could support BigInt, but Flow doesn't seem to like it. // See Recoil_stableStringify-test.js for examples function stableStringify(x,opt={allowFunctions:false}){return stringify(x,opt);}var Recoil_stableStringify=stableStringify;const{TreeCache:TreeCache$2}=Recoil_TreeCache$1;const defaultPolicy={equality:'reference',eviction:'keep-all',maxSize:Infinity};function treeCacheFromPolicy({equality=defaultPolicy.equality,eviction=defaultPolicy.eviction,maxSize=defaultPolicy.maxSize}=defaultPolicy,name){const valueMapper=getValueMapper(equality);return getTreeCache(eviction,maxSize,valueMapper,name);}function getValueMapper(equality){switch(equality){case'reference':return val=>val;case'value':return val=>Recoil_stableStringify(val);}throw Recoil_err(`Unrecognized equality policy ${equality}`);}function getTreeCache(eviction,maxSize,mapNodeValue,name){switch(eviction){case'keep-all':return new TreeCache$2({name,mapNodeValue});case'lru':return Recoil_treeCacheLRU({name,maxSize:Recoil_nullthrows(maxSize),mapNodeValue});case'most-recent':return Recoil_treeCacheLRU({name,maxSize:1,mapNodeValue});}throw Recoil_err(`Unrecognized eviction policy ${eviction}`);}var Recoil_treeCacheFromPolicy=treeCacheFromPolicy;/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * This is a stub for some integration into FB internal stuff * * * @format * @oncall recoil */function startPerfBlock(_id){return ()=>null;}var Recoil_PerformanceTimings={startPerfBlock};const{isLoadable:isLoadable$1,loadableWithError:loadableWithError$1,loadableWithPromise:loadableWithPromise$1,loadableWithValue:loadableWithValue$2}=Recoil_Loadable$1;const{WrappedValue:WrappedValue$1}=Recoil_Wrapper$1;const{getNodeLoadable:getNodeLoadable$2,peekNodeLoadable:peekNodeLoadable$1,setNodeValue:setNodeValue$3}=Recoil_FunctionalCore;const{saveDepsToStore:saveDepsToStore$1}=Recoil_Graph;const{DEFAULT_VALUE:DEFAULT_VALUE$6,getConfigDeletionHandler:getConfigDeletionHandler$1,getNode:getNode$6,registerNode:registerNode$1}=Recoil_Node;const{isRecoilValue:isRecoilValue$3}=Recoil_RecoilValue$1;const{markRecoilValueModified:markRecoilValueModified$1}=Recoil_RecoilValueInterface;const{retainedByOptionWithDefault:retainedByOptionWithDefault$1}=Recoil_Retention;const{recoilCallback:recoilCallback$1}=Recoil_useRecoilCallback;const{startPerfBlock:startPerfBlock$1}=Recoil_PerformanceTimings;class Canceled{}const CANCELED=new Canceled();/** * An ExecutionID is an arbitrary ID that lets us distinguish executions from * each other. This is necessary as we need a way of solving this problem: * "given 3 async executions, only update state for the 'latest' execution when * it finishes running regardless of when the other 2 finish". ExecutionIDs * provide a convenient way of identifying executions so that we can track and * manage them over time. */const dependencyStack=[];// for detecting circular dependencies. const waitingStores=new Map();const getNewExecutionID=(()=>{let executionID=0;return ()=>executionID++;})();/* eslint-disable no-redeclare */function selector(options){let recoilValue=null;const{key,get,cachePolicy_UNSTABLE:cachePolicy}=options;const set=options.set!=null?options.set:undefined;// flow const discoveredDependencyNodeKeys=new Set();const cache=Recoil_treeCacheFromPolicy(cachePolicy!==null&&cachePolicy!==void 0?cachePolicy:{equality:'reference',eviction:'keep-all'},key);const retainedBy=retainedByOptionWithDefault$1(options.retainedBy_UNSTABLE);const executionInfoMap=new Map();let liveStoresCount=0;function selectorIsLive(){return !Recoil_gkx('recoil_memory_managament_2020')||liveStoresCount>0;}function selectorInit(store){store.getState().knownSelectors.add(key);liveStoresCount++;return ()=>{liveStoresCount--;};}function selectorShouldDeleteConfigOnRelease(){return getConfigDeletionHandler$1(key)!==undefined&&!selectorIsLive();}function resolveAsync(store,state,executionID,loadable,depValues){setCache(state,loadable,depValues);notifyStoresOfResolvedAsync(store,executionID);}function notifyStoresOfResolvedAsync(store,executionID){if(isLatestExecution(store,executionID)){clearExecutionInfo(store);}notifyWaitingStores(executionID,true);}/** * Notify stores to pull the selector again if a new async dep was discovered. * 1) Async selector adds a new dep but doesn't resolve yet. * Note that deps for an async selector are based on the state when the * evaluation started, in order to provide a consistent picture of state. * 2) But, new value of dep based on the current state might cause the selector * to resolve or resolve differently. * 3) Therefore, this notification will pull the selector based on the current * state for the components */function notifyStoresOfNewAsyncDep(store,executionID){if(isLatestExecution(store,executionID)){const executionInfo=Recoil_nullthrows(getExecutionInfo(store));executionInfo.stateVersions.clear();notifyWaitingStores(executionID,false);}}function notifyWaitingStores(executionID,clearWaitlist){const stores=waitingStores.get(executionID);if(stores!=null){for(const waitingStore of stores){markRecoilValueModified$1(waitingStore,Recoil_nullthrows(recoilValue));}if(clearWaitlist){waitingStores.delete(executionID);}}}function markStoreWaitingForResolvedAsync(store,executionID){let stores=waitingStores.get(executionID);if(stores==null){waitingStores.set(executionID,stores=new Set());}stores.add(store);}/** * This function attaches a then() and a catch() to a promise that was * returned from a selector's get() (either explicitly or implicitly by * running a function that uses the "async" keyword). If a selector's get() * returns a promise, we have two possibilities: * * 1. The promise will resolve, in which case it will have completely finished * executing without any remaining pending dependencies. No more retries * are needed and we can proceed with updating the cache and notifying * subscribers (if it is the latest execution, otherwise only the cache * will be updated and subscriptions will not be fired). This is the case * handled by the attached then() handler. * * 2. The promise will throw because it either has an error or it came across * an async dependency that has not yet resolved, in which case we will * call wrapDepdencyPromise(), whose responsibility is to handle dependency * promises. This case is handled by the attached catch() handler. * * Both branches will eventually resolve to the final result of the selector * (or an error if a real error occurred). * * The execution will run to completion even if it is stale, and its value * will be cached. But stale executions will not update global state or update * executionInfo as that is the responsibility of the 'latest' execution. * * Note this function should not be passed a promise that was thrown--AKA a * dependency promise. Dependency promises should be passed to * wrapPendingDependencyPromise()). */function wrapResultPromise(store,promise,state,depValues,executionID,loadingDepsState){return promise.then(value=>{if(!selectorIsLive()){// The selector was released since the request began; ignore the response. clearExecutionInfo(store);throw CANCELED;}const loadable=loadableWithValue$2(value);resolveAsync(store,state,executionID,loadable,depValues);return value;}).catch(errorOrPromise=>{if(!selectorIsLive()){// The selector was released since the request began; ignore the response. clearExecutionInfo(store);throw CANCELED;}if(Recoil_isPromise(errorOrPromise)){return wrapPendingDependencyPromise(store,errorOrPromise,state,depValues,executionID,loadingDepsState);}const loadable=loadableWithError$1(errorOrPromise);resolveAsync(store,state,executionID,loadable,depValues);throw errorOrPromise;});}/** * This function attaches a then() and a catch() to a promise that was * thrown from a selector's get(). If a selector's get() throws a promise, * we have two possibilities: * * 1. The promise will resolve, meaning one of our selector's dependencies is * now available and we should "retry" our get() by running it again. This * is the case handled by the attached then() handler. * * 2. The promise will throw because something went wrong with the dependency * promise (in other words a real error occurred). This case is handled by * the attached catch() handler. If the dependency promise throws, it is * _always_ a real error and not another dependency promise (any dependency * promises would have been handled upstream). * * The then() branch will eventually resolve to the final result of the * selector (or an error if a real error occurs), and the catch() will always * resolve to an error because the dependency promise is a promise that was * wrapped upstream, meaning it will only resolve to its real value or to a * real error. * * The execution will run to completion even if it is stale, and its value * will be cached. But stale executions will not update global state or update * executionInfo as that is the responsibility of the 'latest' execution. * * Note this function should not be passed a promise that was returned from * get(). The intention is that this function is only passed promises that * were thrown due to a pending dependency. Promises returned by get() should * be passed to wrapResultPromise() instead. */function wrapPendingDependencyPromise(store,promise,state,existingDeps,executionID,loadingDepsState){return promise.then(resolvedDep=>{if(!selectorIsLive()){// The selector was released since the request began; ignore the response. clearExecutionInfo(store);throw CANCELED;}// Check if we are handling a pending Recoil dependency or if the user // threw their own Promise to "suspend" a selector evaluation. We need // to check that the loadingDepPromise actually matches the promise that // we caught in case the selector happened to catch the promise we threw // for a pending Recoil dependency from `getRecoilValue()` and threw // their own promise instead. if(loadingDepsState.loadingDepKey!=null&&loadingDepsState.loadingDepPromise===promise){/** * Note for async atoms, this means we are changing the atom's value * in the store for the given version. This should be alright because * the version of state is now stale and a new version will have * already been triggered by the atom being resolved (see this logic * in Recoil_atom.js) */state.atomValues.set(loadingDepsState.loadingDepKey,loadableWithValue$2(resolvedDep));}else {/** * If resolvedDepKey is not defined, the promise was a user-thrown * promise. User-thrown promises are an advanced feature and they * should be avoided in almost all cases. Using `loadable.map()` inside * of selectors for loading loadables and then throwing that mapped * loadable's promise is an example of a user-thrown promise. * * When we hit a user-thrown promise, we have to bail out of an optimization * where we bypass calculating selector cache keys for selectors that * have been previously seen for a given state (these selectors are saved in * state.atomValues) to avoid stale state as we have no way of knowing * what state changes happened (if any) in result to the promise resolving. * * Ideally we would only bail out selectors that are in the chain of * dependencies for this selector, but there's currently no way to get * a full list of a selector's downstream nodes because the state that * is executing may be a discarded tree (so store.getGraph(state.version) * will be empty), and the full dep tree may not be in the selector * caches in the case where the selector's cache was cleared. To solve * for this we would have to keep track of all running selector * executions and their downstream deps. Because this only covers edge * cases, that complexity might not be justifyable. */store.getState().knownSelectors.forEach(nodeKey=>{state.atomValues.delete(nodeKey);});}/** * Optimization: Now that the dependency has resolved, let's try hitting * the cache in case the dep resolved to a value we have previously seen. * * TODO: * Note this optimization is not perfect because it only prevents re-executions * _after_ the point where an async dependency is found. Any code leading * up to the async dependency may have run unnecessarily. The ideal case * would be to wait for the async dependency to resolve first, check the * cache, and prevent _any_ execution of the selector if the resulting * value of the dependency leads to a path that is found in the cache. * The ideal case is more difficult to implement as it would require that * we capture and wait for the the async dependency right after checking * the cache. The current approach takes advantage of the fact that running * the selector already has a code path that lets us exit early when * an async dep resolves. */const cachedLoadable=getLoadableFromCacheAndUpdateDeps(store,state);if(cachedLoadable&&cachedLoadable.state!=='loading'){/** * This has to notify stores of a resolved async, even if there is no * current pending execution for the following case: * 1) A component renders with this pending loadable. * 2) The upstream dependency resolves. * 3) While processing some other selector it reads this one, such as * while traversing its dependencies. At this point it gets the * new resolved value synchronously and clears the current * execution ID. The component wasn't getting the value itself, * though, so it still has the pending loadable. * 4) When this code executes the current execution id was cleared * and it wouldn't notify the component of the new value. * * I think this is only an issue with "early" rendering since the * components got their value using the in-progress execution. * We don't have a unit test for this case yet. I'm not sure it is * necessary with recoil_transition_support mode. */if(isLatestExecution(store,executionID)||getExecutionInfo(store)==null){notifyStoresOfResolvedAsync(store,executionID);}if(cachedLoadable.state==='hasValue'){return cachedLoadable.contents;}else {throw cachedLoadable.contents;}}/** * If this execution is stale, let's check to see if there is some in * progress execution with a matching state. If we find a match, then * we can take the value from that in-progress execution. Note this may * sound like an edge case, but may be very common in cases where a * loading dependency resolves from loading to having a value (thus * possibly triggering a re-render), and React re-renders before the * chained .then() functions run, thus starting a new execution as the * dep has changed value. Without this check we will run the selector * twice (once in the new execution and once again in this .then(), so * this check is necessary to keep unnecessary re-executions to a * minimum). * * Also note this code does not check across all executions that may be * running. It only optimizes for the _latest_ execution per store as * we currently do not maintain a list of all currently running executions. * This means in some cases we may run selectors more than strictly * necessary when there are multiple executions running for the same * selector. This may be a valid tradeoff as checking for dep changes * across all in-progress executions may take longer than just * re-running the selector. This will be app-dependent, and maybe in the * future we can make the behavior configurable. An ideal fix may be * to extend the tree cache to support caching loading states. */if(!isLatestExecution(store,executionID)){const executionInfo=getInProgressExecutionInfo(store,state);if(executionInfo!=null){/** * Returning promise here without wrapping as the wrapper logic was * already done upstream when this promise was generated. */return executionInfo.loadingLoadable.contents;}}// Retry the selector evaluation now that the dependency has resolved const[loadable,depValues]=evaluateSelectorGetter(store,state,executionID);if(loadable.state!=='loading'){resolveAsync(store,state,executionID,loadable,depValues);}if(loadable.state==='hasError'){throw loadable.contents;}return loadable.contents;}).catch(error=>{// The selector was released since the request began; ignore the response. if(error instanceof Canceled){throw CANCELED;}if(!selectorIsLive()){clearExecutionInfo(store);throw CANCELED;}const loadable=loadableWithError$1(error);resolveAsync(store,state,executionID,loadable,existingDeps);throw error;});}function updateDeps(store,state,deps,executionID){var _store$getState,_store$getState$curre,_store$getState2,_store$getState2$next;if(isLatestExecution(store,executionID)||state.version===((_store$getState=store.getState())===null||_store$getState===void 0?void 0:(_store$getState$curre=_store$getState.currentTree)===null||_store$getState$curre===void 0?void 0:_store$getState$curre.version)||state.version===((_store$getState2=store.getState())===null||_store$getState2===void 0?void 0:(_store$getState2$next=_store$getState2.nextTree)===null||_store$getState2$next===void 0?void 0:_store$getState2$next.version)){var _store$getState$nextT,_store$getState3,_store$getState3$next;saveDepsToStore$1(key,deps,store,(_store$getState$nextT=(_store$getState3=store.getState())===null||_store$getState3===void 0?void 0:(_store$getState3$next=_store$getState3.nextTree)===null||_store$getState3$next===void 0?void 0:_store$getState3$next.version)!==null&&_store$getState$nextT!==void 0?_store$getState$nextT:store.getState().currentTree.version);}for(const nodeKey of deps){discoveredDependencyNodeKeys.add(nodeKey);}}function evaluateSelectorGetter(store,state,executionID){const endPerfBlock=startPerfBlock$1(key);// TODO T63965866: use execution ID here let duringSynchronousExecution=true;let duringAsynchronousExecution=true;const finishEvaluation=()=>{endPerfBlock();duringAsynchronousExecution=false;};let result;let resultIsError=false;let loadable;const loadingDepsState={loadingDepKey:null,loadingDepPromise:null};/** * Starting a fresh set of deps that we'll be using to update state. We're * starting a new set versus adding it in existing state deps because * the version of state that we update deps for may be a more recent version * than the version the selector was called with. This is because the latest * execution will update the deps of the current/latest version of state * (This is safe to do because the fact that the selector is the latest * execution means the deps we discover below are our best guess at the * deps for the current/latest state in the store) */const depValues=new Map();function getRecoilValue({key:depKey}){const depLoadable=getNodeLoadable$2(store,state,depKey);depValues.set(depKey,depLoadable);// We need to update asynchronous dependencies as we go so the selector // knows if it has to restart evaluation if one of them is updated before // the asynchronous selector completely resolves. if(!duringSynchronousExecution){updateDeps(store,state,new Set(depValues.keys()),executionID);notifyStoresOfNewAsyncDep(store,executionID);}switch(depLoadable.state){case'hasValue':return depLoadable.contents;case'hasError':throw depLoadable.contents;case'loading':loadingDepsState.loadingDepKey=depKey;loadingDepsState.loadingDepPromise=depLoadable.contents;throw depLoadable.contents;}throw Recoil_err('Invalid Loadable state');}const getCallback=fn=>{return (...args)=>{if(duringAsynchronousExecution){throw Recoil_err('Callbacks from getCallback() should only be called asynchronously after the selector is evalutated. It can be used for selectors to return objects with callbacks that can work with Recoil state without a subscription.');}!(recoilValue!=null)?Recoil_invariant(false):void 0;return recoilCallback$1(store,fn,args,{node:recoilValue}// flowlint-line unclear-type:off );};};try{result=get({get:getRecoilValue,getCallback});result=isRecoilValue$3(result)?getRecoilValue(result):result;if(isLoadable$1(result)){if(result.state==='hasError'){resultIsError=true;}result=result.contents;}if(Recoil_isPromise(result)){result=wrapResultPromise(store,result,state,depValues,executionID,loadingDepsState).finally(finishEvaluation);}else {finishEvaluation();}result=result instanceof WrappedValue$1?result.value:result;}catch(errorOrDepPromise){result=errorOrDepPromise;if(Recoil_isPromise(result)){result=wrapPendingDependencyPromise(store,result,state,depValues,executionID,loadingDepsState).finally(finishEvaluation);}else {resultIsError=true;finishEvaluation();}}if(resultIsError){loadable=loadableWithError$1(result);}else if(Recoil_isPromise(result)){loadable=loadableWithPromise$1(result);}else {loadable=loadableWithValue$2(result);}duringSynchronousExecution=false;updateExecutionInfoDepValues(store,executionID,depValues);updateDeps(store,state,new Set(depValues.keys()),executionID);return [loadable,depValues];}function getLoadableFromCacheAndUpdateDeps(store,state){// First, look up in the state cache // If it's here, then the deps in the store should already be valid. let cachedLoadable=state.atomValues.get(key);if(cachedLoadable!=null){return cachedLoadable;}// Second, look up in the selector cache and update the deps in the store const depsAfterCacheLookup=new Set();try{cachedLoadable=cache.get(nodeKey=>{!(typeof nodeKey==='string')?"production"!=="production"?Recoil_invariant(false,'Cache nodeKey is type string'):Recoil_invariant(false):void 0;return getNodeLoadable$2(store,state,nodeKey).contents;},{onNodeVisit:node=>{if(node.type==='branch'&&node.nodeKey!==key){depsAfterCacheLookup.add(node.nodeKey);}}});}catch(error){throw Recoil_err(`Problem with cache lookup for selector "${key}": ${error.message}`);}if(cachedLoadable){var _getExecutionInfo;// Cache the results in the state to allow for cheaper lookup than // iterating the tree cache of dependencies. state.atomValues.set(key,cachedLoadable);/** * Ensure store contains correct dependencies if we hit the cache so that * the store deps and cache are in sync for a given state. This is important * because store deps are normally updated when new executions are created, * but cache hits don't trigger new executions but they still _may_ signify * a change in deps in the store if the store deps for this state are empty * or stale. */updateDeps(store,state,depsAfterCacheLookup,(_getExecutionInfo=getExecutionInfo(store))===null||_getExecutionInfo===void 0?void 0:_getExecutionInfo.executionID);}return cachedLoadable;}/** * Given a tree state, this function returns a Loadable of the current state. * * The selector's get() function will only be re-evaluated if _both_ of the * following statements are true: * * 1. The current dep values from the given state produced a cache key that * was not found in the cache. * 2. There is no currently running async execution OR there is an * async execution that is running, but after comparing the dep values in * the given state with the dep values that the execution has discovered so * far we find that at least one dep value has changed, in which case we * start a new execution (the previously running execution will continue to * run to completion, but only the new execution will be deemed the * 'latest' execution, meaning it will be the only execution that will * update global state when it is finished. Any non-latest executions will * run to completion and update the selector cache but not global state). */function getSelectorLoadableAndUpdateDeps(store,state){// First, see if our current state is cached const cachedVal=getLoadableFromCacheAndUpdateDeps(store,state);if(cachedVal!=null){clearExecutionInfo(store);return cachedVal;}// Second, check if there is already an ongoing execution based on the current state const inProgressExecutionInfo=getInProgressExecutionInfo(store,state);if(inProgressExecutionInfo!=null){var _inProgressExecutionI;if(((_inProgressExecutionI=inProgressExecutionInfo.loadingLoadable)===null||_inProgressExecutionI===void 0?void 0:_inProgressExecutionI.state)==='loading'){markStoreWaitingForResolvedAsync(store,inProgressExecutionInfo.executionID);}// FIXME: check after the fact to see if we made the right choice by waiting return inProgressExecutionInfo.loadingLoadable;}// Third, start a new evaluation of the selector const newExecutionID=getNewExecutionID();const[loadable,newDepValues]=evaluateSelectorGetter(store,state,newExecutionID);/** * Conditionally updates the cache with a given loadable. * * We only cache loadables that are not loading because our cache keys are * based on dep values, which are in an unfinished state for loadables that * have a 'loading' state (new deps may be discovered while the selector * runs its async code). We never want to cache partial dependencies b/c it * could lead to errors, such as prematurely returning the result based on a * partial list of deps-- we need the full list of deps to ensure that we * are returning the correct result from cache. */if(loadable.state==='loading'){setExecutionInfo(store,newExecutionID,loadable,newDepValues,state);markStoreWaitingForResolvedAsync(store,newExecutionID);}else {clearExecutionInfo(store);setCache(state,loadable,newDepValues);}return loadable;}/** * Searches execution info across all stores to see if there is an in-progress * execution whose dependency values match the values of the requesting store. */function getInProgressExecutionInfo(store,state){// Sort the pending executions so that our current store is checked first. const pendingExecutions=Recoil_concatIterables([executionInfoMap.has(store)?[Recoil_nullthrows(executionInfoMap.get(store))]:[],Recoil_mapIterable(Recoil_filterIterable(executionInfoMap,([s])=>s!==store),([,execInfo])=>execInfo)]);function anyDepChanged(execDepValues){for(const[depKey,execLoadable]of execDepValues){if(!getNodeLoadable$2(store,state,depKey).is(execLoadable)){return true;}}return false;}for(const execInfo of pendingExecutions){if(// If this execution was already checked to be valid with this version // of state, then let's use it! execInfo.stateVersions.get(state.version)||// If the deps for the execution match our current state, then it's valid !anyDepChanged(execInfo.depValuesDiscoveredSoFarDuringAsyncWork)){execInfo.stateVersions.set(state.version,true);return execInfo;}else {execInfo.stateVersions.set(state.version,false);}}return undefined;}function getExecutionInfo(store){return executionInfoMap.get(store);}/** * This function will update the selector's execution info when the selector * has either finished running an execution or has started a new execution. If * the given loadable is in a 'loading' state, the intention is that a new * execution has started. Otherwise, the intention is that an execution has * just finished. */function setExecutionInfo(store,newExecutionID,loadable,depValues,state){executionInfoMap.set(store,{depValuesDiscoveredSoFarDuringAsyncWork:depValues,executionID:newExecutionID,loadingLoadable:loadable,stateVersions:new Map([[state.version,true]])});}function updateExecutionInfoDepValues(store,executionID,depValues){// We only need to bother updating the deps for the latest execution because // that's all getInProgressExecutionInfo() will be looking for. if(isLatestExecution(store,executionID)){const executionInfo=getExecutionInfo(store);if(executionInfo!=null){executionInfo.depValuesDiscoveredSoFarDuringAsyncWork=depValues;}}}function clearExecutionInfo(store){executionInfoMap.delete(store);}function isLatestExecution(store,executionID){var _getExecutionInfo2;return executionID===((_getExecutionInfo2=getExecutionInfo(store))===null||_getExecutionInfo2===void 0?void 0:_getExecutionInfo2.executionID);}/** * FIXME: dep keys should take into account the state of the loadable to * prevent the edge case where a loadable with an error and a loadable with * an error as a value are treated as the same thing incorrectly. For example * these two should be treated differently: * * selector({key: '', get: () => new Error('hi')}); * selector({key: '', get () => {throw new Error('hi')}}); * * With current implementation they are treated the same */function depValuesToDepRoute(depValues){return Array.from(depValues.entries()).map(([depKey,valLoadable])=>[depKey,valLoadable.contents]);}function setCache(state,loadable,depValues){state.atomValues.set(key,loadable);try{cache.set(depValuesToDepRoute(depValues),loadable);}catch(error){throw Recoil_err(`Problem with setting cache for selector "${key}": ${error.message}`);}}function detectCircularDependencies(fn){if(dependencyStack.includes(key)){const message=`Recoil selector has circular dependencies: ${dependencyStack.slice(dependencyStack.indexOf(key)).join(' \u2192 ')}`;return loadableWithError$1(Recoil_err(message));}dependencyStack.push(key);try{return fn();}finally{dependencyStack.pop();}}function selectorPeek(store,state){const cachedLoadable=state.atomValues.get(key);if(cachedLoadable!=null){return cachedLoadable;}return cache.get(nodeKey=>{var _peekNodeLoadable;!(typeof nodeKey==='string')?Recoil_invariant(false):void 0;return (_peekNodeLoadable=peekNodeLoadable$1(store,state,nodeKey))===null||_peekNodeLoadable===void 0?void 0:_peekNodeLoadable.contents;});}function selectorGet(store,state){return detectCircularDependencies(()=>getSelectorLoadableAndUpdateDeps(store,state));}function invalidateSelector(state){state.atomValues.delete(key);}function clearSelectorCache(store,treeState){!(recoilValue!=null)?Recoil_invariant(false):void 0;for(const nodeKey of discoveredDependencyNodeKeys){var _node$clearCache;const node=getNode$6(nodeKey);(_node$clearCache=node.clearCache)===null||_node$clearCache===void 0?void 0:_node$clearCache.call(node,store,treeState);}discoveredDependencyNodeKeys.clear();invalidateSelector(treeState);cache.clear();markRecoilValueModified$1(store,recoilValue);}if(set!=null){/** * ES5 strict mode prohibits defining non-top-level function declarations, * so don't use function declaration syntax here */const selectorSet=(store,state,newValue)=>{let syncSelectorSetFinished=false;const writes=new Map();function getRecoilValue({key:depKey}){if(syncSelectorSetFinished){throw Recoil_err('Recoil: Async selector sets are not currently supported.');}const loadable=getNodeLoadable$2(store,state,depKey);if(loadable.state==='hasValue'){return loadable.contents;}else if(loadable.state==='loading'){const msg=`Getting value of asynchronous atom or selector "${depKey}" in a pending state while setting selector "${key}" is not yet supported.`;throw Recoil_err(msg);}else {throw loadable.contents;}}function setRecoilState(recoilState,valueOrUpdater// $FlowFixMe[missing-local-annot] ){if(syncSelectorSetFinished){const msg='Recoil: Async selector sets are not currently supported.';throw Recoil_err(msg);}const setValue=typeof valueOrUpdater==='function'?// cast to any because we can't restrict type S from being a function itself without losing support for opaque types // flowlint-next-line unclear-type:off valueOrUpdater(getRecoilValue(recoilState)):valueOrUpdater;const upstreamWrites=setNodeValue$3(store,state,recoilState.key,setValue);upstreamWrites.forEach((v,k)=>writes.set(k,v));}function resetRecoilState(recoilState){setRecoilState(recoilState,DEFAULT_VALUE$6);}const ret=set({set:setRecoilState,get:getRecoilValue,reset:resetRecoilState},newValue);// set should be a void method, but if the user makes it `async`, then it // will return a Promise, which we don't currently support. if(ret!==undefined){throw Recoil_isPromise(ret)?Recoil_err('Recoil: Async selector sets are not currently supported.'):Recoil_err('Recoil: selector set should be a void function.');}syncSelectorSetFinished=true;return writes;};return recoilValue=registerNode$1({key,nodeType:'selector',peek:selectorPeek,get:selectorGet,set:selectorSet,init:selectorInit,invalidate:invalidateSelector,clearCache:clearSelectorCache,shouldDeleteConfigOnRelease:selectorShouldDeleteConfigOnRelease,dangerouslyAllowMutability:options.dangerouslyAllowMutability,shouldRestoreFromSnapshots:false,retainedBy});}else {return recoilValue=registerNode$1({key,nodeType:'selector',peek:selectorPeek,get:selectorGet,init:selectorInit,invalidate:invalidateSelector,clearCache:clearSelectorCache,shouldDeleteConfigOnRelease:selectorShouldDeleteConfigOnRelease,dangerouslyAllowMutability:options.dangerouslyAllowMutability,shouldRestoreFromSnapshots:false,retainedBy});}}/* eslint-enable no-redeclare */ // $FlowIssue[incompatible-use] // $FlowFixMe[missing-local-annot] selector.value=value=>new WrappedValue$1(value);var Recoil_selector=selector;// @fb-only: import type {ScopeRules} from 'Recoil_ScopedAtom'; // @fb-only: const {scopedAtom} = require('Recoil_ScopedAtom'); const{isLoadable:isLoadable$2,loadableWithError:loadableWithError$2,loadableWithPromise:loadableWithPromise$2,loadableWithValue:loadableWithValue$3}=Recoil_Loadable$1;const{WrappedValue:WrappedValue$2}=Recoil_Wrapper$1;const{peekNodeInfo:peekNodeInfo$3}=Recoil_FunctionalCore;const{DEFAULT_VALUE:DEFAULT_VALUE$7,DefaultValue:DefaultValue$2,getConfigDeletionHandler:getConfigDeletionHandler$2,registerNode:registerNode$2,setConfigDeletionHandler:setConfigDeletionHandler$1}=Recoil_Node;const{isRecoilValue:isRecoilValue$4}=Recoil_RecoilValue$1;const{getRecoilValueAsLoadable:getRecoilValueAsLoadable$4,markRecoilValueModified:markRecoilValueModified$2,setRecoilValue:setRecoilValue$4,setRecoilValueLoadable:setRecoilValueLoadable$2}=Recoil_RecoilValueInterface;const{retainedByOptionWithDefault:retainedByOptionWithDefault$2}=Recoil_Retention;const unwrap=x=>x instanceof WrappedValue$2?x.value:x;function baseAtom(options){const{key,persistence_UNSTABLE:persistence}=options;const retainedBy=retainedByOptionWithDefault$2(options.retainedBy_UNSTABLE);let liveStoresCount=0;function unwrapPromise(promise){return loadableWithPromise$2(promise.then(value=>{defaultLoadable=loadableWithValue$3(value);return value;}).catch(error=>{defaultLoadable=loadableWithError$2(error);throw error;}));}let defaultLoadable=Recoil_isPromise(options.default)?unwrapPromise(options.default):isLoadable$2(options.default)?options.default.state==='loading'?unwrapPromise(options.default.contents):options.default:// $FlowFixMe[incompatible-call] loadableWithValue$3(unwrap(options.default));maybeFreezeValueOrPromise(defaultLoadable.contents);let cachedAnswerForUnvalidatedValue=undefined;// Cleanup handlers for this atom // Rely on stable reference equality of the store to use it as a key per const cleanupEffectsByStore=new Map();function maybeFreezeValueOrPromise(valueOrPromise){return valueOrPromise;}function wrapPendingPromise(store,promise){const wrappedPromise=promise.then(value=>{var _store$getState$nextT,_state$atomValues$get;const state=(_store$getState$nextT=store.getState().nextTree)!==null&&_store$getState$nextT!==void 0?_store$getState$nextT:store.getState().currentTree;if(((_state$atomValues$get=state.atomValues.get(key))===null||_state$atomValues$get===void 0?void 0:_state$atomValues$get.contents)===wrappedPromise){setRecoilValue$4(store,node,value);}return value;}).catch(error=>{var _store$getState$nextT2,_state$atomValues$get2;const state=(_store$getState$nextT2=store.getState().nextTree)!==null&&_store$getState$nextT2!==void 0?_store$getState$nextT2:store.getState().currentTree;if(((_state$atomValues$get2=state.atomValues.get(key))===null||_state$atomValues$get2===void 0?void 0:_state$atomValues$get2.contents)===wrappedPromise){setRecoilValueLoadable$2(store,node,loadableWithError$2(error));}throw error;});return wrappedPromise;}function initAtom(store,initState,trigger){var _options$effects;liveStoresCount++;const cleanupAtom=()=>{var _cleanupEffectsByStor;liveStoresCount--;(_cleanupEffectsByStor=cleanupEffectsByStore.get(store))===null||_cleanupEffectsByStor===void 0?void 0:_cleanupEffectsByStor.forEach(cleanup=>cleanup());cleanupEffectsByStore.delete(store);};store.getState().knownAtoms.add(key);// Setup async defaults to notify subscribers when they resolve if(defaultLoadable.state==='loading'){const notifyDefaultSubscribers=()=>{var _store$getState$nextT3;const state=(_store$getState$nextT3=store.getState().nextTree)!==null&&_store$getState$nextT3!==void 0?_store$getState$nextT3:store.getState().currentTree;if(!state.atomValues.has(key)){markRecoilValueModified$2(store,node);}};defaultLoadable.contents.finally(notifyDefaultSubscribers);}/////////////////// // Run Atom Effects /////////////////// const effects=(_options$effects=options.effects)!==null&&_options$effects!==void 0?_options$effects:options.effects_UNSTABLE;if(effects!=null){// This state is scoped by Store, since this is in the initAtom() closure let initValue=DEFAULT_VALUE$7;let isDuringInit=true;let isInitError=false;let pendingSetSelf=null;function getLoadable(recoilValue){// Normally we can just get the current value of another atom. // But for our own value we need to check if there is a pending // initialized value or get the fallback default value. if(isDuringInit&&recoilValue.key===key){// Cast T to S const retValue=initValue;// flowlint-line unclear-type:off return retValue instanceof DefaultValue$2?peekAtom(store,initState)// flowlint-line unclear-type:off :Recoil_isPromise(retValue)?loadableWithPromise$2(retValue.then(v=>v instanceof DefaultValue$2?// Cast T to S defaultLoadable.toPromise()// flowlint-line unclear-type:off :v)):// $FlowFixMe[incompatible-call] loadableWithValue$3(retValue);}return getRecoilValueAsLoadable$4(store,recoilValue);}function getPromise(recoilValue){return getLoadable(recoilValue).toPromise();}function getInfo_UNSTABLE(recoilValue){var _store$getState$nextT4;const info=peekNodeInfo$3(store,(_store$getState$nextT4=store.getState().nextTree)!==null&&_store$getState$nextT4!==void 0?_store$getState$nextT4:store.getState().currentTree,recoilValue.key);return isDuringInit&&recoilValue.key===key&&!(initValue instanceof DefaultValue$2)?{...info,isSet:true,loadable:getLoadable(recoilValue)}:info;}const setSelf=effect=>valueOrUpdater=>{if(isDuringInit){const currentLoadable=getLoadable(node);const currentValue=currentLoadable.state==='hasValue'?currentLoadable.contents:DEFAULT_VALUE$7;initValue=typeof valueOrUpdater==='function'?// cast to any because we can't restrict T from being a function without losing support for opaque types valueOrUpdater(currentValue)// flowlint-line unclear-type:off :valueOrUpdater;if(Recoil_isPromise(initValue)){initValue=initValue.then(value=>{// Avoid calling onSet() when setSelf() initializes with a Promise pendingSetSelf={effect,value};return value;});}}else {if(Recoil_isPromise(valueOrUpdater)){throw Recoil_err('Setting atoms to async values is not implemented.');}if(typeof valueOrUpdater!=='function'){pendingSetSelf={effect,value:unwrap(valueOrUpdater)};}setRecoilValue$4(store,node,typeof valueOrUpdater==='function'?currentValue=>{const newValue=unwrap(// cast to any because we can't restrict T from being a function without losing support for opaque types valueOrUpdater(currentValue)// flowlint-line unclear-type:off );// $FlowFixMe[incompatible-type] pendingSetSelf={effect,value:newValue};return newValue;}:unwrap(valueOrUpdater));}};const resetSelf=effect=>()=>setSelf(effect)(DEFAULT_VALUE$7);const onSet=effect=>handler=>{var _cleanupEffectsByStor2;const{release}=store.subscribeToTransactions(currentStore=>{var _currentTree$atomValu;// eslint-disable-next-line prefer-const let{currentTree,previousTree}=currentStore.getState();if(!previousTree){previousTree=currentTree;// attempt to trundle on }const newLoadable=(_currentTree$atomValu=currentTree.atomValues.get(key))!==null&&_currentTree$atomValu!==void 0?_currentTree$atomValu:defaultLoadable;if(newLoadable.state==='hasValue'){var _previousTree$atomVal,_pendingSetSelf,_pendingSetSelf2,_pendingSetSelf3;const newValue=newLoadable.contents;const oldLoadable=(_previousTree$atomVal=previousTree.atomValues.get(key))!==null&&_previousTree$atomVal!==void 0?_previousTree$atomVal:defaultLoadable;const oldValue=oldLoadable.state==='hasValue'?oldLoadable.contents:DEFAULT_VALUE$7;// TODO This isn't actually valid, use as a placeholder for now. // Ignore atom value changes that were set via setSelf() in the same effect. // We will still properly call the handler if there was a subsequent // set from something other than an atom effect which was batched // with the `setSelf()` call. However, we may incorrectly ignore // the handler if the subsequent batched call happens to set the // atom to the exact same value as the `setSelf()`. But, in that // case, it was kind of a noop, so the semantics are debatable.. if(((_pendingSetSelf=pendingSetSelf)===null||_pendingSetSelf===void 0?void 0:_pendingSetSelf.effect)!==effect||((_pendingSetSelf2=pendingSetSelf)===null||_pendingSetSelf2===void 0?void 0:_pendingSetSelf2.value)!==newValue){handler(newValue,oldValue,!currentTree.atomValues.has(key));}else if(((_pendingSetSelf3=pendingSetSelf)===null||_pendingSetSelf3===void 0?void 0:_pendingSetSelf3.effect)===effect){pendingSetSelf=null;}}},key);cleanupEffectsByStore.set(store,[...((_cleanupEffectsByStor2=cleanupEffectsByStore.get(store))!==null&&_cleanupEffectsByStor2!==void 0?_cleanupEffectsByStor2:[]),release]);};for(const effect of effects){try{const cleanup=effect({node,storeID:store.storeID,parentStoreID_UNSTABLE:store.parentStoreID,trigger,setSelf:setSelf(effect),resetSelf:resetSelf(effect),onSet:onSet(effect),getPromise,getLoadable,getInfo_UNSTABLE});if(cleanup!=null){var _cleanupEffectsByStor3;cleanupEffectsByStore.set(store,[...((_cleanupEffectsByStor3=cleanupEffectsByStore.get(store))!==null&&_cleanupEffectsByStor3!==void 0?_cleanupEffectsByStor3:[]),cleanup]);}}catch(error){initValue=error;isInitError=true;}}isDuringInit=false;// Mutate initial state in place since we know there are no other subscribers // since we are the ones initializing on first use. if(!(initValue instanceof DefaultValue$2)){var _store$getState$nextT5;const initLoadable=isInitError?loadableWithError$2(initValue):Recoil_isPromise(initValue)?loadableWithPromise$2(wrapPendingPromise(store,initValue)):loadableWithValue$3(unwrap(initValue));maybeFreezeValueOrPromise(initLoadable.contents);initState.atomValues.set(key,initLoadable);// If there is a pending transaction, then also mutate the next state tree. // This could happen if the atom was first initialized in an action that // also updated some other atom's state. (_store$getState$nextT5=store.getState().nextTree)===null||_store$getState$nextT5===void 0?void 0:_store$getState$nextT5.atomValues.set(key,initLoadable);}}return cleanupAtom;}function peekAtom(_store,state){var _ref,_state$atomValues$get3;return (_ref=(_state$atomValues$get3=state.atomValues.get(key))!==null&&_state$atomValues$get3!==void 0?_state$atomValues$get3:cachedAnswerForUnvalidatedValue)!==null&&_ref!==void 0?_ref:defaultLoadable;}function getAtom(_store,state){if(state.atomValues.has(key)){// Atom value is stored in state: return Recoil_nullthrows(state.atomValues.get(key));}else if(state.nonvalidatedAtoms.has(key)){// Atom value is stored but needs validation before use. // We might have already validated it and have a cached validated value: if(cachedAnswerForUnvalidatedValue!=null){return cachedAnswerForUnvalidatedValue;}if(persistence==null){return defaultLoadable;}const nonvalidatedValue=state.nonvalidatedAtoms.get(key);const validatorResult=persistence.validator(nonvalidatedValue,DEFAULT_VALUE$7);const validatedValueLoadable=validatorResult instanceof DefaultValue$2?defaultLoadable:loadableWithValue$3(validatorResult);cachedAnswerForUnvalidatedValue=validatedValueLoadable;return cachedAnswerForUnvalidatedValue;}else {return defaultLoadable;}}function invalidateAtom(){cachedAnswerForUnvalidatedValue=undefined;}function setAtom(_store,state,newValue){// Bail out if we're being set to the existing value, or if we're being // reset but have no stored value (validated or unvalidated) to reset from: if(state.atomValues.has(key)){const existing=Recoil_nullthrows(state.atomValues.get(key));if(existing.state==='hasValue'&&newValue===existing.contents){return new Map();}}else if(!state.nonvalidatedAtoms.has(key)&&newValue instanceof DefaultValue$2){return new Map();}cachedAnswerForUnvalidatedValue=undefined;// can be released now if it was previously in use return new Map().set(key,loadableWithValue$3(newValue));}function shouldDeleteConfigOnReleaseAtom(){return getConfigDeletionHandler$2(key)!==undefined&&liveStoresCount<=0;}const node=registerNode$2({key,nodeType:'atom',peek:peekAtom,get:getAtom,set:setAtom,init:initAtom,invalidate:invalidateAtom,shouldDeleteConfigOnRelease:shouldDeleteConfigOnReleaseAtom,dangerouslyAllowMutability:options.dangerouslyAllowMutability,persistence_UNSTABLE:options.persistence_UNSTABLE?{type:options.persistence_UNSTABLE.type,backButton:options.persistence_UNSTABLE.backButton}:undefined,shouldRestoreFromSnapshots:true,retainedBy});return node;}// prettier-ignore function atom(options){const{// @fb-only: scopeRules_APPEND_ONLY_READ_THE_DOCS, ...restOptions}=options;const optionsDefault='default'in options?// $FlowIssue[incompatible-type] No way to refine in Flow that property is not defined options.default:new Promise(()=>{});if(isRecoilValue$4(optionsDefault)// Continue to use atomWithFallback for promise defaults for scoped atoms // for now, since scoped atoms don't support async defaults // @fb-only: || (isPromise(optionsDefault) && scopeRules_APPEND_ONLY_READ_THE_DOCS) // @fb-only: || (isLoadable(optionsDefault) && scopeRules_APPEND_ONLY_READ_THE_DOCS) ){return atomWithFallback({...restOptions,default:optionsDefault// @fb-only: scopeRules_APPEND_ONLY_READ_THE_DOCS, });// @fb-only: } else if (scopeRules_APPEND_ONLY_READ_THE_DOCS // @fb-only: && !isPromise(optionsDefault) // @fb-only: && !isLoadable(optionsDefault) // @fb-only: ) { // @fb-only: return scopedAtom({ // @fb-only: ...restOptions, // @fb-only: default: unwrap(optionsDefault), // @fb-only: scopeRules_APPEND_ONLY_READ_THE_DOCS, // @fb-only: }); }else {return baseAtom({...restOptions,default:optionsDefault});}}function atomWithFallback(options){const base=atom({...options,default:DEFAULT_VALUE$7,persistence_UNSTABLE:options.persistence_UNSTABLE===undefined?undefined:{...options.persistence_UNSTABLE,validator:storedValue=>storedValue instanceof DefaultValue$2?storedValue:Recoil_nullthrows(options.persistence_UNSTABLE).validator(storedValue,DEFAULT_VALUE$7)},// TODO Hack for now. effects:options.effects,// flowlint-line unclear-type: off effects_UNSTABLE:options.effects_UNSTABLE// flowlint-line unclear-type: off });// $FlowFixMe[incompatible-call] const sel=Recoil_selector({key:`${options.key}__withFallback`,get:({get})=>{const baseValue=get(base);return baseValue instanceof DefaultValue$2?options.default:baseValue;},// $FlowFixMe[incompatible-call] set:({set},newValue)=>set(base,newValue),// This selector does not need to cache as it is a wrapper selector // and the selector within the wrapper selector will have a cache // option by default cachePolicy_UNSTABLE:{eviction:'most-recent'},dangerouslyAllowMutability:options.dangerouslyAllowMutability});setConfigDeletionHandler$1(sel.key,getConfigDeletionHandler$2(options.key));return sel;}// $FlowFixMe[missing-local-annot] atom.value=value=>new WrappedValue$2(value);var Recoil_atom=atom;/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format * @oncall recoil */class MapCache{constructor(options){var _options$mapKey;_defineProperty(this,"_map",void 0);_defineProperty(this,"_keyMapper",void 0);this._map=new Map();this._keyMapper=(_options$mapKey=options===null||options===void 0?void 0:options.mapKey)!==null&&_options$mapKey!==void 0?_options$mapKey:v=>v;}size(){return this._map.size;}has(key){return this._map.has(this._keyMapper(key));}get(key){return this._map.get(this._keyMapper(key));}set(key,val){this._map.set(this._keyMapper(key),val);}delete(key){this._map.delete(this._keyMapper(key));}clear(){this._map.clear();}}var Recoil_MapCache={MapCache};var Recoil_MapCache_1=Recoil_MapCache.MapCache;var Recoil_MapCache$1=/*#__PURE__*/Object.freeze({__proto__:null,MapCache:Recoil_MapCache_1});const{LRUCache:LRUCache$2}=Recoil_LRUCache$1;const{MapCache:MapCache$1}=Recoil_MapCache$1;const defaultPolicy$1={equality:'reference',eviction:'none',maxSize:Infinity};function cacheFromPolicy({equality=defaultPolicy$1.equality,eviction=defaultPolicy$1.eviction,maxSize=defaultPolicy$1.maxSize}=defaultPolicy$1){const valueMapper=getValueMapper$1(equality);const cache=getCache(eviction,maxSize,valueMapper);return cache;}function getValueMapper$1(equality){switch(equality){case'reference':return val=>val;case'value':return val=>Recoil_stableStringify(val);}throw Recoil_err(`Unrecognized equality policy ${equality}`);}function getCache(eviction,maxSize,mapKey){switch(eviction){case'keep-all':return new MapCache$1({mapKey});case'lru':return new LRUCache$2({mapKey,maxSize:Recoil_nullthrows(maxSize)});case'most-recent':return new LRUCache$2({mapKey,maxSize:1});}throw Recoil_err(`Unrecognized eviction policy ${eviction}`);}var Recoil_cacheFromPolicy=cacheFromPolicy;// @fb-only: import type {ScopeRules} from 'Recoil_ScopedAtom'; const{setConfigDeletionHandler:setConfigDeletionHandler$2}=Recoil_Node;// Process scopeRules to handle any entries which are functions taking parameters // prettier-ignore // @fb-only: function mapScopeRules

( // @fb-only: scopeRules?: ParameterizedScopeRules

, // @fb-only: param: P, // @fb-only: ): ScopeRules | void { // @fb-only: return scopeRules?.map(rule => // @fb-only: Array.isArray(rule) // @fb-only: ? rule.map(entry => (typeof entry === 'function' ? entry(param) : entry)) // @fb-only: : rule, // @fb-only: ); // @fb-only: } /* A function which returns an atom based on the input parameter. Each unique parameter returns a unique atom. E.g., const f = atomFamily(...); f({a: 1}) => an atom f({a: 2}) => a different atom This allows components to persist local, private state using atoms. Each instance of the component may have a different key, which it uses as the parameter for a family of atoms; in this way, each component will have its own atom not shared by other instances. These state keys may be composed into children's state keys as well. */function atomFamily(options){var _options$cachePolicyF,_options$cachePolicyF2;const atomCache=Recoil_cacheFromPolicy({equality:(_options$cachePolicyF=(_options$cachePolicyF2=options.cachePolicyForParams_UNSTABLE)===null||_options$cachePolicyF2===void 0?void 0:_options$cachePolicyF2.equality)!==null&&_options$cachePolicyF!==void 0?_options$cachePolicyF:'value',eviction:'keep-all'});// Simple atomFamily implementation to cache individual atoms based // on the parameter value equality. return params=>{var _stableStringify,_options$effects;const cachedAtom=atomCache.get(params);if(cachedAtom!=null){return cachedAtom;}const{cachePolicyForParams_UNSTABLE,...atomOptions}=options;const optionsDefault='default'in options?// $FlowIssue[incompatible-type] No way to refine in Flow that property is not defined options.default:new Promise(()=>{});const newAtom=Recoil_atom({...atomOptions,key:`${options.key}__${(_stableStringify=Recoil_stableStringify(params))!==null&&_stableStringify!==void 0?_stableStringify:'void'}`,default:typeof optionsDefault==='function'?// The default was parameterized // Flow doesn't know that T isn't a function, so we need to case to any // $FlowIssue[incompatible-use] optionsDefault(params):// Default may be a static value, promise, or RecoilValue optionsDefault,retainedBy_UNSTABLE:typeof options.retainedBy_UNSTABLE==='function'?options.retainedBy_UNSTABLE(params):options.retainedBy_UNSTABLE,effects:typeof options.effects==='function'?options.effects(params):typeof options.effects_UNSTABLE==='function'?options.effects_UNSTABLE(params):(_options$effects=options.effects)!==null&&_options$effects!==void 0?_options$effects:options.effects_UNSTABLE// prettier-ignore // @fb-only: scopeRules_APPEND_ONLY_READ_THE_DOCS: mapScopeRules( // @fb-only: options.scopeRules_APPEND_ONLY_READ_THE_DOCS, // @fb-only: params, // @fb-only: ), });atomCache.set(params,newAtom);setConfigDeletionHandler$2(newAtom.key,()=>{atomCache.delete(params);});return newAtom;};}var Recoil_atomFamily=atomFamily;const{setConfigDeletionHandler:setConfigDeletionHandler$3}=Recoil_Node;// Keep in mind the parameter needs to be serializable as a cahche key // using Recoil_stableStringify // Add a unique index to each selector in case the cache implementation allows // duplicate keys based on equivalent stringified parameters let nextIndex=0;/* eslint-disable no-redeclare */ // Return a function that returns members of a family of selectors of the same type // E.g., // // const s = selectorFamily(...); // s({a: 1}) => a selector // s({a: 2}) => a different selector // // By default, the selectors are distinguished by distinct values of the // parameter based on value equality, not reference equality. This allows using // object literals or other equivalent objects at callsites to not create // duplicate cache entries. This behavior may be overridden with the // cacheImplementationForParams option. function selectorFamily(options){var _options$cachePolicyF,_options$cachePolicyF2;const selectorCache=Recoil_cacheFromPolicy({equality:(_options$cachePolicyF=(_options$cachePolicyF2=options.cachePolicyForParams_UNSTABLE)===null||_options$cachePolicyF2===void 0?void 0:_options$cachePolicyF2.equality)!==null&&_options$cachePolicyF!==void 0?_options$cachePolicyF:'value',eviction:'keep-all'});return params=>{var _stableStringify;// Throw an error with selector key so that it is clear which // selector is causing an error let cachedSelector;try{cachedSelector=selectorCache.get(params);}catch(error){throw Recoil_err(`Problem with cache lookup for selector ${options.key}: ${error.message}`);}if(cachedSelector!=null){return cachedSelector;}const myKey=`${options.key}__selectorFamily/${(_stableStringify=Recoil_stableStringify(params,{// It is possible to use functions in parameters if the user uses // a cache with reference equality thanks to the incrementing index. allowFunctions:true}))!==null&&_stableStringify!==void 0?_stableStringify:'void'}/${nextIndex++}`;// Append index in case values serialize to the same key string const myGet=callbacks=>options.get(params)(callbacks);const myCachePolicy=options.cachePolicy_UNSTABLE;const retainedBy=typeof options.retainedBy_UNSTABLE==='function'?options.retainedBy_UNSTABLE(params):options.retainedBy_UNSTABLE;let newSelector;if(options.set!=null){const set=options.set;const mySet=(callbacks,newValue)=>set(params)(callbacks,newValue);newSelector=Recoil_selector({key:myKey,get:myGet,set:mySet,cachePolicy_UNSTABLE:myCachePolicy,dangerouslyAllowMutability:options.dangerouslyAllowMutability,retainedBy_UNSTABLE:retainedBy});}else {newSelector=Recoil_selector({key:myKey,get:myGet,cachePolicy_UNSTABLE:myCachePolicy,dangerouslyAllowMutability:options.dangerouslyAllowMutability,retainedBy_UNSTABLE:retainedBy});}selectorCache.set(params,newSelector);setConfigDeletionHandler$3(newSelector.key,()=>{selectorCache.delete(params);});return newSelector;};}/* eslint-enable no-redeclare */var Recoil_selectorFamily=selectorFamily;// flowlint-next-line unclear-type:off const constantSelector=Recoil_selectorFamily({key:'__constant',get:constant=>()=>constant,cachePolicyForParams_UNSTABLE:{equality:'reference'}});// Function that returns a selector which always produces the // same constant value. It may be called multiple times with the // same value, based on reference equality, and will provide the // same selector. function constSelector(constant){return constantSelector(constant);}var Recoil_constSelector=constSelector;// flowlint-next-line unclear-type:off const throwingSelector=Recoil_selectorFamily({key:'__error',get:message=>()=>{throw Recoil_err(message);},// TODO Why? cachePolicyForParams_UNSTABLE:{equality:'reference'}});// Function that returns a selector which always throws an error // with the provided message. function errorSelector(message){return throwingSelector(message);}var Recoil_errorSelector=errorSelector;/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * Wraps another recoil value and prevents writing to it. * * * @format * @oncall recoil */function readOnlySelector(atom){// flowlint-next-line unclear-type: off return atom;}var Recoil_readOnlySelector=readOnlySelector;const{loadableWithError:loadableWithError$3,loadableWithPromise:loadableWithPromise$3,loadableWithValue:loadableWithValue$4}=Recoil_Loadable$1;///////////////// // TRUTH TABLE ///////////////// // Dependencies waitForNone waitForAny waitForAll waitForAllSettled // [loading, loading] [Promise, Promise] Promise Promise Promise // [value, loading] [value, Promise] [value, Promise] Promise Promise // [value, value] [value, value] [value, value] [value, value] [value, value] // // [error, loading] [Error, Promise] [Error, Promise] Error Promise // [error, error] [Error, Error] [Error, Error] Error [error, error] // [value, error] [value, Error] [value, Error] Error [value, error] // Issue parallel requests for all dependencies and return the current // status if they have results, have some error, or are still pending. function concurrentRequests(getRecoilValue,deps){const results=Array(deps.length).fill(undefined);const exceptions=Array(deps.length).fill(undefined);for(const[i,dep]of deps.entries()){try{results[i]=getRecoilValue(dep);}catch(e){// exceptions can either be Promises of pending results or real errors exceptions[i]=e;}}return [results,exceptions];}function isError(exp){return exp!=null&&!Recoil_isPromise(exp);}function unwrapDependencies(dependencies){return Array.isArray(dependencies)?dependencies:Object.getOwnPropertyNames(dependencies).map(key=>dependencies[key]);}function wrapResults(dependencies,/* $FlowFixMe[missing-local-annot] The type annotation(s) required by Flow's * LTI update could not be added via codemod */results){return Array.isArray(dependencies)?results:// Object.getOwnPropertyNames() has consistent key ordering with ES6 Object.getOwnPropertyNames(dependencies).reduce((out,key,idx)=>({...out,[key]:results[idx]}),{});}function wrapLoadables(dependencies,results,exceptions){const output=exceptions.map((exception,idx)=>exception==null?loadableWithValue$4(results[idx]):Recoil_isPromise(exception)?loadableWithPromise$3(exception):loadableWithError$3(exception));return wrapResults(dependencies,output);}function combineAsyncResultsWithSyncResults(syncResults,asyncResults){return asyncResults.map((result,idx)=>/** * it's important we use === undefined as opposed to == null, because the * resolved value of the async promise could be `null`, in which case we * don't want to use syncResults[idx], which would be undefined. If async * promise resolves to `undefined`, that's ok because `syncResults[idx]` * will also be `undefined`. That's a little hacky, but it works. */result===undefined?syncResults[idx]:result);}// Selector that requests all dependencies in parallel and immediately returns // current results without waiting. const waitForNone=Recoil_selectorFamily({key:'__waitForNone',get:dependencies=>({get})=>{// Issue requests for all dependencies in parallel. const deps=unwrapDependencies(dependencies);const[results,exceptions]=concurrentRequests(get,deps);// Always return the current status of the results; never block. return wrapLoadables(dependencies,results,exceptions);},dangerouslyAllowMutability:true});// Selector that requests all dependencies in parallel and waits for at least // one to be available before returning results. It will only error if all // dependencies have errors. const waitForAny=Recoil_selectorFamily({key:'__waitForAny',get:dependencies=>({get})=>{// Issue requests for all dependencies in parallel. // Exceptions can either be Promises of pending results or real errors const deps=unwrapDependencies(dependencies);const[results,exceptions]=concurrentRequests(get,deps);// If any results are available, value or error, return the current status if(exceptions.some(exp=>!Recoil_isPromise(exp))){return wrapLoadables(dependencies,results,exceptions);}// Otherwise, return a promise that will resolve when the next result is // available, whichever one happens to be next. But, if all pending // dependencies end up with errors, then reject the promise. return new Promise(resolve=>{for(const[i,exp]of exceptions.entries()){if(Recoil_isPromise(exp)){exp.then(result=>{results[i]=result;exceptions[i]=undefined;resolve(wrapLoadables(dependencies,results,exceptions));}).catch(error=>{exceptions[i]=error;resolve(wrapLoadables(dependencies,results,exceptions));});}}});},dangerouslyAllowMutability:true});// Selector that requests all dependencies in parallel and waits for all to be // available before returning a value. It will error if any dependencies error. const waitForAll=Recoil_selectorFamily({key:'__waitForAll',get:dependencies=>({get})=>{// Issue requests for all dependencies in parallel. // Exceptions can either be Promises of pending results or real errors const deps=unwrapDependencies(dependencies);const[results,exceptions]=concurrentRequests(get,deps);// If all results are available, return the results if(exceptions.every(exp=>exp==null)){return wrapResults(dependencies,results);}// If we have any errors, throw the first error const error=exceptions.find(isError);if(error!=null){throw error;}// Otherwise, return a promise that will resolve when all results are available return Promise.all(exceptions).then(exceptionResults=>wrapResults(dependencies,combineAsyncResultsWithSyncResults(results,exceptionResults)));},dangerouslyAllowMutability:true});const waitForAllSettled=Recoil_selectorFamily({key:'__waitForAllSettled',get:dependencies=>({get})=>{// Issue requests for all dependencies in parallel. // Exceptions can either be Promises of pending results or real errors const deps=unwrapDependencies(dependencies);const[results,exceptions]=concurrentRequests(get,deps);// If all results are available, return the results if(exceptions.every(exp=>!Recoil_isPromise(exp))){return wrapLoadables(dependencies,results,exceptions);}// Wait for all results to settle return Promise.all(exceptions.map((exp,i)=>Recoil_isPromise(exp)?exp.then(result=>{results[i]=result;exceptions[i]=undefined;}).catch(error=>{results[i]=undefined;exceptions[i]=error;}):null))// Then wrap them as loadables .then(()=>wrapLoadables(dependencies,results,exceptions));},dangerouslyAllowMutability:true});const noWait=Recoil_selectorFamily({key:'__noWait',get:dependency=>({get})=>{try{return Recoil_selector.value(loadableWithValue$4(get(dependency)));}catch(exception){return Recoil_selector.value(Recoil_isPromise(exception)?loadableWithPromise$3(exception):loadableWithError$3(exception));}},dangerouslyAllowMutability:true});var Recoil_WaitFor={waitForNone,waitForAny,waitForAll,waitForAllSettled,noWait};const{RecoilLoadable}=Recoil_Loadable$1;const{DefaultValue:DefaultValue$3}=Recoil_Node;const{RecoilRoot:RecoilRoot$2,useRecoilStoreID:useRecoilStoreID$1}=Recoil_RecoilRoot;const{isRecoilValue:isRecoilValue$5}=Recoil_RecoilValue$1;const{retentionZone:retentionZone$1}=Recoil_RetentionZone;const{freshSnapshot:freshSnapshot$2}=Recoil_Snapshot$1;const{useRecoilState:useRecoilState$1,useRecoilState_TRANSITION_SUPPORT_UNSTABLE:useRecoilState_TRANSITION_SUPPORT_UNSTABLE$1,useRecoilStateLoadable:useRecoilStateLoadable$1,useRecoilValue:useRecoilValue$1,useRecoilValue_TRANSITION_SUPPORT_UNSTABLE:useRecoilValue_TRANSITION_SUPPORT_UNSTABLE$1,useRecoilValueLoadable:useRecoilValueLoadable$1,useRecoilValueLoadable_TRANSITION_SUPPORT_UNSTABLE:useRecoilValueLoadable_TRANSITION_SUPPORT_UNSTABLE$1,useResetRecoilState:useResetRecoilState$1,useSetRecoilState:useSetRecoilState$1}=Recoil_Hooks;const{useGotoRecoilSnapshot:useGotoRecoilSnapshot$1,useRecoilSnapshot:useRecoilSnapshot$1,useRecoilTransactionObserver:useRecoilTransactionObserver$1}=Recoil_SnapshotHooks;const{useRecoilCallback:useRecoilCallback$1}=Recoil_useRecoilCallback;const{noWait:noWait$1,waitForAll:waitForAll$1,waitForAllSettled:waitForAllSettled$1,waitForAny:waitForAny$1,waitForNone:waitForNone$1}=Recoil_WaitFor;var Recoil_index={// Types DefaultValue:DefaultValue$3,isRecoilValue:isRecoilValue$5,RecoilLoadable,// Global Recoil environment settiongs RecoilEnv:Recoil_RecoilEnv,// Recoil Root RecoilRoot:RecoilRoot$2,useRecoilStoreID:useRecoilStoreID$1,useRecoilBridgeAcrossReactRoots_UNSTABLE:Recoil_useRecoilBridgeAcrossReactRoots,// Atoms/Selectors atom:Recoil_atom,selector:Recoil_selector,// Convenience Atoms/Selectors atomFamily:Recoil_atomFamily,selectorFamily:Recoil_selectorFamily,constSelector:Recoil_constSelector,errorSelector:Recoil_errorSelector,readOnlySelector:Recoil_readOnlySelector,// Concurrency Helpers for Atoms/Selectors noWait:noWait$1,waitForNone:waitForNone$1,waitForAny:waitForAny$1,waitForAll:waitForAll$1,waitForAllSettled:waitForAllSettled$1,// Hooks for Atoms/Selectors useRecoilValue:useRecoilValue$1,useRecoilValueLoadable:useRecoilValueLoadable$1,useRecoilState:useRecoilState$1,useRecoilStateLoadable:useRecoilStateLoadable$1,useSetRecoilState:useSetRecoilState$1,useResetRecoilState:useResetRecoilState$1,useGetRecoilValueInfo_UNSTABLE:Recoil_useGetRecoilValueInfo,useRecoilRefresher_UNSTABLE:Recoil_useRecoilRefresher,useRecoilValueLoadable_TRANSITION_SUPPORT_UNSTABLE:useRecoilValueLoadable_TRANSITION_SUPPORT_UNSTABLE$1,useRecoilValue_TRANSITION_SUPPORT_UNSTABLE:useRecoilValue_TRANSITION_SUPPORT_UNSTABLE$1,useRecoilState_TRANSITION_SUPPORT_UNSTABLE:useRecoilState_TRANSITION_SUPPORT_UNSTABLE$1,// Hooks for complex operations useRecoilCallback:useRecoilCallback$1,useRecoilTransaction_UNSTABLE:Recoil_useRecoilTransaction,// Snapshots useGotoRecoilSnapshot:useGotoRecoilSnapshot$1,useRecoilSnapshot:useRecoilSnapshot$1,useRecoilTransactionObserver_UNSTABLE:useRecoilTransactionObserver$1,snapshot_UNSTABLE:freshSnapshot$2,// Memory Management useRetain:Recoil_useRetain,retentionZone:retentionZone$1};var Recoil_index_5=Recoil_index.RecoilRoot;var Recoil_index_8=Recoil_index.atom;var Recoil_index_22=Recoil_index.useRecoilState; const view = Recoil_index_8({ key: 'fileTreeViewState', default: 'folder', }); const activeFolderPath = Recoil_index_8({ key: 'fileTreeActiveFolderPathState', default: '', }); const activeOZFile = Recoil_index_8({ key: 'fileTreeActiveOZFile', default: null, }); const excludedFolders = Recoil_index_8({ key: 'fileTreeExcludedFoldersState', default: [], }); const excludedExtensions = Recoil_index_8({ key: 'fileTreeExcludedExtensions', default: [], }); const folderFileCountMap = Recoil_index_8({ key: 'fileTreeFolderFileCountMapState', default: {}, }); const folderTree = Recoil_index_8({ key: 'fileTreeFolderTreeState', default: null, dangerouslyAllowMutability: true, }); const ozFileList = Recoil_index_8({ key: 'fileTreeOzFileListState', default: [], }); const ozPinnedFileList = Recoil_index_8({ key: 'fileTreeOzPinnedFilesState', default: [], }); const openFolders = Recoil_index_8({ key: 'fileTreeOpenFoldersState', default: [], }); const showSubFolders = Recoil_index_8({ key: 'showSubFoldersInVault', default: false, }); const focusedFolder = Recoil_index_8({ key: 'fileTreeFocusedFolder', default: null, dangerouslyAllowMutability: true, }); function useForceUpdate() { const [value, setValue] = reactExports.useState(0); return () => setValue((value) => value + 1); } function isMouseEvent(e) { return e && 'screenX' in e; } function useLongPress(callback = (e) => { }, ms = 300) { const [startLongPress, setStartLongPress] = reactExports.useState(false); const [longPressEvent, setLongPressEvent] = reactExports.useState(null); const [startLocationY, setStartLocationY] = reactExports.useState(null); reactExports.useEffect(() => { let timerId; if (startLongPress && startLocationY) { timerId = setTimeout(() => { callback(longPressEvent); stop(longPressEvent); }, ms); } else { clearTimeout(timerId); } return () => { clearTimeout(timerId); }; }, [callback, ms, startLongPress, startLocationY]); const start = reactExports.useCallback((e) => { setStartLongPress(true); setStartLocationY(e.touches[0].clientY); setLongPressEvent(e); }, []); const move = reactExports.useCallback((e) => { if (startLocationY) { let dist = Math.abs(e.touches[0].clientY - startLocationY); if (dist >= 0.5) stop(e); } }, [startLocationY]); const stop = reactExports.useCallback((e) => { setStartLongPress(false); setLongPressEvent(null); }, []); return { onTouchStart: start, onTouchMove: move, onTouchEnd: stop, }; } // ----> FILE TREE COMPONENT HANDLERS <----- \\ // Function After an External File Dropped into Folder Name const handleOnDropFiles = (params) => { let { files, activeFolderPath, plugin } = params; files.map((file) => __awaiter(void 0, void 0, void 0, function* () { file.arrayBuffer().then((arrayBuffer) => { plugin.app.vault.adapter.writeBinary(activeFolderPath + '/' + file.name, arrayBuffer); }); })); }; const getFilesWithName = (params) => { let { searchPhrase, searchFolder, plugin, getAllFiles, excludedExtensions, excludedFolders } = params; var files = getFilesUnderPath({ path: searchFolder, plugin: plugin, excludedExtensions: excludedExtensions, excludedFolders: excludedFolders, getAllFiles: getAllFiles, }); var filteredFiles = files.filter((file) => file.basename.toLowerCase().includes(searchPhrase.toLowerCase().trimStart())); return filteredFiles; }; const getFileTags = (params) => { let { f, plugin } = params; let mdFile = plugin.app.vault.getAbstractFileByPath(f.path); if (!mdFile) return []; let fileCache = plugin.app.metadataCache.getFileCache(mdFile); let fileTags = []; if (fileCache.tags) { for (let fileTag of fileCache.tags) { fileTags.push(fileTag.tag); } } if (fileCache.frontmatter && fileCache.frontmatter['tags']) { let tagsFM = fileCache.frontmatter['tags']; if (typeof tagsFM === 'string') { let fileFMTags = tagsFM.split(','); for (let i = 0; i < fileFMTags.length; i++) { fileTags.push(fileFMTags[i]); } } else if (Array.isArray(tagsFM)) { for (let i = 0; i < tagsFM.length; i++) { fileTags.push(tagsFM[i]); } } } return fileTags; }; const getFilesWithTag = (params) => { let { searchTag, plugin, focusedFolder, excludedExtensions, excludedFolders } = params; let filesWithTag = new Set(); let ozFiles = getFilesUnderPath({ path: plugin.settings.allSearchOnlyInFocusedFolder ? focusedFolder.path : '/', plugin: plugin, excludedExtensions: excludedExtensions, excludedFolders: excludedFolders, getAllFiles: true, }); for (let ozFile of ozFiles) { let fileTags = getFileTags({ f: ozFile, plugin: plugin, }); for (let fileTag of fileTags) { if (fileTag.toLowerCase().contains(searchTag.toLowerCase().trimStart())) { if (!filesWithTag.has(ozFile)) filesWithTag.add(ozFile); } } } return filesWithTag; }; const handleRevealActiveFileButton = (params) => { let { plugin } = params; let event = new CustomEvent(eventTypes.revealFile, { detail: { file: plugin.app.workspace.getActiveFile(), }, }); window.dispatchEvent(event); }; // Sort - Filter Files Depending on Preferences const sortedFiles = (params) => { let { fileList, plugin, ozPinnedFiles } = params; let sortedfileList = fileList; // Remove Files for Folder Note (If file name is same as parent folder name) if (plugin.settings.folderNote) { sortedfileList = sortedfileList.filter((f) => !f.isFolderNote); } // Sort File by Name or Last Content Update, moving pinned files to the front sortedfileList = sortedfileList.sort((a, b) => { if (ozPinnedFiles.some((f) => f.path === a.path) && !ozPinnedFiles.some((f) => f.path === b.path)) { return -1; } else if (!ozPinnedFiles.some((f) => f.path === a.path) && ozPinnedFiles.some((f) => f.path === b.path)) { return 1; } if (plugin.settings.sortReverse) { [a, b] = [b, a]; } if (plugin.settings.sortFilesBy === 'name') { return plugin.settings.showFileNameAsFullPath ? a.path.localeCompare(b.path, 'en', { numeric: true }) : a.basename.localeCompare(b.basename, 'en', { numeric: true }); } else if (plugin.settings.sortFilesBy === 'last-update') { return b.stat.mtime - a.stat.mtime; } else if (plugin.settings.sortFilesBy === 'created') { return b.stat.ctime - a.stat.ctime; } else if (plugin.settings.sortFilesBy === 'file-size') { return b.stat.size - a.stat.size; } }); return sortedfileList; }; const sortFileListClickHandle = (params) => { let { e, plugin, forceUpdate } = params; const sortMenu = new obsidian.Menu(); const changeSortSettingTo = (newValue) => { plugin.settings.sortFilesBy = newValue; plugin.saveSettings(); forceUpdate(); }; const addMenuItem = (label, low, high, value) => { sortMenu.addItem((menuItem) => { const order = plugin.settings.sortReverse ? `${high} to ${low}` : `${low} to ${high}`; menuItem.setTitle(`${label} (${order})`); menuItem.setIcon(value === plugin.settings.sortFilesBy ? 'checkmark' : 'spaceIcon'); menuItem.onClick(() => changeSortSettingTo(value)); }); }; addMenuItem('File Name', 'A', 'Z', 'name'); addMenuItem('Created', 'New', 'Old', 'created'); addMenuItem('File Size', 'Big', 'Small', 'file-size'); addMenuItem('Last Update', 'New', 'Old', 'last-update'); sortMenu.addSeparator(); sortMenu.addItem((menuItem) => { menuItem.setTitle('Reverse Order'); menuItem.setIcon(plugin.settings.sortReverse ? 'checkmark' : 'spaceIcon'); menuItem.onClick(() => { plugin.settings.sortReverse = !plugin.settings.sortReverse; plugin.saveSettings(); forceUpdate(); }); }); // Trigger sortMenu.showAtPosition({ x: e.pageX, y: e.pageY }); }; // Search Function const searchAllRegex = new RegExp('all:(.*)?'); const searchTagRegex = new RegExp('tag:(.*)?'); const handleSearch = (params) => { let { e, activeFolderPath, setSearchPhrase, setOzFileList, setTreeHeader, plugin, focusedFolder, excludedExtensions, excludedFolders } = params; var searchPhrase = e.target.value; setSearchPhrase(searchPhrase); var searchFolder = activeFolderPath; // Check Tag Regex in Search Phrase let tagRegexMatch = searchPhrase.match(searchTagRegex); if (tagRegexMatch) { setTreeHeader('Files with Tag'); if (tagRegexMatch[1] === undefined || tagRegexMatch[1].replace(/\s/g, '').length === 0) { setOzFileList([]); return; } setOzFileList([ ...getFilesWithTag({ searchTag: tagRegexMatch[1], plugin: plugin, focusedFolder: focusedFolder, excludedExtensions: excludedExtensions, excludedFolders: excludedFolders, }), ]); return; } // Check All Regex in Search Phrase let allRegexMatch = searchPhrase.match(searchAllRegex); if (allRegexMatch) { searchPhrase = allRegexMatch[1] ? allRegexMatch[1] : ''; searchFolder = plugin.settings.allSearchOnlyInFocusedFolder ? focusedFolder.path : '/'; setTreeHeader('All Files'); } else { setTreeHeader(getFolderName(activeFolderPath, plugin.app)); } let getAllFiles = allRegexMatch ? true : false; let filteredFiles = getFilesWithName({ searchPhrase, searchFolder, plugin, excludedExtensions, excludedFolders, getAllFiles, }); setOzFileList(filteredFiles); }; // ----> NAV FILE COMPONENT HANDLERS <----- \\ // Handle Click Event on File - Allows Open with Cmd/Ctrl const openFile = (params) => { let { file, e, plugin, setActiveOzFile } = params; openFile$1({ file: file, app: plugin.app, newLeaf: (e.ctrlKey || e.metaKey) && !(e.shiftKey || e.altKey), leafBySplit: (e.ctrlKey || e.metaKey) && (e.shiftKey || e.altKey), }); setActiveOzFile(file); }; const getFileIcon = (params) => { let { file } = params; return file.extension === 'pdf' ? AiFillFilePdf : ['png', 'jpg', 'jpeg', 'svg'].contains(file.extension) ? AiFillFileImage : ['doc', 'docx'].contains(file.extension) ? AiFillFileWord : BiFile; }; // --> Dragging for File const dragStarted = (params) => { let { e, file, plugin } = params; let obsidianFile = plugin.app.vault.getAbstractFileByPath(file.path); if (!obsidianFile) return; // json to move file to folder e.dataTransfer.setData('application/json', JSON.stringify({ filePath: file.path })); let dragManager = plugin.app.dragManager; const dragData = dragManager.dragFile(e.nativeEvent, obsidianFile); dragManager.onDragStart(e.nativeEvent, dragData); }; // --> AuxClick (Mouse Wheel Button Action) const onAuxClick = (params) => { let { e, plugin, file } = params; if (e.button === 1) openFileInNewTab(plugin.app, file); }; const mouseEnteredOnFile = (params) => { let { e, file, plugin, setHoverActive } = params; setHoverActive(true); if (plugin.settings.filePreviewOnHover && (e.ctrlKey || e.metaKey)) { plugin.app.workspace.trigger('link-hover', {}, e.target, file.path, file.path); } }; const mouseLeftFile = (params) => { params.setHoverActive(false); }; // Handle Right Click Event on File - Custom Menu const triggerContextMenu = (params) => { let { file, e, ozPinnedFiles, setOzPinnedFiles, plugin } = params; const fileMenu = new obsidian.Menu(); let fileToTrigger = plugin.app.vault.getAbstractFileByPath(file.path); if (!fileToTrigger) return; // Pin - Unpin Item fileMenu.addItem((menuItem) => { menuItem.setIcon('pin'); const isAlreadyPinned = ozPinnedFiles.some((pinnedFile) => pinnedFile.path === file.path); if (isAlreadyPinned) menuItem.setTitle('Unpin'); else menuItem.setTitle('Pin to Top'); menuItem.onClick((ev) => { if (isAlreadyPinned) { let newPinnedFiles = ozPinnedFiles.filter((pinnedFile) => pinnedFile.path !== file.path); setOzPinnedFiles(newPinnedFiles); } else { setOzPinnedFiles([...ozPinnedFiles, file]); } }); }); // Rename Item fileMenu.addItem((menuItem) => { menuItem.setTitle('Rename'); menuItem.setIcon('pencil'); menuItem.onClick((ev) => { let vaultChangeModal = new VaultChangeModal(plugin, file, 'rename'); vaultChangeModal.open(); }); }); // Delete Item fileMenu.addItem((menuItem) => { menuItem.setTitle('Delete'); menuItem.setIcon('trash'); menuItem.onClick((ev) => { let confirmationModal = new ConfirmationModal(plugin, `Are you sure you want to delete the file "${file.basename}${file.extension === 'md' ? '' : file.extension}"?`, function () { let deleteOption = plugin.settings.deleteFileOption; let fileToDelete = plugin.app.vault.getAbstractFileByPath(file.path); if (!fileToDelete) return; if (deleteOption === 'permanent') { plugin.app.vault.delete(fileToDelete, true); } else if (deleteOption === 'system-trash') { plugin.app.vault.trash(fileToDelete, true); } else if (deleteOption === 'trash') { plugin.app.vault.trash(fileToDelete, false); } }); confirmationModal.open(); }); }); // Open in a New Pane fileMenu.addItem((menuItem) => { menuItem.setIcon('go-to-file'); menuItem.setTitle('Open in a new tab'); menuItem.onClick((ev) => { openFileInNewTab(plugin.app, file); }); }); // Open in a New Pane fileMenu.addItem((menuItem) => { menuItem.setIcon('go-to-file'); menuItem.setTitle('Open to right'); menuItem.onClick((ev) => { openFileInNewTabGroup(plugin.app, file); }); }); // Make a Copy Item fileMenu.addItem((menuItem) => { menuItem.setTitle('Make a copy'); menuItem.setIcon('documents'); menuItem.onClick((ev) => { let fileToCopy = plugin.app.vault.getAbstractFileByPath(file.path); if (fileToCopy) { plugin.app.vault.copy(fileToCopy, `${file.parent.path}/${file.basename} 1.${file.extension}`); } }); }); // Move Item if (!internalPluginLoaded('file-explorer', plugin.app)) { fileMenu.addItem((menuItem) => { menuItem.setTitle('Move file to...'); menuItem.setIcon('paper-plane'); menuItem.onClick((ev) => { let fileMoveSuggester = new MoveSuggestionModal(plugin.app, file); fileMoveSuggester.open(); }); }); } // Trigger plugin.app.workspace.trigger('file-menu', fileMenu, fileToTrigger, 'file-explorer'); if (isMouseEvent(e)) { fileMenu.showAtPosition({ x: e.pageX, y: e.pageY }); } else { // @ts-ignore fileMenu.showAtPosition({ x: e.nativeEvent.locationX, y: e.nativeEvent.locationY }); } return false; }; var h=Object.defineProperty;var u=(n,t,e)=>t in n?h(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e;var c=(n,t,e)=>(u(n,typeof t!="symbol"?t+"":t,e),e);const p=(n,t)=>typeof getComputedStyle<"u"?getComputedStyle(n,null).getPropertyValue(t):n.style.getPropertyValue(t),y=n=>p(n,"overflow")+p(n,"overflow-y")+p(n,"overflow-x"),w=n=>{if(!(n instanceof HTMLElement))return window;let t=n;for(;t&&!(t===document.body||t===document.documentElement||!t.parentNode);){if(/(scroll|auto)/.test(y(t)))return t;t=t.parentNode;}return window;};class g extends reactExports.Component{constructor(e){super(e);c(this,"elementObserver");c(this,"wrapper");c(this,"lazyLoadHandler",e=>{var o,i;const{onContentVisible:s}=this.props,[r]=e,{isIntersecting:l}=r;if(l){this.setState({visible:!0},()=>{s&&s();});const a=(o=this.wrapper)==null?void 0:o.current;a&&a instanceof HTMLElement&&((i=this.elementObserver)==null||i.unobserve(a));}});this.elementObserver=null,this.wrapper=/*#__PURE__*/React.createRef(),this.state={visible:!1};}componentDidMount(){var o;this.getEventNode();const{offset:e,threshold:s}=this.props,r={rootMargin:typeof e=="number"?`${e}px`:e||"0px",threshold:s||0};this.elementObserver=new IntersectionObserver(this.lazyLoadHandler,r);const l=(o=this.wrapper)==null?void 0:o.current;l instanceof HTMLElement&&this.elementObserver.observe(l);}shouldComponentUpdate(e,s){return s.visible;}componentWillUnmount(){var s,r;const e=(s=this.wrapper)==null?void 0:s.current;e&&e instanceof HTMLElement&&((r=this.elementObserver)==null||r.unobserve(e));}getEventNode(){var e;return w((e=this.wrapper)==null?void 0:e.current);}render(){const{children:e,className:s,height:r,width:l,elementType:o}=this.props,{visible:i}=this.state,a={height:r,width:l},d=`LazyLoad${i?" is-visible":""}${s?` ${s}`:""}`;return/*#__PURE__*/reactExports.createElement(o||"div",{className:d,style:a,ref:this.wrapper},i&&reactExports.Children.only(e));}}c(g,"defaultProps",{elementType:"div",className:"",offset:0,threshold:0,width:null,onContentVisible:null,height:null}); function FileComponent(props) { let searchInput = React.useRef(null); const plugin = props.plugin; // States Coming From Main Component const [_view, setView] = Recoil_index_22(view); const [ozFileList$1, setOzFileList] = Recoil_index_22(ozFileList); const [ozPinnedFiles] = Recoil_index_22(ozPinnedFileList); const [activeFolderPath$1, setActiveFolderPath] = Recoil_index_22(activeFolderPath); const [excludedExtensions$1] = Recoil_index_22(excludedExtensions); const [excludedFolders$1] = Recoil_index_22(excludedFolders); const [showSubFolders$1, setShowSubFolders] = Recoil_index_22(showSubFolders); const [focusedFolder$1, _setFocusedFolder] = Recoil_index_22(focusedFolder); // Local States const [highlight, setHighlight] = reactExports.useState(false); const [searchPhrase, setSearchPhrase] = reactExports.useState(''); const [searchBoxVisible, setSearchBoxVisible] = reactExports.useState(false); const [treeHeader, setTreeHeader] = reactExports.useState(getFolderName(activeFolderPath$1, plugin.app)); // Force Update const forceUpdate = useForceUpdate(); // Folder Name Update once Active Folder Path Change reactExports.useEffect(() => setTreeHeader(getFolderName(activeFolderPath$1, plugin.app)), [activeFolderPath$1]); // File List Update once showSubFolders change reactExports.useEffect(() => { setOzFileList(getFilesUnderPath({ path: activeFolderPath$1, plugin: plugin, excludedExtensions: excludedExtensions$1, excludedFolders: excludedFolders$1, })); }, [showSubFolders$1, excludedExtensions$1, excludedFolders$1]); // To focus on Search box if visible set reactExports.useEffect(() => { if (searchBoxVisible) searchInput.current.focus(); }, [searchBoxVisible]); const filesToList = reactExports.useMemo(() => sortedFiles({ fileList: ozFileList$1, plugin: plugin, ozPinnedFiles: ozPinnedFiles, }), [excludedFolders$1, excludedExtensions$1, ozPinnedFiles, ozFileList$1, plugin.settings.sortFilesBy, plugin.settings.sortReverse]); // Go Back Button - Sets Main Component View to Folder const handleGoBack = (e) => { setView('folder'); setActiveFolderPath(''); }; // Toggle Search Box Visibility State const toggleSearchBox = () => { setSearchPhrase(''); setSearchBoxVisible(!searchBoxVisible); setOzFileList(getFilesUnderPath({ path: activeFolderPath$1, plugin: plugin, excludedExtensions: excludedExtensions$1, excludedFolders: excludedFolders$1, })); }; const toggleShowSubFolders = () => __awaiter(this, void 0, void 0, function* () { plugin.settings.showFilesFromSubFolders = !showSubFolders$1; yield plugin.saveSettings(); setShowSubFolders(!showSubFolders$1); }); const topIconSize = 19; return (React.createElement(React.Fragment, null, React.createElement(Dropzone$1, { onDrop: (files) => handleOnDropFiles({ files, activeFolderPath: activeFolderPath$1, plugin, }), noClick: true, onDragEnter: () => setHighlight(true), onDragLeave: () => setHighlight(false), onDropAccepted: () => setHighlight(false), onDropRejected: () => setHighlight(false) }, ({ getRootProps, getInputProps }) => (React.createElement("div", Object.assign({}, getRootProps(), { className: highlight ? 'drag-entered' : '', style: { width: '100%', height: '100%', position: 'relative' } }), React.createElement("input", Object.assign({}, getInputProps())), React.createElement("div", { className: "oz-explorer-container" }, React.createElement("div", { className: `oz-file-tree-header-wrapper${plugin.settings.fixedHeaderInFileList ? ' file-tree-header-fixed' : ''}` }, React.createElement("div", { className: "oz-flex-container" }, React.createElement("div", { className: "oz-nav-action-button", style: { marginLeft: '0px' } }, ['Horizontal', 'Vertical'].includes(plugin.settings.evernoteView) ? (React.createElement(IoIosCloseCircleOutline, { onClick: (e) => handleGoBack(), size: topIconSize, "aria-label": "Close File Pane" })) : (React.createElement(IoIosArrowBack, { onClick: (e) => handleGoBack(), size: topIconSize, "aria-label": "Go Back to Folder View" }))), React.createElement("div", { className: "oz-nav-buttons-right-block" }, plugin.settings.revealActiveFileButton && (React.createElement("div", { className: "oz-nav-action-button" }, React.createElement(BiCurrentLocation, { onClick: () => handleRevealActiveFileButton({ plugin }), size: topIconSize, "aria-label": "Reveal Active File" }))), plugin.settings.showFilesFromSubFoldersButton && (React.createElement("div", { className: "oz-nav-action-button" }, showSubFolders$1 ? (React.createElement(IoIosEyeOff, { onClick: toggleShowSubFolders, size: topIconSize, "aria-label": "Hide Files from Sub-Folders" })) : (React.createElement(IoIosEye, { onClick: toggleShowSubFolders, size: topIconSize, "aria-label": "Show Files from Sub-Folders" })))), plugin.settings.searchFunction && (React.createElement("div", { className: "oz-nav-action-button" }, React.createElement(IoIosSearch, { onClick: toggleSearchBox, size: topIconSize, "aria-label": "Search File by Name or Tag" }))), React.createElement("div", { className: "oz-nav-action-button" }, React.createElement(CgSortAz, { size: topIconSize + 2, onClick: (e) => { sortFileListClickHandle({ e, plugin, forceUpdate }); }, "aria-label": "Sorting Options" })), React.createElement("div", { className: "oz-nav-action-button" }, React.createElement(IoIosAddCircle, { onClick: (e) => createNewFile(e, activeFolderPath$1, plugin), size: topIconSize, "aria-label": "Create a Note" })))), searchBoxVisible && (React.createElement("div", { className: "oz-input-container" }, React.createElement("input", { type: "search", placeholder: "Search...", ref: searchInput, value: searchPhrase, onChange: (e) => { handleSearch({ e, plugin, activeFolderPath: activeFolderPath$1, setSearchPhrase, setTreeHeader, setOzFileList, excludedExtensions: excludedExtensions$1, excludedFolders: excludedFolders$1, focusedFolder: focusedFolder$1, }); }, onKeyDown: (e) => { if (e.key === 'Escape') { e.preventDefault(); toggleSearchBox(); } } }))), React.createElement("div", { className: "oz-file-tree-header" }, treeHeader)), React.createElement("div", { className: `oz-file-tree-files${plugin.settings.fixedHeaderInFileList ? searchBoxVisible ? ' file-tree-files-fixed-with-search' : ' file-tree-files-fixed' : ''}` }, filesToList.map((file, index) => { return (React.createElement(g, { height: 22, key: index }, React.createElement(NavFile, { file: file, plugin: plugin }))); })))))))); } /* ----------- SINGLE NAVFILE ELEMENT ----------- */ const NavFile = (props) => { const { file, plugin } = props; const [ozPinnedFiles, setOzPinnedFiles] = Recoil_index_22(ozPinnedFileList); const [activeOzFile, setActiveOzFile] = Recoil_index_22(activeOZFile); const [hoverActive, setHoverActive] = reactExports.useState(false); const longPressEvents = useLongPress((e) => { triggerContextMenu({ file, e, plugin, ozPinnedFiles, setOzPinnedFiles, }); }, 500); reactExports.useEffect(() => { const handleKeyDownEvent = (e) => { if (e.key === 'Control' || e.key === 'Meta') { let el = document.querySelector(`.oz-nav-file-title[data-path="${file.path}"]`); if (el) plugin.app.workspace.trigger('link-hover', {}, el, file.path, file.path); } }; if (hoverActive && plugin.settings.filePreviewOnHover) { document.addEventListener('keydown', handleKeyDownEvent); return () => { document.removeEventListener('keydown', handleKeyDownEvent); }; } }, [hoverActive]); const FileIcon = reactExports.useMemo(() => getFileIcon({ file, }), [plugin.settings.iconBeforeFileName, file]); const fileDisplayName = reactExports.useMemo(() => { return plugin.settings.showFileNameAsFullPath ? getFileNameAndExtension(file.path).fileName : file.basename; }, [plugin.settings.showFileNameAsFullPath, file.path]); return (React.createElement("div", Object.assign({ className: 'oz-nav-file' + (activeOzFile && activeOzFile.path === file.path ? ' is-active' : ''), key: file.path, draggable: true, onDragStart: (e) => dragStarted({ e, file, plugin, }), onClick: (e) => openFile({ e, file, plugin, setActiveOzFile, }), onAuxClick: (e) => onAuxClick({ e, plugin, file }), onContextMenu: (e) => triggerContextMenu({ e, file, plugin, ozPinnedFiles, setOzPinnedFiles, }), onMouseEnter: (e) => mouseEnteredOnFile({ e, file, plugin, setHoverActive, }), onMouseLeave: (e) => mouseLeftFile({ e, file, setHoverActive }) }, longPressEvents), React.createElement("div", { className: "oz-nav-file-title", "data-path": file.path }, React.createElement("div", { className: "oz-nav-file-title-content" }, plugin.settings.iconBeforeFileName && React.createElement(FileIcon, { className: "oz-nav-file-icon", size: 15 }), fileDisplayName), ozPinnedFiles.some((f) => f.path === file.path) && React.createElement(FaThumbtack, { className: "oz-nav-file-tag", size: 14 }), file.extension !== 'md' && React.createElement("span", { className: "oz-nav-file-tag" }, file.extension)))); }; function Tree(props) { // Global States const [openFolders$1, setOpenFolders] = Recoil_index_22(openFolders); const [folderFileCountMap$1] = Recoil_index_22(folderFileCountMap); const [activeFolderPath$1] = Recoil_index_22(activeFolderPath); const longPressEvents = useLongPress((e) => { props.onContextMenu(e); }, 500); // Local States const [open, setOpen] = reactExports.useState(props.open); const [highlight, setHightlight] = reactExports.useState(false); const isFolderActive = props.folder.path === activeFolderPath$1; // --> For state update from outside of the component reactExports.useEffect(() => setOpen(props.open), [props.open]); // --> Icon to be toggled between min(-) and plus(+) Each click sets openFolders Main Component state to save in settings const toggle = () => { if (props.children) { // Set State in Main Component for Keeping Folders Open if (!open) { setOpenFolders([...openFolders$1, props.folder.path]); } else { const newOpenFolders = openFolders$1.filter((openFolder) => props.folder.path !== openFolder); setOpenFolders(newOpenFolders); } // Set State Open for the Folder setOpen(!open); } }; // --> Function After an External File Dropped into Folder Name const onDrop = (files) => { files.map((file) => __awaiter(this, void 0, void 0, function* () { file.arrayBuffer().then((arrayBuffer) => { props.plugin.app.vault.adapter.writeBinary(props.folder.path + '/' + file.name, arrayBuffer); }); })); }; // --> Click Events const folderNameClickEvent = (ev) => { if (props.plugin.settings.folderNote && ev.shiftKey) { const fileFullPath = `${props.folder.path}/${props.folder.name}.md`; props.plugin.app.vault.getAbstractFileByPath(fileFullPath); props.plugin.app.workspace.openLinkText(fileFullPath, '/', false); } else { props.onClick(); } }; const folderContextMenuEvent = () => props.onContextMenu(); const folderNameDoubleClickEvent = (ev) => { setOpen(true); props.onDoubleClick(); }; // --> Icon const Icon = reactExports.useMemo(() => getFolderIcon(props.plugin, props.children, open), [open, props.children, props.plugin.settings.folderIcon]); // --> Folder Count Map const folderCount = folderFileCountMap$1[props.folder.path]; // --> Drag and Drop Actions const dropFileOrFolder = (e) => { let data = e.dataTransfer.getData('application/json'); if (data !== '') { let dataJson = JSON.parse(data); // File Drop if (dataJson['filePath']) { const filePath = dataJson.filePath; // check if file exists let file = props.plugin.app.vault.getAbstractFileByPath(filePath); if (file) { props.plugin.app.vault.rename(file, `${props.folder.path}/${file.name}`); } else { new obsidian.Notice('Couldnt find the file'); } } // Folder Drop else if (dataJson['folderPath']) { const folderPath = dataJson.folderPath; let folder = props.plugin.app.vault.getAbstractFileByPath(folderPath); if (folder) { if (!props.folder.path.startsWith(folder.path)) { props.plugin.app.vault.rename(folder, `${props.folder.path}/${folder.name}`); } else { new obsidian.Notice('You cant move folder under its child'); } } else { new obsidian.Notice('Couldnt find the folder'); } } } setHightlight(false); e.dataTransfer.clearData(); }; const onFolderDragStart = (e, folder) => { e.dataTransfer.setData('application/json', JSON.stringify({ folderPath: folder.path })); let dragManager = props.plugin.app.dragManager; const dragData = dragManager.dragFile(e.nativeEvent, folder); dragManager.onDragStart(e.nativeEvent, dragData); }; return (React.createElement(Dropzone$1, { onDrop: onDrop, noClick: true, onDragEnter: () => setHightlight(true), onDragLeave: () => setHightlight(false), onDropAccepted: () => setHightlight(false), onDropRejected: () => setHightlight(false) }, ({ getRootProps, getInputProps }) => (React.createElement(React.Fragment, null, React.createElement("div", { style: Object.assign({}, props.style), className: "treeview", draggable: true, onDragStart: (e) => onFolderDragStart(e, props.folder), onDrop: (e) => dropFileOrFolder(e), onDragOver: () => setHightlight(true), onDragLeave: () => setHightlight(false) }, React.createElement("div", Object.assign({}, getRootProps({ className: 'dropzone' }), { className: 'oz-folder-element' + (highlight ? ' drag-entered' : ''), "data-path": props.folder.path }), React.createElement("input", Object.assign({}, getInputProps())), React.createElement("div", { className: "oz-folder-line" }, React.createElement("div", { className: "oz-icon-div" }, React.createElement(Icon, { className: "oz-folder-toggle", style: { opacity: props.children ? 1 : 0.3 }, onClick: toggle })), React.createElement("div", Object.assign({ className: "oz-folder-block", onClick: folderNameClickEvent, onDoubleClick: folderNameDoubleClickEvent, onContextMenu: folderContextMenuEvent }, longPressEvents), React.createElement("div", { className: "oz-folder-type", style: { marginRight: props.type ? 10 : 0 } }, props.type), React.createElement("div", { className: `oz-folder-name ${isFolderActive ? 'is-folder-active' : ''}${props.isRootFolder ? ' is-root-folder' : ''}` }, props.content, ' ', props.plugin.settings.folderNote && props.folder.children.some((f) => f.name === `${props.folder.name}.md`) ? (React.createElement(IoMdArrowDropright, { size: 10, className: "oz-folder-note-icon" })) : ('')), props.plugin.settings.folderCount && (React.createElement("div", { className: "oz-folder-count" }, React.createElement("span", { className: "oz-nav-file-tag" }, folderCount ? (open ? folderCount.open : folderCount.closed) : 0))))))), props.children && (React.createElement("div", { className: "oz-folder-contents", style: { height: open ? 'auto' : 0, opacity: open ? 1 : 0, display: open ? 'inherit' : 'none', } }, props.children)))))); } const ConditionalRootFolderWrapper = ({ condition, wrapper, children }) => condition ? wrapper(children) : children; function NestedFolders(props) { const plugin = props.plugin; const app = plugin.app; let rootFolder = app.vault.getRoot(); // Global States const [openFolders$1] = Recoil_index_22(openFolders); const [activeFolderPath$1, setActiveFolderPath] = Recoil_index_22(activeFolderPath); const [excludedFolders$1, setExcludedFolders] = Recoil_index_22(excludedFolders); const [focusedFolder$1, setFocusedFolder] = Recoil_index_22(focusedFolder); const [folderFileCountMap$1] = Recoil_index_22(folderFileCountMap); const [_view, setView] = Recoil_index_22(view); const handleFolderNameClick = (folderPath) => setActiveFolderPath(folderPath); const focusOnFolder = (folder) => { setFocusedFolder(folder); setActiveFolderPath(folder.path); }; const getSortedFolderTree = (folderTree) => { let newTree = folderTree; newTree = newTree.sort((a, b) => { if (plugin.settings.sortFoldersBy === 'name') { return a.folder.name.localeCompare(b.folder.name, 'en', { numeric: true }); } else if (plugin.settings.sortFoldersBy === 'item-number') { let aCount = folderFileCountMap$1[a.folder.path] ? folderFileCountMap$1[a.folder.path].closed : 0; let bCount = folderFileCountMap$1[b.folder.path] ? folderFileCountMap$1[b.folder.path].closed : 0; return bCount - aCount; } }); return newTree; }; const handleFolderContextMenu = (params) => { let { event, folder } = params; // Event Undefined Correction let e = event; if (event === undefined) e = window.event; // Menu Items const folderMenu = new obsidian.Menu(); // Focus Items if (hasChildFolder(folder)) { folderMenu.addItem((menuItem) => { menuItem .setTitle('Focus on Folder') .setIcon('zoomInIcon') .onClick(() => focusOnFolder(folder)); }); } if (!focusedFolder$1.isRoot()) { folderMenu.addItem((menuItem) => { menuItem .setTitle('Focus Back to Root') .setIcon('zoomOutIcon') .onClick(() => focusOnFolder(rootFolder)); }); } // CRUD Items folderMenu.addItem((menuItem) => { menuItem .setTitle('New Folder') .setIcon('folder') .onClick((ev) => { let vaultChangeModal = new VaultChangeModal(plugin, folder, 'create folder'); vaultChangeModal.open(); }); }); folderMenu.addItem((menuItem) => { menuItem .setTitle('Delete') .setIcon('trash') .onClick((ev) => { let confirmationModal = new ConfirmationModal(plugin, `Are you sure you want to delete folder "${folder.name}" and all folders & files under it?`, () => { let deleteOption = plugin.settings.deleteFileOption; if (deleteOption === 'permanent') { plugin.app.vault.delete(folder, true); } else if (deleteOption === 'system-trash') { plugin.app.vault.trash(folder, true); } else if (deleteOption === 'trash') { plugin.app.vault.trash(folder, false); } if (activeFolderPath$1 === folder.path) { setActiveFolderPath(''); setView('folder'); } }); confirmationModal.open(); }); }); folderMenu.addItem((menuItem) => { menuItem .setTitle('Rename') .setIcon('pencil') .onClick((ev) => { let vaultChangeModal = new VaultChangeModal(plugin, folder, 'rename'); vaultChangeModal.open(); }); }); folderMenu.addItem((menuItem) => { menuItem .setTitle('New File') .setIcon('document') .onClick((ev) => { createNewFile(ev, folder.path, plugin); }); }); // Move Item if (!internalPluginLoaded('file-explorer', app)) { folderMenu.addItem((menuItem) => { menuItem .setTitle('Move folder to...') .setIcon('paper-plane') .onClick((ev) => { let folderMoveModal = new MoveSuggestionModal(app, folder); folderMoveModal.open(); }); }); } folderMenu.addItem((menuItem) => { menuItem .setTitle('Add to Excluded Folders') .setIcon('switch') .onClick((ev) => { setExcludedFolders([...excludedFolders$1, folder.path]); }); }); // Folder Note Open & Create & Delete (If folder note loaded, avoid duplicate create, delete buttons) const folderNotePath = `${folder.path}/${folder.name}.md`; let folderNoteExists = folder.children.some((f) => `${folder.name}.md` === f.name); if (folderNoteExists) { folderMenu.addItem((menuItem) => { menuItem .setTitle('Open Folder Note') .setIcon('go-to-file') .onClick((ev) => { plugin.app.workspace.activeLeaf.setViewState({ type: 'markdown', state: { file: folderNotePath }, }); }); }); } if (!pluginIsLoaded(plugin.app, 'folder-note-core')) { // Delete Folder Note Button if (folderNoteExists) { folderMenu.addItem((menuItem) => { menuItem .setTitle('Delete Folder Note') .setIcon('trash') .onClick((ev) => { const folderNoteFile = plugin.app.vault.getAbstractFileByPath(folderNotePath); if (folderNoteFile) plugin.app.vault.delete(folderNoteFile, true); }); }); } // Create Folder Note Button else { folderMenu.addItem((menuItem) => { menuItem .setTitle('Create Folder Note') .setIcon('create-new') .onClick((ev) => __awaiter(this, void 0, void 0, function* () { createNewMarkdownFile(plugin, folder, folder.name, `# ${folder.name}`); })); }); } } // Trigger app.workspace.trigger('file-menu', folderMenu, folder, 'file-explorer'); if (e instanceof MouseEvent) { folderMenu.showAtPosition({ x: e.pageX, y: e.pageY }); } else { folderMenu.showAtPosition({ x: 0, y: 0 }); } return false; }; if (!props.folderTree.children) return null; let sortedFolderTree = reactExports.useMemo(() => getSortedFolderTree(props.folderTree.children), [props.folderTree.children, excludedFolders$1, plugin.settings.sortFoldersBy]); return (React.createElement(React.Fragment, null, Array.isArray(props.folderTree.children) && sortedFolderTree.map((child) => { return (React.createElement(React.Fragment, { key: child.folder.path }, child.children.length > 0 ? (React.createElement(Tree, { plugin: plugin, content: child.folder.name, open: openFolders$1.contains(child.folder.path), onClick: () => handleFolderNameClick(child.folder.path), onDoubleClick: () => focusOnFolder(child.folder), onContextMenu: (e) => handleFolderContextMenu({ event: e, folder: child.folder, }), folder: child.folder }, React.createElement(NestedFolders, { plugin: plugin, folderTree: child }))) : (React.createElement(Tree, { plugin: plugin, content: child.folder.name, onClick: () => handleFolderNameClick(child.folder.path), onDoubleClick: () => focusOnFolder(child.folder), onContextMenu: (e) => handleFolderContextMenu({ event: e, folder: child.folder, }), folder: child.folder })))); }))); } function MainFolder(props) { const treeStyles = { color: 'var(--text-muted)', fill: '#c16ff7', width: '100%' }; const plugin = props.plugin; const app = plugin.app; const rootFolder = app.vault.getRoot(); // Global States const [_activeFolderPath, setActiveFolderPath] = Recoil_index_22(activeFolderPath); const [folderTree$1] = Recoil_index_22(folderTree); const [focusedFolder$1, setFocusedFolder] = Recoil_index_22(focusedFolder); const [_openFolders, setOpenFolders] = Recoil_index_22(openFolders); // Force Update const forceUpdate = useForceUpdate(); const focusOnFolder = (folder) => { setFocusedFolder(folder); setActiveFolderPath(folder.path); }; const createFolder = (underFolder) => { let vaultChangeModal = new VaultChangeModal(plugin, underFolder, 'create folder'); vaultChangeModal.open(); }; const handleRootFolderContextMenu = (event, folder) => { // Event Undefined Correction let e = event; if (event === undefined) e = window.event; // Menu Items const folderMenu = new obsidian.Menu(); folderMenu.addItem((menuItem) => { menuItem .setTitle('New Folder') .setIcon('folder') .onClick((ev) => createFolder(folder)); }); if (!folder.isRoot()) { folderMenu.addItem((menuItem) => { menuItem .setTitle('Focus Back to Root') .setIcon('zoomOutDoubleIcon') .onClick(() => focusOnFolder(rootFolder)); }); } if (folder.parent && !folder.parent.isRoot() && folder.parent !== focusedFolder$1) { folderMenu.addItem((menuItem) => { menuItem .setTitle('Focus to Parent Folder') .setIcon('zoomOutIcon') .onClick(() => focusOnFolder(folder.parent)); }); } // Trigger app.workspace.trigger('root-folder-menu', folderMenu, folder); folderMenu.showAtPosition({ x: e.pageX, y: e.pageY }); return false; }; // --> Collapse, Expland Button Functions const collapseAllFolders = () => setOpenFolders([]); const explandAllFolders = () => { let newOpenFolders = []; newOpenFolders.push(folderTree$1.folder.path); const recursiveFx = (folderTreeChildren) => { for (let folderTreeChild of folderTreeChildren) { newOpenFolders.push(folderTreeChild.folder.path); if (folderTreeChild.children.length > 0) { recursiveFx(folderTreeChild.children); } } }; recursiveFx(folderTree$1.children); setOpenFolders(newOpenFolders); }; const triggerFolderSortOptions = (e) => { const sortMenu = new obsidian.Menu(); const changeSortSettingTo = (newValue) => { plugin.settings.sortFoldersBy = newValue; plugin.saveSettings(); forceUpdate(); }; sortMenu.addItem((menuItem) => { menuItem.setTitle('Folder Name (A to Z)'); menuItem.onClick((ev) => { changeSortSettingTo('name'); }); }); if (plugin.settings.folderCount) { sortMenu.addItem((menuItem) => { menuItem.setTitle('Item Numbers (Bigger to Smaller)'); menuItem.onClick((ev) => { changeSortSettingTo('item-number'); }); }); } // Trigger plugin.app.workspace.trigger('sort-menu', sortMenu); sortMenu.showAtPosition({ x: e.pageX, y: e.pageY }); return false; }; const handleFolderNameDoubleClick = (folder) => { if (!folder.isRoot()) focusOnFolder(folder.parent); }; let folderActionItemSize = 22; return (React.createElement("div", { className: "oz-folders-tree-wrapper" }, React.createElement("div", { className: "oz-folders-action-items file-tree-header-fixed" }, React.createElement(MdOutlineCreateNewFolder, { className: "oz-nav-action-button", size: folderActionItemSize, onClick: (e) => createFolder(plugin.app.vault.getRoot()), "aria-label": "Create Folder" }), React.createElement(CgSortAz, { className: "oz-nav-action-button", size: folderActionItemSize, onClick: triggerFolderSortOptions, "aria-label": "Sorting Options" }), React.createElement(CgChevronDoubleUp, { className: "oz-nav-action-button", size: folderActionItemSize, onClick: collapseAllFolders, "aria-label": "Collapse Folders" }), React.createElement(CgChevronDoubleDown, { className: "oz-nav-action-button", size: folderActionItemSize, onClick: explandAllFolders, "aria-label": "Expand Folders" })), React.createElement(ConditionalRootFolderWrapper, { condition: (focusedFolder$1 && !focusedFolder$1.isRoot()) || (focusedFolder$1 && focusedFolder$1.isRoot && plugin.settings.showRootFolder), wrapper: (children) => { return (React.createElement(Tree, { plugin: plugin, content: focusedFolder$1.isRoot() ? plugin.app.vault.getName() : focusedFolder$1.name, open: true, isRootFolder: focusedFolder$1.isRoot(), style: treeStyles, onClick: () => setActiveFolderPath(focusedFolder$1.path), onDoubleClick: () => handleFolderNameDoubleClick(focusedFolder$1), folder: focusedFolder$1, onContextMenu: (e) => handleRootFolderContextMenu(e, focusedFolder$1) }, children)); } }, folderTree$1 && React.createElement(NestedFolders, { plugin: plugin, folderTree: folderTree$1 })))); } const SingleViewVertical = (props) => { let { plugin } = props; const [dividerOnMove, setDividerOnMove] = reactExports.useState(false); const [folderPaneHeight, setFolderPaneHeight] = reactExports.useState(null); const [clientY, setClientY] = reactExports.useState(null); let folderPaneRef = reactExports.useRef(); let dividerRef = reactExports.useRef(); let heightSetting = localStorage.getItem(plugin.keys.customHeightKey); reactExports.useEffect(() => { if (folderPaneHeight) { localStorage.setItem(plugin.keys.customHeightKey, folderPaneHeight.toString()); } }, [folderPaneHeight]); function touchMouseStart(e) { if (e.type !== 'drag' && e.target.id !== 'file-tree-divider') return; e.preventDefault(); setDividerOnMove(true); let height = dividerRef.current.offsetTop - folderPaneRef.current.offsetTop; setFolderPaneHeight(height); setClientY(e.nativeEvent.clientY); } function touchMouseMove(e) { if (!dividerOnMove) return; e.preventDefault(); setFolderPaneHeight(folderPaneHeight + (e.nativeEvent.clientY - clientY)); setClientY(e.nativeEvent.clientY); } function touchMouseEnd(e) { if (!dividerOnMove) return; e.preventDefault(); setDividerOnMove(false); setClientY(e.nativeEvent.clientY); } return ( // Register Move & End Events for All File Tree Leaf React.createElement("div", { className: "file-tree-container", onMouseMove: (e) => touchMouseMove(e), onMouseUp: (e) => touchMouseEnd(e) }, React.createElement("div", { className: "oz-folder-pane", ref: folderPaneRef, style: { height: folderPaneHeight ? `${folderPaneHeight}px` : heightSetting && heightSetting !== '' ? `${heightSetting}px` : '50%' } }, React.createElement(MainFolder, { plugin: plugin })), React.createElement("div", { id: "file-tree-divider", ref: dividerRef, onClick: (e) => e.preventDefault(), onMouseDown: (e) => touchMouseStart(e), className: dividerOnMove ? 'active-divider' : '' }), React.createElement("div", { className: "oz-file-list-pane" }, React.createElement(FileComponent, { plugin: plugin })))); }; const SingleViewHorizontal = (props) => { let { plugin } = props; const [dividerOnMove, setDividerOnMove] = reactExports.useState(false); const [folderPaneWidth, setFolderPaneWidth] = reactExports.useState(null); const [clientX, setClientX] = reactExports.useState(null); let folderPaneRef = reactExports.useRef(); let dividerRef = reactExports.useRef(); let widthSetting = localStorage.getItem(plugin.keys.customWidthKey); reactExports.useEffect(() => { if (folderPaneWidth) { localStorage.setItem(plugin.keys.customWidthKey, folderPaneWidth.toString()); } }, [folderPaneWidth]); function touchMouseStart(e) { if (e.type !== 'drag' && e.target.id !== 'file-tree-divider-horizontal') return; e.preventDefault(); setDividerOnMove(true); let width = dividerRef.current.offsetLeft - folderPaneRef.current.offsetLeft; setFolderPaneWidth(width); setClientX(e.nativeEvent.clientX); } function touchMouseMove(e) { if (!dividerOnMove) return; e.preventDefault(); setFolderPaneWidth(folderPaneWidth + (e.nativeEvent.clientX - clientX)); setClientX(e.nativeEvent.clientX); } function touchMouseEnd(e) { if (!dividerOnMove) return; e.preventDefault(); setDividerOnMove(false); setClientX(e.nativeEvent.clientX); } return ( // Register Move & End Events for All File Tree Leaf React.createElement("div", { className: "file-tree-container-horizontal", onMouseMove: (e) => touchMouseMove(e), onMouseUp: (e) => touchMouseEnd(e) }, React.createElement("div", { className: "oz-folder-pane-horizontal", ref: folderPaneRef, style: { width: folderPaneWidth ? `${folderPaneWidth}px` : widthSetting && widthSetting !== '' ? `${widthSetting}px` : '50%' } }, React.createElement(MainFolder, { plugin: plugin })), React.createElement("div", { id: "file-tree-divider-horizontal", ref: dividerRef, onClick: (e) => e.preventDefault(), onMouseDown: (e) => touchMouseStart(e), className: dividerOnMove ? 'active-divider' : '' }), React.createElement("div", { className: "oz-file-list-pane-horizontal" }, React.createElement(FileComponent, { plugin: plugin })))); }; function MainTreeComponent(props) { // --> Main Variables const { plugin } = props; // --> Force Update Hook const forceUpdate = useForceUpdate(); // --> Plugin States const [view$1, setView] = Recoil_index_22(view); const [activeFolderPath$1, setActiveFolderPath] = Recoil_index_22(activeFolderPath); const [ozFileList$1, setOzFileList] = Recoil_index_22(ozFileList); const [ozPinnedFiles, setOzPinnedFiles] = Recoil_index_22(ozPinnedFileList); const [openFolders$1, setOpenFolders] = Recoil_index_22(openFolders); const [_folderTree, setFolderTree] = Recoil_index_22(folderTree); const [excludedFolders$1, setExcludedFolders] = Recoil_index_22(excludedFolders); const [_folderFileCountMap, setFolderFileCountMap] = Recoil_index_22(folderFileCountMap); const [excludedExtensions$1, setExcludedExtensions] = Recoil_index_22(excludedExtensions); const [_showSubFolders, setShowSubFolders] = Recoil_index_22(showSubFolders); const [focusedFolder$1, setFocusedFolder] = Recoil_index_22(focusedFolder); const [activeOZFile$1, setActiveOzFile] = Recoil_index_22(activeOZFile); const setNewFileList = (folderPath) => { let filesPath = folderPath ? folderPath : activeFolderPath$1; setOzFileList(getFilesUnderPath({ path: filesPath, plugin: plugin, excludedExtensions: excludedExtensions$1, excludedFolders: excludedFolders$1, })); }; const setInitialActiveFolderPath = () => { if (['Horizontal', 'Vertical'].includes(plugin.settings.evernoteView)) { let previousActiveFolder = localStorage.getItem(plugin.keys.activeFolderPathKey); if (previousActiveFolder) { let folder = plugin.app.vault.getAbstractFileByPath(previousActiveFolder); if (folder && folder instanceof obsidian.TFolder) { setActiveFolderPath(folder.path); } } } }; // --> Create Custom Event Handlers reactExports.useEffect(() => { window.addEventListener(eventTypes.vaultChange, vaultChangeEvent); window.addEventListener(eventTypes.activeFileChange, changeActiveFile); window.addEventListener(eventTypes.refreshView, forceUpdate); window.addEventListener(eventTypes.revealFile, handleRevealFileEvent); window.addEventListener(eventTypes.revealFolder, handleRevealFolderEvent); window.addEventListener(eventTypes.createNewNote, handleCreateNewNoteEvent); return () => { window.removeEventListener(eventTypes.vaultChange, vaultChangeEvent); window.removeEventListener(eventTypes.activeFileChange, changeActiveFile); window.removeEventListener(eventTypes.refreshView, forceUpdate); window.removeEventListener(eventTypes.revealFile, handleRevealFileEvent); window.removeEventListener(eventTypes.revealFolder, handleRevealFolderEvent); window.removeEventListener(eventTypes.createNewNote, handleCreateNewNoteEvent); }; }, []); const handleCreateNewNoteEvent = () => { let currentActiveFolderPath = '/'; setActiveFolderPath((activeFolderPath) => { currentActiveFolderPath = activeFolderPath; return activeFolderPath; }); createNewFile(null, currentActiveFolderPath, plugin); }; const vaultChangeEvent = (evt) => { handleVaultChanges(evt.detail.file, evt.detail.changeType, evt.detail.oldPath); }; const changeActiveFile = (evt) => { // @ts-ignore let filePath = evt.detail.filePath; let file = plugin.app.vault.getAbstractFileByPath(filePath); if (file) setActiveOzFile(TFile2OZFile(file)); }; // Initial Load reactExports.useEffect(() => { setInitialFocusedFolder(); setExcludedFolders(getExcludedFolders()); setExcludedExtensions(getExcludedExtensions()); setOzPinnedFiles(getPinnedFilesFromSettings()); setOpenFolders(getOpenFoldersFromSettings()); setShowSubFolders(plugin.settings.showFilesFromSubFolders); setInitialActiveFolderPath(); if (plugin.settings.folderCount) setFolderFileCountMap(getFolderNoteCountMap(plugin)); }, []); // Each Focused Folder Change triggers new folder tree build reactExports.useEffect(() => { if (focusedFolder$1) { setFolderTree(createFolderTree({ startFolder: focusedFolder$1, plugin: plugin, excludedFolders: excludedFolders$1, })); localStorage.setItem(plugin.keys.focusedFolder, focusedFolder$1.path); } }, [focusedFolder$1, excludedFolders$1]); const setInitialFocusedFolder = () => { let localFocusedFolder = localStorage.getItem(plugin.keys.focusedFolder); if (localFocusedFolder) { let folder = plugin.app.vault.getAbstractFileByPath(localFocusedFolder); if (folder && folder instanceof obsidian.TFolder) { setFocusedFolder(folder); return; } } setFocusedFolder(plugin.app.vault.getRoot()); }; // State Change Handlers reactExports.useEffect(() => savePinnedFilesToSettings(), [ozPinnedFiles]); reactExports.useEffect(() => saveOpenFoldersToSettings(), [openFolders$1]); reactExports.useEffect(() => saveExcludedFoldersToSettings(), [excludedFolders$1]); // If activeFolderPath is set, it means it should go to 'file' view reactExports.useEffect(() => { if (activeFolderPath$1 !== '') { setNewFileList(activeFolderPath$1); setView('file'); } localStorage.setItem(plugin.keys.activeFolderPathKey, activeFolderPath$1); }, [activeFolderPath$1]); // Load Excluded Extensions as State function getExcludedExtensions() { let extensionsString = plugin.settings.excludedExtensions; let excludedExtensions = []; for (let extension of extensionsString.split(',')) { excludedExtensions.push(extension.trim()); } return excludedExtensions; } // Load Excluded Folders function getExcludedFolders() { let excludedString = plugin.settings.excludedFolders; let excludedFolders = []; if (excludedString) { for (let excludedFolder of excludedString.split(',')) { if (excludedFolder !== '') excludedFolders.push(excludedFolder.trim()); } } return excludedFolders; } // Load The String List and Set Open Folders State function getOpenFoldersFromSettings() { let openFolders = []; let localStorageOpenFolders = localStorage.getItem(plugin.keys.openFoldersKey); if (localStorageOpenFolders) { localStorageOpenFolders = JSON.parse(localStorageOpenFolders); for (let folder of localStorageOpenFolders) { let openFolder = plugin.app.vault.getAbstractFileByPath(folder); if (openFolder) openFolders.push(openFolder.path); } } return openFolders; } // Load The String List anad Set Pinned Files State function getPinnedFilesFromSettings() { let pinnedFiles = []; let localStoragePinnedFiles = localStorage.getItem(plugin.keys.pinnedFilesKey); if (localStoragePinnedFiles) { localStoragePinnedFiles = JSON.parse(localStoragePinnedFiles); for (let file of localStoragePinnedFiles) { let pinnedFile = plugin.app.vault.getAbstractFileByPath(file); if (pinnedFile) pinnedFiles.push(TFile2OZFile(pinnedFile)); } } return pinnedFiles; } // Get The Folders State and Save in Data as String Array function saveOpenFoldersToSettings() { let openFoldersToSave = []; for (let folder of openFolders$1) { openFoldersToSave.push(folder); } localStorage.setItem(plugin.keys.openFoldersKey, JSON.stringify(openFoldersToSave)); } // Get The Pinned Files State and Save in Data as String Array function savePinnedFilesToSettings() { let pinnedFilesToSave = []; for (let file of ozPinnedFiles) { pinnedFilesToSave.push(file.path); } localStorage.setItem(plugin.keys.pinnedFilesKey, JSON.stringify(pinnedFilesToSave)); } // Save Excluded Folders to Settings as String function saveExcludedFoldersToSettings() { plugin.settings.excludedFolders = excludedFolders$1.length > 1 ? excludedFolders$1.join(', ') : excludedFolders$1[0]; plugin.saveSettings(); } // Function for Event Handlers function handleVaultChanges(file, changeType, oldPathBeforeRename) { // Get Current States from Setters let currentActiveFolderPath = ''; setActiveFolderPath((activeFolderPath) => { currentActiveFolderPath = activeFolderPath; return activeFolderPath; }); // File Event Handlers if (file instanceof obsidian.TFile) { // Update Pinned Files if (['rename', 'delete'].contains(changeType)) { let currentOzPinnedFiles = []; setOzPinnedFiles((ozPinnedFiles) => { currentOzPinnedFiles = ozPinnedFiles; return ozPinnedFiles; }); const filteredPinnedFiles = currentOzPinnedFiles.filter((f) => f.path !== (changeType === 'rename' ? oldPathBeforeRename : file.path)); if (filteredPinnedFiles.length !== currentOzPinnedFiles.length) { setOzPinnedFiles([...filteredPinnedFiles, ...(changeType === 'rename' ? [TFile2OZFile(file)] : [])]); } } // Update current View let currentView = ''; setView((view) => { currentView = view; return view; }); if (currentView === 'file') { let currentFileList = []; setOzFileList((fileList) => { currentFileList = fileList; return fileList; }); // Evaluate changes if (changeType === 'rename' || changeType === 'modify' || changeType === 'delete') { // If the file is modified but sorting is not last-update to not component update unnecessarily, return let sortFilesBy = plugin.settings.sortFilesBy; if (changeType === 'modify') { if (!(sortFilesBy === 'last-update' || sortFilesBy === 'file-size')) { return; } } // If the file renamed or deleted or modified is in the current view, it will be updated let parentFolderPath = file.path.substring(0, file.path.lastIndexOf('/')); let fileInCurrentView = currentFileList.some((f) => { return changeType === 'rename' ? f.path === oldPathBeforeRename : f.path === file.path; }); let fileInCurrentFolder = currentActiveFolderPath === parentFolderPath || (plugin.settings.showFilesFromSubFolders && parentFolderPath.startsWith(currentActiveFolderPath)); if (fileInCurrentView) { if (changeType === 'delete') { setOzFileList(currentFileList.filter((f) => { return f.path !== file.path; })); } else if (changeType === 'rename' || (changeType === 'modify' && (sortFilesBy === 'last-update' || sortFilesBy === 'file-size'))) { // Fix for Root Folder Path if (currentActiveFolderPath === '/') currentActiveFolderPath = ''; // Set the file list setOzFileList([ ...currentFileList.filter((f) => { return changeType === 'rename' ? f.path !== oldPathBeforeRename : f.path !== file.path; }), // Include any file that roles up to the current active folder, not only the direct ones ...(file.parent.path.startsWith(currentActiveFolderPath) ? [TFile2OZFile(file)] : []), ]); // If active file is renamed, change the active file let currentActiveOZFile = null; setActiveOzFile((activeOZFile) => { currentActiveOZFile = activeOZFile; return activeOZFile; }); if (changeType === 'rename' && currentActiveOZFile && currentActiveOZFile.path === oldPathBeforeRename) { setActiveOzFile(TFile2OZFile(file)); } } } // File is no in current view but parent folder is and should be included else if (fileInCurrentFolder && !fileInCurrentView) { setOzFileList([...currentFileList, TFile2OZFile(file)]); } } else if (changeType === 'create') { let fileIsCreatedUnderActiveFolder = file.path.match(new RegExp(currentActiveFolderPath + '.*')); if (fileIsCreatedUnderActiveFolder) { // If file is not already in the list, add into view if (!currentFileList.some((f) => f.path === file.path)) { setOzFileList([...currentFileList, TFile2OZFile(file)]); } } } } } // Folder Event Handlers else if (file instanceof obsidian.TFolder) { let currentFocusedFolder = null; setFocusedFolder((focusedFolder) => { currentFocusedFolder = focusedFolder; return focusedFolder; }); setFolderTree(createFolderTree({ startFolder: currentFocusedFolder, plugin: plugin, excludedFolders: excludedFolders$1 })); // if active folder is renamed, activefolderpath needs to be refreshed if (changeType === 'rename' && oldPathBeforeRename && currentActiveFolderPath === oldPathBeforeRename) { setActiveFolderPath(file.path); } } // After Each Vault Change Folder Count Map to Be Updated if (plugin.settings.folderCount && changeType !== 'modify') { setFolderFileCountMap(getFolderNoteCountMap(plugin)); } } // ******** REVEAL ACTIVE FILE FUNCTIONS ******** // // --> During file list change, it will scroll to the active file element reactExports.useEffect(() => { if (activeOZFile$1 && ozFileList$1.length > 0) scrollToFile(activeOZFile$1); }, [ozFileList$1]); // Custom Event Handler Function function handleRevealFileEvent(evt) { return __awaiter(this, void 0, void 0, function* () { // @ts-ignore const file = evt.detail.file; if (file && file instanceof obsidian.TFile) { yield plugin.openFileTreeLeaf(true); revealFileInFileTree(TFile2OZFile(file)); } else { new obsidian.Notice('File not found'); } }); } function handleRevealFolderEvent(evt) { // @ts-ignore const folder = evt.detail.folder; if (folder && folder instanceof obsidian.TFolder) { revealFolderInFileTree(folder); } else { new obsidian.Notice('Folder not found'); } } // Scrolling Functions function scrollToFile(fileToScroll) { const selector = `div.oz-file-tree-files div.oz-nav-file-title[data-path="${fileToScroll.path}"]`; const fileTitleElement = document.querySelector(selector); if (fileTitleElement) fileTitleElement.scrollIntoView(false); } function scrollToFolder(folder) { const selector = `div.oz-folder-contents div.oz-folder-element[data-path="${folder.path}"]`; const folderElement = document.querySelector(selector); if (folderElement) folderElement.scrollIntoView(false); } // Helper for Reveal Button: Obtain all folders that needs to be opened const getAllFoldersToOpen = (fileToReveal) => { let foldersToOpen = []; const recursiveFx = (folder) => { foldersToOpen.push(folder.path); if (folder.parent) recursiveFx(folder.parent); }; recursiveFx(fileToReveal instanceof obsidian.TFile ? fileToReveal.parent : fileToReveal); return foldersToOpen; }; // --> Handle Reveal Folder Button function revealFolderInFileTree(folderToReveal) { if (!folderToReveal) return; setActiveFolderPath(folderToReveal.path); const foldersToOpen = getAllFoldersToOpen(folderToReveal); let openFoldersSet = new Set([...openFolders$1, ...foldersToOpen]); setOpenFolders(Array.from(openFoldersSet)); scrollToFolder(folderToReveal); } // --> Handle Reveal Active File Button function revealFileInFileTree(ozFileToReveal) { const fileToReveal = plugin.app.vault.getAbstractFileByPath(ozFileToReveal.path); if (!fileToReveal) return; // Get parent folder const parentFolder = fileToReveal.parent; // Focused Folder needs to be root for the reveal if (focusedFolder$1 && focusedFolder$1.path !== '/') setFocusedFolder(plugin.app.vault.getRoot()); // Sanity check - Parent to be folder and set required component states if (parentFolder instanceof obsidian.TFolder) { // Set Active Folder - It will trigger auto file list update setActiveFolderPath(parentFolder.path); // Set active file to show in the list setActiveOzFile(TFile2OZFile(fileToReveal)); // Set openfolders to expand in the folder list const foldersToOpen = getAllFoldersToOpen(fileToReveal); let openFoldersSet = new Set([...openFolders$1, ...foldersToOpen]); setOpenFolders(Array.from(openFoldersSet)); scrollToFile(TFile2OZFile(fileToReveal)); scrollToFolder(parentFolder); } } return (React.createElement(React.Fragment, null, view$1 === 'folder' ? (React.createElement(MainFolder, { plugin: plugin })) : plugin.settings.evernoteView === 'Horizontal' ? (React.createElement(SingleViewHorizontal, { plugin: plugin })) : plugin.settings.evernoteView === 'Vertical' ? (React.createElement(SingleViewVertical, { plugin: plugin })) : (React.createElement(FileComponent, { plugin: plugin })))); } class FileTreeView extends obsidian.ItemView { constructor(leaf, plugin) { super(leaf); this.plugin = plugin; } getViewType() { var _a; return (_a = this.plugin) === null || _a === void 0 ? void 0 : _a.VIEW_TYPE; } getDisplayText() { var _a; return (_a = this.plugin) === null || _a === void 0 ? void 0 : _a.VIEW_DISPLAY_TEXT; } getIcon() { var _a; return (_a = this.plugin) === null || _a === void 0 ? void 0 : _a.ICON; } onClose() { return __awaiter(this, void 0, void 0, function* () { this.destroy(); }); } destroy() { if (this.root) this.root.unmount(); } onOpen() { return __awaiter(this, void 0, void 0, function* () { this.destroy(); this.constructFileTree(this.app.vault.getRoot().path, ''); }); } constructFileTree(folderPath, vaultChange) { this.destroy(); this.root = createRoot(this.contentEl); this.root.render(React.createElement("div", { className: "file-tree-plugin-view" }, React.createElement(Recoil_index_5, null, React.createElement(MainTreeComponent, { fileTreeView: this, plugin: this.plugin })))); } } var lib = {}; Object.defineProperty(lib,"__esModule",{value:true});var LocalStorageHandler_1 = lib.LocalStorageHandler=void 0;var LocalStorageHandler=/** @class */function(){/** * @param cacheHours: Default is 24 Hours, specify if you need less or more */function LocalStorageHandler(params){var _this=this;this.getTimeStampKey=function(key){return key+"-timestamp";};/** * Checks the key and returns the value from LocalStorage if data saved in last cachedHours. * If no data within last cacheHours, returns null. * If data, returns String value from the Storage. * @param key the key to check * @param checkCacheHours specify if you want to check the cachehours or return the value no matter when set * @param cacheHours specify if you want to overwrite the cacheHours of the Local Storage Handler and check with the new value * @returns Value from Local Storage as String or null */this.getFromLocalStorage=function(params){var key=params.key,checkCacheHours=params.checkCacheHours,cacheHours=params.cacheHours;var localData=localStorage.getItem(key);var localDataTimeStamp=localStorage.getItem(_this.getTimeStampKey(key));if(checkCacheHours!==undefined){if(!checkCacheHours)return localData;}// If Local Storage has the data less than cacheHours if(cacheHours)_this.cacheHours=cacheHours;if(localDataTimeStamp!==null){var dt=new Date(JSON.parse(localDataTimeStamp));var hours=Math.abs(new Date().getTime()-dt.getTime())/3600000;if(hours<_this.cacheHours&&localData!==null){return localData;}}return null;};/** * Sets the LocalStorage Value with provided key * Sets also a timestamp in LocalStorage for the provided key * You need to return the LocalStorage value by utilizing the getFromLocalStorage() function * @param key * @param value */this.setLocalStorage=function(params){var key=params.key,value=params.value;localStorage.setItem(key,value);localStorage.setItem(_this.getTimeStampKey(key),JSON.stringify(new Date()));return 'success';};/** * @param key - key to remove from local storage */this.removeFromLocalStorage=function(params){var key=params.key;var localData=localStorage.getItem(key);if(!localData)return 'not-found';// Delete the key first if found localStorage.removeItem(key);// Delete the timestamp if found var timestampKey=_this.getTimeStampKey(key);var localTimestamp=localStorage.getItem(timestampKey);if(localTimestamp)localStorage.removeItem(timestampKey);return 'success';};var cacheHours=params.cacheHours;this.cacheHours=cacheHours?cacheHours:24;}return LocalStorageHandler;}();LocalStorageHandler_1 = lib.LocalStorageHandler=LocalStorageHandler; const DEFAULT_SETTINGS = { openViewOnStart: true, ribbonIcon: true, showRootFolder: true, showFilesFromSubFolders: true, searchFunction: true, allSearchOnlyInFocusedFolder: false, showFilesFromSubFoldersButton: true, revealActiveFileButton: false, excludedExtensions: '', excludedFolders: '', hideAttachments: false, attachmentsFolderName: 'attachments', folderIcon: 'default', folderCount: true, folderCountOption: 'notes', evernoteView: 'Vertical', filePreviewOnHover: false, iconBeforeFileName: true, sortFilesBy: 'name', sortReverse: false, sortFoldersBy: 'name', fixedHeaderInFileList: true, createdYaml: false, fileNameIsHeader: false, folderNote: false, deleteFileOption: 'trash', showFileNameAsFullPath: false, bookmarksEvents: false, }; class FileTreeAlternativePluginSettingsTab extends obsidian.PluginSettingTab { constructor(app, plugin) { super(app, plugin); this.plugin = plugin; } refreshView() { let evt = new CustomEvent(eventTypes.refreshView, {}); window.dispatchEvent(evt); } display() { let { containerEl } = this; containerEl.empty(); let lsh = new LocalStorageHandler_1({}); /* ------------- Buy Me a Coffee ------------- */ const coffeeDiv = containerEl.createDiv('coffee'); coffeeDiv.addClass('oz-coffee-div'); const coffeeLink = coffeeDiv.createEl('a', { href: 'https://ko-fi.com/L3L356V6Q' }); const coffeeImg = coffeeLink.createEl('img', { attr: { src: 'https://cdn.ko-fi.com/cdn/kofi2.png?v=3', }, }); coffeeImg.height = 45; /* ------------- General Settings ------------- */ containerEl.createEl('h2', { text: 'General' }); new obsidian.Setting(containerEl) .setName('Evernote View') .setDesc('Turn on if you want to see the folders and files in a single view without switching between views. Similar experience to Evernote.') .addDropdown((dropdown) => { dropdown .addOption('Disabled', 'Disabled') .addOption('Horizontal', 'Horizontal') .addOption('Vertical', 'Vertical') .setValue(this.plugin.settings.evernoteView) .onChange((value) => { this.plugin.settings.evernoteView = value; this.plugin.saveSettings(); this.refreshView(); }); }); new obsidian.Setting(containerEl) .setName('Ribbon Icon') .setDesc('Turn on if you want Ribbon Icon for activating the File Tree.') .addToggle((toggle) => toggle.setValue(this.plugin.settings.ribbonIcon).onChange((value) => { this.plugin.settings.ribbonIcon = value; this.plugin.saveSettings(); this.plugin.refreshIconRibbon(); })); new obsidian.Setting(containerEl) .setName('Open on Start') .setDesc("Turn off if you don't want file tree view to be opened automatically during vault start") .addToggle((toggle) => toggle.setValue(this.plugin.settings.openViewOnStart).onChange((value) => { this.plugin.settings.openViewOnStart = value; this.plugin.saveSettings(); })); new obsidian.Setting(containerEl) .setName('Bookmarks Event Listener (Shift + Click)') .setDesc('This will enable to reveal file or folder from core bookmarks plugin.' + 'Because there is no API yet to overwrite the default behaviour for Bookmarks plugin,' + 'this will add an event to reveal file if you click on bookmark name using shift') .addToggle((toggle) => toggle.setValue(this.plugin.settings.bookmarksEvents).onChange((value) => { this.plugin.settings.bookmarksEvents = value; if (value) { this.plugin.bookmarksAddEventListener(); } else { this.plugin.bookmarksRemoveEventListener(); } this.plugin.saveSettings(); })); /* ------------- Folder Pane Settings ------------- */ containerEl.createEl('h2', { text: 'Folder Pane Settings' }); new obsidian.Setting(containerEl) .setName('Folder Icons') .setDesc('Change the default folder icons your preferred option') .addDropdown((dropdown) => { dropdown .addOption('default', 'Default') .addOption('box-folder', 'Box Icons') .addOption('icomoon', 'IcoMoon Icons') .addOption('typicon', 'Typicons') .addOption('circle-gg', 'Circle GG') .setValue(this.plugin.settings.folderIcon) .onChange((value) => { this.plugin.settings.folderIcon = value; this.plugin.saveSettings(); this.refreshView(); }); }); new obsidian.Setting(containerEl) .setName('Show Root Folder') .setDesc(`Turn on if you want your Root Folder "${this.plugin.app.vault.getName()}" to be visible in the file tree`) .addToggle((toggle) => toggle.setValue(this.plugin.settings.showRootFolder).onChange((value) => { this.plugin.settings.showRootFolder = value; this.plugin.saveSettings(); this.refreshView(); })); new obsidian.Setting(containerEl) .setName('Folder Count') .setDesc('Turn on if you want see the number of notes/files under file tree.') .addToggle((toggle) => toggle.setValue(this.plugin.settings.folderCount).onChange((value) => { this.plugin.settings.folderCount = value; this.plugin.saveSettings(); this.plugin.refreshTreeLeafs(); })); new obsidian.Setting(containerEl) .setName('Folder Count Details') .setDesc('Select which files you want to be included into count') .addDropdown((dropdown) => { dropdown.addOption('notes', 'Notes'); dropdown.addOption('files', 'All Files'); dropdown.setValue(this.plugin.settings.folderCountOption); dropdown.onChange((option) => { this.plugin.settings.folderCountOption = option; this.plugin.saveSettings(); this.refreshView(); }); }); new obsidian.Setting(containerEl) .setName('Folder Note') .setDesc(`Turn this option on if you want to create Folder Note same as Folder Note Plugin. By default, Click will open the list of files. You need to use "Shift+Click" to open the folder note. If folder has a folder note, you will see an arrow icon on the right side of folder. The note created as a folder note is hidden in the file list.`) .addToggle((toggle) => { toggle.setValue(this.plugin.settings.folderNote).onChange((value) => { this.plugin.settings.folderNote = value; this.plugin.saveSettings(); this.refreshView(); }); }); /* ------------- File Pane Settings ------------- */ containerEl.createEl('h2', { text: 'File Pane Settings' }); new obsidian.Setting(containerEl) .setName('Include Files From Subfolders to the File List') .setDesc(`Turn on this option if you want to see the list of files from all subfolders in addition to the selected folder`) .addToggle((toggle) => toggle.setValue(this.plugin.settings.showFilesFromSubFolders).onChange((value) => { this.plugin.settings.showFilesFromSubFolders = value; this.plugin.saveSettings(); this.refreshView(); })); new obsidian.Setting(containerEl) .setName('Toggle Button for Include Files from Subfolders') .setDesc(`Turn on this option if you want to have an additional button on the top of the file list to toggle "Include Files From Subfolders"`) .addToggle((toggle) => toggle.setValue(this.plugin.settings.showFilesFromSubFoldersButton).onChange((value) => { this.plugin.settings.showFilesFromSubFoldersButton = value; this.plugin.saveSettings(); this.refreshView(); })); new obsidian.Setting(containerEl) .setName('Reveal Active File in File Tree Button') .setDesc(`Turn on this option if you want to have an additional button to reveal the active file in the file tree. It will set the folder and file pane accordingly.`) .addToggle((toggle) => toggle.setValue(this.plugin.settings.revealActiveFileButton).onChange((value) => { this.plugin.settings.revealActiveFileButton = value; this.plugin.saveSettings(); this.refreshView(); })); new obsidian.Setting(containerEl) .setName('Search in File List') .setDesc(`Turn on this option if you want to enable search function to filter files by name.`) .addToggle((toggle) => toggle.setValue(this.plugin.settings.searchFunction).onChange((value) => { this.plugin.settings.searchFunction = value; this.plugin.saveSettings(); this.refreshView(); })); new obsidian.Setting(containerEl) .setName('All & Tag Search only in Focused Folder') .setDesc(`"all:" and "tag:" searches by default looks for all files in your vault. Turn on this option if you want search only in Focused Folder`) .addToggle((toggle) => toggle.setValue(this.plugin.settings.allSearchOnlyInFocusedFolder).onChange((value) => { this.plugin.settings.allSearchOnlyInFocusedFolder = value; this.plugin.saveSettings(); })); new obsidian.Setting(containerEl) .setName('Icon Before File Name') .setDesc('Turn on if you want to file icon before the file name in the file list.') .addToggle((toggle) => toggle.setValue(this.plugin.settings.iconBeforeFileName).onChange((value) => { this.plugin.settings.iconBeforeFileName = value; this.plugin.saveSettings(); this.refreshView(); })); new obsidian.Setting(containerEl) .setName('Preview File on Hover') .setDesc('Turn on if you want to preview the files once you hover on them within the file list holding Ctrl/Cmd button.') .addToggle((toggle) => toggle.setValue(this.plugin.settings.filePreviewOnHover).onChange((value) => { this.plugin.settings.filePreviewOnHover = value; this.plugin.saveSettings(); })); new obsidian.Setting(containerEl) .setName('Fixed Buttons and Header in File Pane') .setDesc('Turn on if you want buttons and header to be not scrolled within the file list.') .addToggle((toggle) => toggle.setValue(this.plugin.settings.fixedHeaderInFileList).onChange((value) => { this.plugin.settings.fixedHeaderInFileList = value; this.plugin.saveSettings(); this.refreshView(); })); new obsidian.Setting(containerEl) .setName('Show file names as full path') .setDesc('Turn on if you want to see the full path within the file name list rather than only file name') .addToggle((toggle) => { toggle.setValue(this.plugin.settings.showFileNameAsFullPath).onChange((value) => { this.plugin.settings.showFileNameAsFullPath = value; this.plugin.saveSettings(); this.refreshView(); }); }); new obsidian.Setting(containerEl) .setName('Deleted File Destination') .setDesc('Select where you want files to be moved once they are deleted') .addDropdown((dropdown) => { dropdown.addOption('permanent', 'Delete Permanently'); dropdown.addOption('trash', 'Move to Obsidian Trash'); dropdown.addOption('system-trash', 'Move to System Trash'); dropdown.setValue(this.plugin.settings.deleteFileOption); dropdown.onChange((option) => { this.plugin.settings.deleteFileOption = option; this.plugin.saveSettings(); }); }); /* ------------- Exclusion Settings ------------- */ containerEl.createEl('h2', { text: 'File Creation' }); containerEl.createEl('p', { text: 'The settings below are only applicable if the plus (+) button within the file pane of the plugin is used.' }); new obsidian.Setting(containerEl) .setName('Created information in YAML') .setDesc('Turn on if you want plugin to include created YAML key with the time of creation') .addToggle((toggle) => { toggle.setValue(this.plugin.settings.createdYaml).onChange((value) => { this.plugin.settings.createdYaml = value; this.plugin.saveSettings(); }); }); new obsidian.Setting(containerEl) .setName('Set File Name as Header 1') .setDesc('Turn on if you want plugin to add the initial file name as main header in the created file.') .addToggle((toggle) => { toggle.setValue(this.plugin.settings.fileNameIsHeader).onChange((value) => { this.plugin.settings.fileNameIsHeader = value; this.plugin.saveSettings(); }); }); /* ------------- Exclusion Settings ------------- */ containerEl.createEl('h2', { text: 'Exclude Settings' }); new obsidian.Setting(containerEl) .setName('Hide Attachments') .setDesc(`It will hide "attachments" folder from the view and any file under this folder from the file list`) .addToggle((toggle) => toggle.setValue(this.plugin.settings.hideAttachments).onChange((value) => { this.plugin.settings.hideAttachments = value; this.plugin.saveSettings(); this.plugin.refreshTreeLeafs(); })); new obsidian.Setting(containerEl) .setName('Excluded File Extensions') .setDesc(`Provide extension of files, which you want to exclude from listing in file tree, divided by comma. i.e. 'png, pdf, jpeg'. You need to reload the vault or use "Reload File Tree" button below to make changes effective.`) .addTextArea((text) => text.setValue(this.plugin.settings.excludedExtensions).onChange((value) => { this.plugin.settings.excludedExtensions = value; this.plugin.saveSettings(); })); new obsidian.Setting(containerEl) .setName('Excluded Folder Paths') .setDesc(`Provide full path of folders, which you want to exclude from listing in file tree, divided by comma. i.e. 'Personal/Attachments, Work/Documents/Folders'. All subfolders are going to be excluded, as well. You need to reload the vault or use "Reload File Tree" button below to make changes effective.`) .addTextArea((text) => text.setValue(this.plugin.settings.excludedFolders).onChange((value) => { this.plugin.settings.excludedFolders = value; this.plugin.saveSettings(); })); new obsidian.Setting(containerEl) .setDesc('Use this button to reload the file tree. Reloading the file tree is required for some of the settings. You can also restart your vault to have same effect.') .addButton((button) => { button .setClass('reload-file-tree-button') .setTooltip('Click here to reload the file tree') .setButtonText('Reload File Tree') .onClick((e) => { this.plugin.refreshTreeLeafs(); }); }); /* ------------- Clear Data ------------- */ containerEl.createEl('h2', { text: 'Clear Data' }); new obsidian.Setting(containerEl) .setName('Clear All Cache Data') .setDesc(`This button will clear the following cache data: "Last position of the divider" & "List of expanded folders in the folder pane", & "Last active folder path". It will not touch your settings above and list of pinned files. It is recommended to do this clearing once in a while.`) .addButton((button) => { button .setTooltip('Click here to clear the cache data') .setButtonText('Click for Clearing the Cache') .onClick(() => __awaiter(this, void 0, void 0, function* () { lsh.removeFromLocalStorage({ key: this.plugin.keys.customHeightKey }); lsh.removeFromLocalStorage({ key: this.plugin.keys.customWidthKey }); lsh.removeFromLocalStorage({ key: this.plugin.keys.openFoldersKey }); lsh.removeFromLocalStorage({ key: this.plugin.keys.activeFolderPathKey }); lsh.removeFromLocalStorage({ key: this.plugin.keys.focusedFolder }); this.plugin.refreshTreeLeafs(); new obsidian.Notice('The plugin cache is cleared...'); })); }); new obsidian.Setting(containerEl) .setName('Clear Pinned Files') .setDesc(`This button will clear the pinned files in the file list pane.`) .addButton((button) => { button .setTooltip('Click here to clear the pinned files') .setButtonText('Click for Clearing the Pinned files') .onClick(() => __awaiter(this, void 0, void 0, function* () { lsh.removeFromLocalStorage({ key: this.plugin.keys.pinnedFilesKey }); this.plugin.refreshTreeLeafs(); new obsidian.Notice('The pinned files are cleared...'); })); }); } } class FileTreeAlternativePlugin extends obsidian.Plugin { constructor() { super(...arguments); this.ribbonIconEl = undefined; this.keys = { activeFolderPathKey: 'fileTreePlugin-ActiveFolderPath', pinnedFilesKey: 'fileTreePlugin-PinnedFiles', openFoldersKey: 'fileTreePlugin-OpenFolders', customHeightKey: 'fileTreePlugin-CustomHeight', customWidthKey: 'fileTreePlugin-CustomWidth', focusedFolder: 'fileTreePlugin-FocusedFolder', }; // File Tree View Variables this.VIEW_TYPE = 'file-tree-view'; this.VIEW_DISPLAY_TEXT = 'File Tree'; this.ICON = 'sheets-in-box'; this.bookmarksEventHandler = (event) => { // Find the tree-item that includes the bookmarks plugin title let treeItem = event.target.closest('.tree-item'); if (!treeItem) return; // If it exists, get the title of the bookmark let dataPath = treeItem.getAttribute('data-path'); if (!dataPath || dataPath === '') return; // Find the bookmark from the items let bookmarkItem = getBookmarkTitle(dataPath); // Create Custom Menu only if Shift is Used if (event.shiftKey) { if (!bookmarkItem) return; event.stopImmediatePropagation(); if (bookmarkItem.type === 'file') { // Dispatch Reveal File Event let customEvent = new CustomEvent(eventTypes.revealFile, { detail: { file: this.app.vault.getAbstractFileByPath(bookmarkItem.path), }, }); window.dispatchEvent(customEvent); } else if (bookmarkItem.type === 'folder') { event.stopImmediatePropagation(); // Dispatch Reveal Folder Event let customEvent = new CustomEvent(eventTypes.revealFolder, { detail: { folder: this.app.vault.getAbstractFileByPath(bookmarkItem.path), }, }); window.dispatchEvent(customEvent); } else { new obsidian.Notice('Not a file or folder'); } } }; this.getBookmarksLeafElement = () => { return document.querySelector('.workspace-leaf-content[data-type="bookmarks"]'); }; this.bookmarksAddEventListener = () => { let bookmarkLeafElement = this.getBookmarksLeafElement(); if (bookmarkLeafElement) { bookmarkLeafElement.addEventListener('click', this.bookmarksEventHandler, true); } }; this.bookmarksRemoveEventListener = () => { let bookmarkLeafElement = this.getBookmarksLeafElement(); if (bookmarkLeafElement) { bookmarkLeafElement.removeEventListener('click', this.bookmarksEventHandler, true); } }; this.triggerVaultChangeEvent = (file, changeType, oldPath) => { let event = new CustomEvent(eventTypes.vaultChange, { detail: { file: file, changeType: changeType, oldPath: oldPath ? oldPath : '', }, }); window.dispatchEvent(event); }; this.onCreate = (file) => this.triggerVaultChangeEvent(file, 'create', ''); this.onDelete = (file) => this.triggerVaultChangeEvent(file, 'delete', ''); this.onModify = (file) => this.triggerVaultChangeEvent(file, 'modify', ''); this.onRename = (file, oldPath) => this.triggerVaultChangeEvent(file, 'rename', oldPath); this.refreshIconRibbon = () => { var _a; (_a = this.ribbonIconEl) === null || _a === void 0 ? void 0 : _a.remove(); if (this.settings.ribbonIcon) { this.ribbonIconEl = this.addRibbonIcon(this.ICON, 'File Tree Alternative Plugin', () => __awaiter(this, void 0, void 0, function* () { yield this.openFileTreeLeaf(true); })); } }; this.openFileTreeLeaf = (showAfterAttach) => __awaiter(this, void 0, void 0, function* () { let leafs = this.app.workspace.getLeavesOfType(this.VIEW_TYPE); if (leafs.length == 0) { // Needs to be mounted let leaf = this.app.workspace.getLeftLeaf(false); yield leaf.setViewState({ type: this.VIEW_TYPE }); if (showAfterAttach) this.app.workspace.revealLeaf(leaf); } else { // Already mounted - show if only selected showAfterAttach if (showAfterAttach) { leafs.forEach((leaf) => this.app.workspace.revealLeaf(leaf)); } } }); this.detachFileTreeLeafs = () => { let leafs = this.app.workspace.getLeavesOfType(this.VIEW_TYPE); for (let leaf of leafs) { leaf.view.destroy(); leaf.detach(); } }; this.refreshTreeLeafs = () => { this.detachFileTreeLeafs(); this.openFileTreeLeaf(true); }; } onload() { return __awaiter(this, void 0, void 0, function* () { console.log('Loading Alternative File Tree Plugin'); obsidian.addIcon('zoomInIcon', ZoomInIcon); obsidian.addIcon('zoomOutIcon', ZoomOutIcon); obsidian.addIcon('zoomOutDoubleIcon', ZoomOutDoubleIcon); obsidian.addIcon('locationIcon', LocationIcon); obsidian.addIcon('spaceIcon', SpaceIcon); // Load Settings this.addSettingTab(new FileTreeAlternativePluginSettingsTab(this.app, this)); yield this.loadSettings(); // Register File Tree View this.registerView(this.VIEW_TYPE, (leaf) => { return new FileTreeView(leaf, this); }); // Event Listeners this.app.workspace.onLayoutReady(() => __awaiter(this, void 0, void 0, function* () { if (this.settings.openViewOnStart) { yield this.openFileTreeLeaf(true); } })); // Add Command to Open File Tree Leaf this.addCommand({ id: 'open-file-tree-view', name: 'Open File Tree View', callback: () => __awaiter(this, void 0, void 0, function* () { return yield this.openFileTreeLeaf(true); }), }); this.app.workspace.onLayoutReady(() => { if (this.settings.bookmarksEvents) { this.bookmarksAddEventListener(); } }); // Add Command to Reveal Active File this.addCommand({ id: 'reveal-active-file', name: 'Reveal Active File', callback: () => { // Activate file tree pane let leafs = this.app.workspace.getLeavesOfType(this.VIEW_TYPE); if (leafs.length === 0) this.openFileTreeLeaf(true); for (let leaf of leafs) { this.app.workspace.revealLeaf(leaf); } // Run custom event let event = new CustomEvent(eventTypes.revealFile, { detail: { file: this.app.workspace.getActiveFile(), }, }); window.dispatchEvent(event); }, }); // Add Command to create a new file under active folder path this.addCommand({ id: ' create-new-note', name: 'Create a New Note', callback: () => { let event = new CustomEvent(eventTypes.createNewNote, { detail: {}, }); window.dispatchEvent(event); }, }); // Add event listener for vault changes this.app.vault.on('create', this.onCreate); this.app.vault.on('delete', this.onDelete); this.app.vault.on('modify', this.onModify); this.app.vault.on('rename', this.onRename); // Ribbon Icon For Opening this.refreshIconRibbon(); }); } onunload() { console.log('Unloading Alternative File Tree Plugin'); this.detachFileTreeLeafs(); // Remove event listeners this.app.vault.off('create', this.onCreate); this.app.vault.off('delete', this.onDelete); this.app.vault.off('modify', this.onModify); this.app.vault.off('rename', this.onRename); this.bookmarksRemoveEventListener(); } loadSettings() { return __awaiter(this, void 0, void 0, function* () { this.settings = Object.assign({}, DEFAULT_SETTINGS, yield this.loadData()); }); } saveSettings() { return __awaiter(this, void 0, void 0, function* () { yield this.saveData(this.settings); }); } } module.exports = FileTreeAlternativePlugin;