@guruhotel/aura-hooks
Version:
🪝 Hooks library designed by the Guruhotel team for Aura UI
1 lines • 1.08 kB
JavaScript
import{useReducer as e,useCallback as t}from"react";var n;!function(e){e.Undo="UNDO",e.Redo="REDO",e.Set="SET",e.Reset="RESET"}(n||(n={}));const s={past:[],present:null,future:[]};export const useUndo=(r,o={})=>{const{useCheckpoints:u}={useCheckpoints:!1,...o},[p,c]=e(((e,t)=>{const{past:s,present:r,future:o}=e;switch(t.type){case n.Undo:{if(0===s.length)return e;const t=s[s.length-1];return{past:s.slice(0,s.length-1),present:t,future:[r,...o]}}case n.Redo:{if(0===o.length)return e;const t=o[0],n=o.slice(1);return{past:[...s,r],present:t,future:n}}case n.Set:{const n=!u||!!t.historyCheckpoint,{newPresent:o}=t;return o===r?e:{past:!1===n?s:[...s,r],present:o,future:[]}}case n.Reset:{const{newPresent:e}=t;return{past:[],present:e,future:[]}}}}),{...s,present:r}),a=0!==p.past.length,d=0!==p.future.length,h=t((()=>{a&&c({type:n.Undo})}),[a]),i=t((()=>{d&&c({type:n.Redo})}),[d]);return[p,{set:t(((e,t=!1)=>{c({type:n.Set,newPresent:e,historyCheckpoint:t})}),[]),reset:t((e=>c({type:n.Reset,newPresent:e})),[]),undo:h,redo:i,canUndo:a,canRedo:d}]};export default useUndo;