preact-missing-hooks
Version:
A lightweight, extendable collection of missing React-like hooks for Preact — plus fresh, powerful new ones designed specifically for modern Preact apps.
3 lines (2 loc) • 17.8 kB
JavaScript
import{useState as n,useCallback as e,useEffect as r,useMemo as t,useRef as o}from"preact/hooks";import{isValidElement as u,cloneElement as i}from"preact";function c(){var r=n(!1),t=r[0],o=r[1];return[e(function(n){o(!0),Promise.resolve().then(function(){n(),o(!1)})},[]),t]}function a(n,e,t){r(function(){var r=n.current;if(r){var o=new MutationObserver(e);return o.observe(r,t),function(){return o.disconnect()}}},[n,e,t])}var s=new Map;function f(){var n=e(function(n){var e=arguments,r=s.get(n);r&&r.forEach(function(n){return n.apply(void 0,[].slice.call(e,1))})},[]);return{emit:n,on:e(function(n,e){var r=s.get(n);return r||(r=new Set,s.set(n,r)),r.add(e),function(){r.delete(e),0===r.size&&s.delete(n)}},[])}}function l(n,e){(null==e||e>n.length)&&(e=n.length);for(var r=0,t=Array(e);r<e;r++)t[r]=n[r];return t}function d(n,e){var r="undefined"!=typeof Symbol&&n[Symbol.iterator]||n["@@iterator"];if(r)return(r=r.call(n)).next.bind(r);if(Array.isArray(n)||(r=function(n,e){if(n){if("string"==typeof n)return l(n,e);var r={}.toString.call(n).slice(8,-1);return"Object"===r&&n.constructor&&(r=n.constructor.name),"Map"===r||"Set"===r?Array.from(n):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?l(n,e):void 0}}(n))||e&&n&&"number"==typeof n.length){r&&(n=r);var t=0;return function(){return t>=n.length?{done:!0}:{done:!1,value:n[t++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function v(){return v=Object.assign?Object.assign.bind():function(n){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var t in r)({}).hasOwnProperty.call(r,t)&&(n[t]=r[t])}return n},v.apply(null,arguments)}function p(n,e,r){return void 0===r&&(r="preserve"),t(function(){if(!n)return n;var t=function(n){if(!u(n))return n;var t,o=n.props||{};t="override"===r?v({},o,e):v({},e,o);var c=null==o?void 0:o.style,a=null==e?void 0:e.style;return c&&a&&"object"==typeof c&&"object"==typeof a&&(t.style="override"===r?v({},c,a):v({},a,c)),i(n,t)};return Array.isArray(n)?n.map(t):t(n)},[n,e,r])}function m(){var e=n(function(){if("undefined"==typeof window)return"no-preference";var n=window.matchMedia("(prefers-color-scheme: dark)"),e=window.matchMedia("(prefers-color-scheme: light)");return n.matches?"dark":e.matches?"light":"no-preference"}),t=e[0],o=e[1];return r(function(){if("undefined"!=typeof window){var n=window.matchMedia("(prefers-color-scheme: dark)"),e=function(n){o(n.matches?"dark":"light")},r=function(){var n=window.matchMedia("(prefers-color-scheme: dark)"),e=window.matchMedia("(prefers-color-scheme: light)");o(n.matches?"dark":e.matches?"light":"no-preference")};n.addEventListener("change",e);var t=window.matchMedia("(prefers-color-scheme: light)");return t.addEventListener("change",r),function(){n.removeEventListener("change",e),t.removeEventListener("change",r)}}},[]),t}function h(){if("undefined"==typeof navigator)return{online:!0};var n={online:navigator.onLine},e=navigator.connection;return e&&(void 0!==e.effectiveType&&(n.effectiveType=e.effectiveType),void 0!==e.downlink&&(n.downlink=e.downlink),void 0!==e.rtt&&(n.rtt=e.rtt),void 0!==e.saveData&&(n.saveData=e.saveData),void 0!==e.type&&(n.connectionType=e.type)),n}function y(){var e=n(h),t=e[0],o=e[1];return r(function(){if("undefined"!=typeof window){var n=function(){return o(h())};window.addEventListener("online",n),window.addEventListener("offline",n);var e=navigator.connection;return null!=e&&e.addEventListener&&e.addEventListener("change",n),function(){window.removeEventListener("online",n),window.removeEventListener("offline",n),null!=e&&e.removeEventListener&&e.removeEventListener("change",n)}}},[]),t}function w(n,e){try{var r=n()}catch(n){return e(n)}return r&&r.then?r.then(void 0,e):r}function g(r){void 0===r&&(r={});var t=r.resetDelay,o=void 0===t?2e3:t,u=n(!1),i=u[0],c=u[1],a=n(null),s=a[0],f=a[1],l=e(function(){c(!1),f(null)},[]);return{copy:e(function(n){try{if(f(null),"undefined"==typeof navigator||!navigator.clipboard){var e=new Error("Clipboard API is not available");return f(e),Promise.resolve(!1)}return Promise.resolve(w(function(){return Promise.resolve(navigator.clipboard.writeText(n)).then(function(){return c(!0),o>0&&setTimeout(function(){return c(!1)},o),!0})},function(n){var e=n instanceof Error?n:new Error(String(n));return f(e),!1}))}catch(n){return Promise.reject(n)}},[o]),paste:e(function(){try{if(f(null),"undefined"==typeof navigator||!navigator.clipboard){var n=new Error("Clipboard API is not available");return f(n),Promise.resolve("")}return Promise.resolve(w(function(){return Promise.resolve(navigator.clipboard.readText())},function(n){var e=n instanceof Error?n:new Error(String(n));return f(e),""}))}catch(n){return Promise.reject(n)}},[]),copied:i,error:s,reset:l}}function b(n,e){var t=e.onRageClick,u=e.threshold,i=void 0===u?5:u,c=e.timeWindow,a=void 0===c?1e3:c,s=e.distanceThreshold,f=void 0===s?30:s,l=o(t);l.current=t;var d=o([]);r(function(){var e=n.current;if(e){var r=function(n){var e=Date.now(),r={time:e,x:n.clientX,y:n.clientY},t=e-a,o=d.current.filter(function(n){return n.time>=t});if(o.push(r),Infinity!==f){var u=o.filter(function(n){return e=n,t=r,Math.hypot(t.x-e.x,t.y-e.y)<=f;var e,t});if(u.length>=i)return l.current({count:u.length,event:n}),void(d.current=[])}else if(o.length>=i)return l.current({count:o.length,event:n}),void(d.current=[]);d.current=o};return e.addEventListener("click",r),function(){return e.removeEventListener("click",r)}}},[n,i,a,f])}function E(t,u){var i=u.concurrency,c="sequential"===u.mode?1:Math.max(1,void 0===i?4:i),a=n(!1),s=a[0],f=a[1],l=n(void 0),d=l[0],v=l[1],p=n(void 0),m=p[0],h=p[1],y=n(0),w=y[0],g=y[1],b=o([]),E=o(0),k=o(0),P=o(!1),x=o(t);x.current=t;var M=e(function(){g(b.current.length+k.current)},[]),S=e(function(){if(!(P.current||k.current>=c)){if(0===b.current.length)return 0===k.current&&f(!1),void M();b.current.sort(function(n,e){return n.priority!==e.priority?n.priority-e.priority:n.sequence-e.sequence});var n=b.current.shift();k.current+=1,f(!0),M(),(0,x.current)(n.data).then(function(e){v(e),h(void 0),n.resolve(e)}).catch(function(e){h(e),n.reject(e)}).finally(function(){k.current-=1,M(),S()}),b.current.length>0&&k.current<c&&S()}},[c,M]),j=e(function(n,e){var r;if(P.current)return Promise.reject(new Error("Worker is terminated"));var t=null!=(r=null==e?void 0:e.priority)?r:1,o=++E.current,u=new Promise(function(e,r){b.current.push({data:n,priority:t,sequence:o,resolve:e,reject:r})});return M(),f(!0),queueMicrotask(S),u},[S,M]),I=e(function(){var n=b.current;b.current=[],n.forEach(function(n){return n.reject(new Error("Task cleared from queue"))}),M(),0===k.current&&f(!1)},[M]),D=e(function(){P.current=!0,I()},[I]);return r(function(){return function(){P.current=!0}},[]),{run:j,loading:s,result:d,error:m,queueSize:w,clearQueue:I,terminate:D}}var k=new Map;function P(n){return new Promise(function(e,r){n.onsuccess=function(){return e(n.result)},n.onerror=function(){var e;return r(null!=(e=n.error)?e:new DOMException("Unknown IndexedDB error"))}})}function x(n,e){return e?n.then(function(n){return null==e.onSuccess||e.onSuccess(n),n}).catch(function(n){throw null==e.onError||e.onError(n),n}):n}function M(e){var t=n(null),u=t[0],i=t[1],c=n(null),a=c[0],s=c[1],f=n(!1),l=f[0],p=f[1],m=o(e);return m.current=e,r(function(){var n=!1;s(null),p(!1),i(null);var e=m.current;return function(n){var e=n.name+"_v"+n.version,r=k.get(e);return r||(r=function(n){return new Promise(function(e,r){var t=indexedDB.open(n.name,n.version);t.onerror=function(){var n;return r(null!=(n=t.error)?n:new DOMException("Failed to open database"))},t.onsuccess=function(){return e(t.result)},t.onupgradeneeded=function(e){for(var r=e.target.result,t=n.tables,o=0,u=Object.keys(t);o<u.length;o++){var i=u[o],c=t[i];if(!r.objectStoreNames.contains(i)){var a,s=r.createObjectStore(i,{keyPath:c.keyPath,autoIncrement:null!=(a=c.autoIncrement)&&a});if(c.indexes)for(var f,l=d(c.indexes);!(f=l()).done;){var v=f.value;s.createIndex(v,v,{unique:!1})}}}}})}(n),k.set(e,r),r)}({name:e.name,version:e.version,tables:e.tables}).then(function(e){if(n)e.close();else{var r=function(n){return{get db(){return n},hasTable:function(e){return n.objectStoreNames.contains(e)},table:function(e){return function(n,e){return function(n,e){function r(r){return n.transaction([e],r).objectStore(e)}return{insert:function(n,e){return x(P(r("readwrite").add(n)),e)},update:function(n,e,t){var o=r("readwrite");return x(P(o.get(n)).then(function(n){if(void 0===n)throw new DOMException("Key not found","NotFoundError");var r=v({},n,e);return P(o.put(r))}).then(function(){}),t)},delete:function(n,e){return x(P(r("readwrite").delete(n)).then(function(){}),e)},exists:function(n){return P(r("readonly").getKey(n)).then(function(n){return void 0!==n})},query:function(n,e){var t=r("readonly").openCursor(),o=[];return x(new Promise(function(e,r){t.onsuccess=function(){var r=t.result;r?(n(r.value)&&o.push(r.value),r.continue()):e(o)},t.onerror=function(){var n;return r(null!=(n=t.error)?n:new DOMException("Unknown error"))}}),e)},upsert:function(n,e){return x(P(r("readwrite").put(n)),e)},bulkInsert:function(n,e){var t=r("readwrite"),o=[];if(0===n.length)return x(Promise.resolve(o),e);var u=0;return x(new Promise(function(e,r){n.forEach(function(i,c){var a=t.add(i);a.onsuccess=function(){o[c]=a.result,++u===n.length&&e(o)},a.onerror=function(){var n;return r(null!=(n=a.error)?n:new DOMException("Unknown error"))}})}),e)},clear:function(n){return x(P(r("readwrite").clear()).then(function(){}),n)},count:function(n){return x(P(r("readonly").count()),null!=n?n:{})}}}(n,e)}(n,e)},transaction:function(e,r,t,o){var u=n.transaction(e,r),i={table:function(n){return function(n,e){return function(n,e){function r(){return n.objectStore(e)}return{insert:function(n,e){return x(P(r().add(n)),e)},update:function(n,e,t){var o=r();return x(P(o.get(n)).then(function(n){if(void 0===n)throw new DOMException("Key not found","NotFoundError");var r=v({},n,e);return P(o.put(r))}).then(function(){}),t)},delete:function(n,e){return x(P(r().delete(n)).then(function(){}),e)},exists:function(n){return P(r().getKey(n)).then(function(n){return void 0!==n})},query:function(n,e){var t=r().openCursor(),o=[];return x(new Promise(function(e,r){t.onsuccess=function(){var r=t.result;r?(n(r.value)&&o.push(r.value),r.continue()):e(o)},t.onerror=function(){var n;return r(null!=(n=t.error)?n:new DOMException("Unknown error"))}}),e)},upsert:function(n,e){return x(P(r().put(n)),e)},bulkInsert:function(n,e){var t=r(),o=[];if(0===n.length)return x(Promise.resolve(o),e);var u=0;return x(new Promise(function(e,r){n.forEach(function(i,c){var a=t.add(i);a.onsuccess=function(){o[c]=a.result,++u===n.length&&e(o)},a.onerror=function(){var n;return r(null!=(n=a.error)?n:new DOMException("Unknown error"))}})}),e)},clear:function(n){return x(P(r().clear()).then(function(){}),n)},count:function(n){return x(P(r().count()),null!=n?n:{})}}}(n,e)}(u,n)}},c=new Promise(function(n,e){u.oncomplete=function(){return n()},u.onerror=function(){var n;return e(null!=(n=u.error)?n:new DOMException("Transaction failed"))}}),a=t(i);return function(n,e){return e?n.then(function(){return null==e.onSuccess?void 0:e.onSuccess()}).catch(function(n){throw null==e.onError||e.onError(n),n}):n}(Promise.resolve(a).then(function(){return c}),o)}}}(e);i(r),p(!0)}}).catch(function(e){n||s(e)}),function(){n=!0}},[e.name,e.version]),{db:u,isReady:l,error:a}}var S=/\b(?:25[0-5]|2[0-4]\d|1?\d{1,2})(?:\.(?:25[0-5]|2[0-4]\d|1?\d{1,2})){3}\b/g,j=["stun:stun.l.google.com:19302"];function I(e){void 0===e&&(e={});var t=e.stunServers,u=void 0===t?j:t,i=e.timeout,c=void 0===i?3e3:i,a=e.onDetect,s=n([]),f=s[0],l=s[1],d=n(!0),v=d[0],p=d[1],m=n(null),h=m[0],y=m[1],w=o(null),g=o(null),b=o(new Set),E=o(a);return E.current=a,r(function(){if("undefined"==typeof window)return p(!1),void y("WebRTC IP detection is not available during SSR");if("undefined"==typeof RTCPeerConnection)return p(!1),void y("RTCPeerConnection is not available");var n=new Set;b.current=n;var e=function(){g.current&&(clearTimeout(g.current),g.current=null),w.current&&(w.current.close(),w.current=null),p(!1)},r=function(e){n.has(e)||(n.add(e),l(function(n){return[].concat(n,[e])}),null==E.current||E.current(e))};try{var t=new RTCPeerConnection({iceServers:[{urls:u}]});w.current=t,t.onicecandidate=function(n){var e,t=n.candidate;t&&t.candidate&&((e=t.candidate.match(S))?[].concat(e):[]).forEach(r)},t.createDataChannel(""),t.createOffer().then(function(n){return t.setLocalDescription(n)}).catch(function(n){y(n instanceof Error?n.message:"Failed to create offer"),e()}),g.current=setTimeout(function(){return e()},c)}catch(n){y(n instanceof Error?n.message:"WebRTC setup failed"),e()}return function(){e()}},[u.join(","),c]),{ips:f,loading:v,error:h}}function D(t){var u=t.wasmUrl,i=t.exportName,c=void 0===i?"compute":i,a=t.workerUrl,s=t.importObject,f=n(void 0),l=f[0],d=f[1],v=n(!0),p=v[0],m=v[1],h=n(null),y=h[0],w=h[1],g=n(!1),b=g[0],E=g[1],k=o(null),P=o(null),x=o(null);return r(function(){if("undefined"==typeof window)return w("useWasmCompute is not available during SSR"),void m(!1);if("undefined"==typeof Worker)return w("Worker is not supported in this environment"),void m(!1);if("undefined"==typeof WebAssembly||"function"!=typeof WebAssembly.instantiate)return w("WebAssembly is not supported in this environment"),void m(!1);w(null),E(!1);var n=function(n){if(n)return new Worker(n);var e=new Blob(["\nself.onmessage = async (e) => {\n const d = e.data;\n if (d.type === 'init') {\n try {\n const res = await fetch(d.wasmUrl);\n const buf = await res.arrayBuffer();\n const mod = await WebAssembly.instantiate(buf, d.importObject || {});\n self.wasmInstance = mod.instance;\n self.exportName = d.exportName || 'compute';\n self.postMessage({ type: 'ready' });\n } catch (err) {\n self.postMessage({ type: 'error', error: (err && err.message) || String(err) });\n }\n return;\n }\n if (d.type === 'compute') {\n try {\n const fn = self.wasmInstance.exports[self.exportName];\n if (typeof fn !== 'function') {\n self.postMessage({ type: 'error', error: 'Export \"' + self.exportName + '\" is not a function' });\n return;\n }\n const result = fn(d.input);\n self.postMessage({ type: 'result', result: result });\n } catch (err) {\n self.postMessage({ type: 'error', error: (err && err.message) || String(err) });\n }\n }\n};\n"],{type:"application/javascript"}),r=URL.createObjectURL(e),t=new Worker(r);return URL.revokeObjectURL(r),t}(a);k.current=n;var e=function(n){var e,r=null!=(e=n.data)?e:{},t=r.type,o=r.result,u=r.error;return"ready"===t?(E(!0),void m(!1)):"error"===t?(w(null!=u?u:"Unknown error"),m(!1),void(x.current&&(x.current(new Error(u)),P.current=null,x.current=null))):void("result"===t&&(d(o),m(!1),P.current&&(P.current(o),P.current=null,x.current=null)))};return n.addEventListener("message",e),n.postMessage({type:"init",wasmUrl:u,exportName:c,importObject:null!=s?s:{}}),function(){n.removeEventListener("message",e),n.terminate(),k.current=null,x.current&&(x.current(new Error("Worker terminated")),P.current=null,x.current=null)}},[u,c,a,s]),{compute:e(function(n){return new Promise(function(e,r){k.current&&b?y?r(new Error(y)):(P.current=e,x.current=r,m(!0),k.current.postMessage({type:"compute",input:n})):r(new Error("WASM not ready"))})},[b,y]),result:l,loading:p,error:y,ready:b}}function L(e,u){void 0===u&&(u={});var i=u.maxHistory,c=void 0===i?100:i,a=u.throughputWindowMs,s=void 0===a?1e3:a,f=n([]),l=f[0],d=f[1],v=n(0),p=v[0],m=v[1],h=n(0),y=h[0],w=h[1],g=n([]),b=g[0],E=g[1],k=n(0),P=k[0],x=k[1],M=o([]),S=o(0),j=o(0);r(function(){if(e){var n=function(n){var e=function(n){if(null==n||"object"!=typeof n)return null;var e=n.type;return"task_start"!==e&&"task_end"!==e&&"task_fail"!==e&&"queue_size"!==e?null:{type:e,taskId:"string"==typeof n.taskId?n.taskId:void 0,duration:"number"==typeof n.duration?n.duration:void 0,error:"string"==typeof n.error?n.error:void 0,size:"number"==typeof n.size?n.size:void 0,timestamp:Date.now()}}(n.data);if(e)if(E(function(n){return[].concat(n,[e]).slice(-c)}),"task_start"===e.type&&e.taskId)d(function(n){return n.includes(e.taskId)?n:[].concat(n,[e.taskId])});else if("task_end"===e.type){e.taskId&&d(function(n){return n.filter(function(n){return n!==e.taskId})}),m(function(n){return n+1});var r=Date.now()-s;M.current=[].concat(M.current.filter(function(n){return n>=r}),[e.timestamp]),"number"==typeof e.duration&&(S.current+=e.duration,j.current+=1)}else"task_fail"===e.type?(e.taskId&&d(function(n){return n.filter(function(n){return n!==e.taskId})}),w(function(n){return n+1})):"queue_size"===e.type&&"number"==typeof e.size&&x(e.size)};return e.addEventListener("message",n),function(){return e.removeEventListener("message",n)}}},[e,c]);var I=t(function(){var n=j.current;return n>0?S.current/n:0},[b]),D=t(function(){var n=Date.now()-s;return M.current.filter(function(e){return e>=n}).length/(s/1e3)},[b,s]),L=t(function(){return{runningTasks:l,completedCount:p,failedCount:y,averageDurationMs:I,throughputPerSecond:D,currentQueueSize:P,totalProcessed:p+y,recentEventCount:b.length}},[l,p,y,I,D,P,b.length]);return{runningTasks:l,completedCount:p,failedCount:y,eventHistory:b,averageDurationMs:I,throughputPerSecond:D,currentQueueSize:P,progress:L}}export{g as useClipboard,f as useEventBus,M as useIndexedDB,a as useMutationObserver,y as useNetworkState,m as usePreferredTheme,b as useRageClick,E as useThreadedWorker,c as useTransition,D as useWasmCompute,I as useWebRTCIP,L as useWorkerNotifications,p as useWrappedChildren};
//# sourceMappingURL=entry.module.js.map