hyper-undo 0.6.2 → 0.6.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,27 @@
1
1
  # hyper-undo changelog
2
2
 
3
+ ## [0.6.4] - 2026-10-15
4
+
5
+ ### Changed
6
+ - Synced content-dom.js and region-capabilities.js with ClayJS, and updated extension-noise.js
7
+
8
+ ### Fixed
9
+ - A select whose selected option is excluded from saving now keeps its selection in the content view (ported from ClayJS)
10
+
11
+
12
+
13
+ ## [0.6.3] - 2026-10-10
14
+
15
+ ### Fixed
16
+ - Cmd+Z inside OverType editors is now handled by the editor's own textarea instead of the global undo
17
+
18
+
19
+
20
+ ## [Unreleased]
21
+
22
+ ### Fixed
23
+ - Cmd+Z inside an OverType editor is left to the textarea, instead of a page-level undo that only restored its `data-value`
24
+
3
25
  ## [0.6.2] - 2026-10-03
4
26
 
5
27
  ### Fixed
@@ -1 +1 @@
1
- var hyperundo=(()=>{var T=Object.defineProperty;var se=Object.getOwnPropertyDescriptor;var ue=Object.getOwnPropertyNames;var le=Object.prototype.hasOwnProperty;var de=(e,t)=>{for(var r in t)T(e,r,{get:t[r],enumerable:!0})},ce=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of ue(t))!le.call(e,o)&&o!==r&&T(e,o,{get:()=>t[o],enumerable:!(n=se(t,o))||n.enumerable});return e};var fe=e=>ce(T({},"__esModule",{value:!0}),e);var xe={};de(xe,{default:()=>ke,undo:()=>I});function pe(e,t=null){let r=[];if(e.type==="attributes"){let n=e.target,o=e.attributeName,a=e.oldValue,u=n.getAttribute(o);return a==null&&u!=null?r.push({kind:"attr-add",target:n,name:o,newValue:u}):a!=null&&u==null?r.push({kind:"attr-remove",target:n,name:o,oldValue:a}):a!==u&&r.push({kind:"attr-set",target:n,name:o,oldValue:a,newValue:u}),r}if(e.type==="characterData")return r.push({kind:"text",target:e.target,oldValue:e.oldValue,newValue:e.target.data}),r;if(e.type==="childList"){let n=e.target,o=e.nextSibling,a=e.nextSibling;for(;a&&t?.(a);)a=a.nextSibling;let u=e.previousSibling;for(;u&&t?.(u);)u=u.previousSibling;let l=t?Array.from(e.addedNodes).filter(p=>!t(p)):Array.from(e.addedNodes),d=t?Array.from(e.removedNodes).filter(p=>!t(p)):Array.from(e.removedNodes);return l.length>0&&r.push({kind:"add",parent:n,nodes:l,before:o,afterAuthored:a,beforeAuthored:u}),d.length>0&&r.push({kind:"remove",parent:n,nodes:d,before:o,afterAuthored:a,beforeAuthored:u}),r}return r}function D(e,t=null){let r=[],n=new Map;for(let o of e){if(o.type==="attributes"){let a=o.target,u=o.attributeName,l=n.get(a);l||(l=new Map,n.set(a,l)),l.has(u)||(l.set(u,{idx:r.length,oldValue:o.oldValue}),r.push(null));continue}for(let a of pe(o,t))r.push(a)}for(let[o,a]of n)for(let[u,l]of a){let d=l.oldValue,p=o.getAttribute(u),m=null;d===p?m=null:d==null?m={kind:"attr-add",target:o,name:u,newValue:p}:p==null?m={kind:"attr-remove",target:o,name:u,oldValue:d}:m={kind:"attr-set",target:o,name:u,oldValue:d,newValue:p},r[l.idx]=m}return r.filter(o=>o!=null)}function j(e){switch(e.kind){case"attr-set":case"attr-add":e.target.setAttribute(e.name,e.newValue);return;case"attr-remove":e.target.removeAttribute(e.name);return;case"text":e.target.data=e.newValue;return;case"value":e.write?e.write(e.target,e.newValue):e.target[e.prop]=e.newValue;return;case"add":M(e);return;case"remove":for(let t of e.nodes)t.parentNode===e.parent&&e.parent.removeChild(t);return}}function U(e){switch(e.kind){case"attr-set":if(e.target.getAttribute(e.name)!==e.newValue)return;e.target.setAttribute(e.name,e.oldValue);return;case"attr-add":if(e.target.getAttribute(e.name)!==e.newValue)return;e.target.removeAttribute(e.name);return;case"attr-remove":if(e.target.hasAttribute(e.name))return;e.target.setAttribute(e.name,e.oldValue);return;case"text":if(e.target.data!==e.newValue)return;e.target.data=e.oldValue;return;case"value":if((e.read?e.read(e.target):e.target[e.prop])!==e.newValue)return;e.write?e.write(e.target,e.oldValue):e.target[e.prop]=e.oldValue;return;case"add":for(let t of e.nodes)t.parentNode===e.parent&&e.parent.removeChild(t);return;case"remove":M(e);return}}function M(e){if(e.afterAuthored?.parentNode===e.parent){for(let t of e.nodes)e.parent.insertBefore(t,e.afterAuthored);return}if(e.beforeAuthored?.parentNode===e.parent){let t=e.beforeAuthored;for(let r of e.nodes)t.after(r),t=r;return}for(let t of e.nodes)e.before?.parentNode===e.parent?e.parent.insertBefore(t,e.before):e.parent.appendChild(t)}var me=['[src^="chrome-extension://"]','[href^="chrome-extension://"]','[src^="moz-extension://"]','[href^="moz-extension://"]','[src^="safari-web-extension://"]','[href^="safari-web-extension://"]','[id="1p-menu-live-region"]',"com-1password-button","com-1password-menu","com-1password-notification","grammarly-extension","grammarly-desktop-integration","lt-div","lt-card","lt-toolbar","lt-highlighter","[data-lastpass-root]","[data-lastpass-icon-root]","[data-dashlane-shadowhost]","[data-klarna-extension]",'[class*="klarna-extension"]',".skiptranslate","#goog-gt-tt",".goog-te-banner-frame",".goog-te-balloon-frame","style.darkreader","style[data-darkreader-mode]","style[data-darkreader-scheme]","#loom-companion-mv3","loom-container","[ext-id]"],he=["data-grammarly","data-lt","data-1p","data-com-onepassword","data-lastpass","data-lp","data-kwimpala","data-bitwarden","data-bw","data-dashlane","data-np","data-protonpass","data-proton-pass","data-keeper","data-rf","data-roboform","data-honey","data-rakuten","data-capital-one","data-wikibuy","data-klarna","data-darkreader","data-evernote","data-pocket","data-pin"],X=me.join(","),B=new RegExp("^(?:"+he.join("|")+")(?:-|$)");var Se=Object.freeze({data:Object.freeze({tokens:["no-data"],bundles:["editor-ui"]}),save:Object.freeze({tokens:["no-save"],bundles:["editor-ui"]}),snapshot:Object.freeze({tokens:["no-snapshot"],bundles:["editor-ui"]}),watch:Object.freeze({tokens:["no-watch"],bundles:["editor-ui"]}),undo:Object.freeze({tokens:["no-undo"],bundles:["editor-ui"]}),history:Object.freeze({tokens:[],bundles:["editor-ui"]})}),ye=Object.freeze({"editor-ui":Object.freeze(["no-data","no-save","no-snapshot","no-watch","no-undo"])}),ge=Object.freeze(["no-save","no-snapshot","no-trigger-autosave","no-dirty","no-watch","no-undo","no-data","freeze","editor-ui"]);function E(e,t){if(!e||e.nodeType!==1)return!1;let r=e.getAttribute?.("clay");return!!(r&&r.split(/\s+/).includes(t)||e.hasAttribute?.(t))}function N(e,t){if(E(e,t))return!0;for(let[r,n]of Object.entries(ye))if(n.includes(t)&&E(e,r))return!0;return!1}function q(e){return e==="clay"||ge.includes(e)}var we=["mutations-ignore","save-remove","save-ignore","save-freeze","no-undo","no-watch"];function be(){if(typeof window>"u")return null;let e=window.clay?.region||window.hyperclay?.region;return e&&typeof e.resolveRegionPolicy=="function"?e.resolveRegionPolicy:null}function S(e){let t=be();if(t)try{if(!t(e).undoable)return!0}catch{}let r=e&&e.nodeType!==1?e.parentElement:e;if(r&&r.closest&&r.closest(X))return!0;for(;r&&r.nodeType===1;){if(N(r,"no-undo")||N(r,"no-watch"))return!0;for(let n of we)if(E(r,n))return!0;r=r.parentElement}return!1}function Ee(e){let t=e.target,r=t.cloneNode(!1),n=r;for(;t.parentElement;){t=t.parentElement;let o=t.cloneNode(!1);o.appendChild(r),r=o}return e.oldValue==null?n.removeAttribute(e.attributeName):n.setAttribute(e.attributeName,e.oldValue),S(n)}function R(e,t,r){if(r?.type==="attributes"&&q(r.attributeName)){if(S(e)&&Ee(r))return!0}else if(S(e))return!0;if(r&&r.type==="attributes"){if(r.attributeName&&B.test(r.attributeName.toLowerCase()))return!0;if(t)try{if(t(r.attributeName,r.target))return!0}catch{}}return!1}function F(){let e=new Map;function t(o,a){let u=e.get(o);return u||(u=new Set,e.set(o,u)),u.add(a),()=>r(o,a)}function r(o,a){let u=e.get(o);u&&u.delete(a)}function n(o,a){let u=e.get(o);if(u)for(let l of Array.from(u))try{l(a)}catch(d){console.error("[hyper-undo] listener threw",d)}}return{on:t,off:r,emit:n}}var ve={maxHistory:100,idleWindowMs:500,idleLabel:"Edit",ignoreAttribute:null,debug:!1};function O(e){let t={...ve,...e};if(!t.scope)throw new Error("hyper-undo: scope is required");let r=F(),n=[],o=[],a=[],u=null,l=null,d=0,p=!1;function m(...s){t.debug&&console.log("[hyper-undo]",...s)}function Y(){p||(p=!0,l=Z(g),l.observe(t.scope,{childList:!0,attributes:!0,characterData:!0,subtree:!0,attributeOldValue:!0,characterDataOldValue:!0}),m("started"))}function Z(s){let c=typeof document<"u"&&t.scope===document.body,f=typeof window<"u"&&(window.clay?.Mutation||window.hyperclay?.Mutation)||null;return c&&f&&typeof f.createObserver=="function"?(m("sourcing records from the platform Mutation hub (shared observer)"),f.createObserver(s)):new MutationObserver(s)}function v(){p&&(p=!1,l&&(l.disconnect(),l=null),y(),n.length=0,o.length=0,a=[],d=0,m("stopped"))}function P(){let s=t.scope;return!!(s&&s.nodeType===1&&s.isConnected===!1)}function g(s){if(d>0)return;let c=_(s);if(c.length>0){for(let f of c)a.push(f);K()}}function _(s){let c=s.filter(f=>!R(f.target,t.ignoreAttribute,f));return D(c,f=>R(f,t.ignoreAttribute))}function K(){y(),u=setTimeout(L,t.idleWindowMs)}function y(){u!=null&&(clearTimeout(u),u=null)}function L(){if(u=null,a.length===0)return;let s=a;a=[],k(t.idleLabel,s)}function k(s,c){for(n.push({label:s,timestamp:Date.now(),primitives:c}),o.length=0;n.length>t.maxHistory;)n.shift();m("commit",s,"primitives:",c.length),r.emit("commit")}function J(s,c){if(!p)throw new Error("hyper-undo: scope not started");g(l.takeRecords()),w();let f=c();if(f&&typeof f.then=="function")throw new Error("hyper-undo: commit() fn must be synchronous; returned a Promise");if(g(l.takeRecords()),a.length===0){r.emit("commit");return}y();let b=a;a=[],k(s,b)}function Q(s){if(!p)throw new Error("hyper-undo: scope not started");if(!l)return;if(d>1){l.takeRecords();return}w();let c=_(l.takeRecords());c.length!==0&&(y(),k(s,c))}function ee(){l&&l.takeRecords()}function z(s){!p||d>0||!s||(a.push(s),K())}function te(s,{prop:c="value",oldValue:f,newValue:b,read:ae,write:ie}={}){!s||f===b||z({kind:"value",target:s,prop:c,oldValue:f,newValue:b,read:ae,write:ie})}function w(){d===0&&l&&g(l.takeRecords()),a.length!==0&&(y(),L())}function x(){d===0&&l&&g(l.takeRecords()),d++,m("paused",d)}function A(){d!==0&&(d--,d===0&&l&&l.takeRecords(),m("resumed",d))}function re(){if(P()){v();return}w();let s=n.pop();if(s){x();try{for(let c=s.primitives.length-1;c>=0;c--)try{U(s.primitives[c])}catch(f){m("undo primitive failed (continuing)",f)}}finally{A()}o.push(s),m("undo",s.label),r.emit("undo")}}function ne(){if(P()){v();return}w();let s=o.pop();if(s){x();try{for(let c of s.primitives)try{j(c)}catch(f){m("redo primitive failed (continuing)",f)}}finally{A()}n.push(s),m("redo",s.label),r.emit("redo")}}function oe(){l&&l.takeRecords(),n.length=0,o.length=0,a=[],y(),m("cleared"),r.emit("clear")}return{_config:t,start:Y,stop:v,commit:J,commitCaptured:Q,discardCaptured:ee,flush:w,record:z,recordValue:te,undo:re,redo:ne,clear:oe,pause:x,resume:A,on:r.on,off:r.off,get canUndo(){return n.length>0},get canRedo(){return o.length>0},get isPaused(){return d>0},get history(){return n.map(s=>({label:s.label,timestamp:s.timestamp}))},get scope(){return t.scope}}}function W(e,t){let r=n=>{let o=e.scope;if(o&&o.nodeType===1&&o.isConnected===!1){t&&t();return}let a=n.target,u=e._config.shadowKeydownIn;if(a&&a.closest&&Array.isArray(u))for(let p of u)try{if(a.closest(p))return}catch{}if(!(n.metaKey||n.ctrlKey))return;let d=(n.key||"").toLowerCase();if(d==="z"&&!n.shiftKey){n.preventDefault(),n.stopPropagation(),e.undo();return}if(d==="z"&&n.shiftKey){n.preventDefault(),n.stopPropagation(),e.redo();return}if(d==="y"&&!n.shiftKey){n.preventDefault(),n.stopPropagation(),e.redo();return}};return window.addEventListener("keydown",r,!0),()=>window.removeEventListener("keydown",r,!0)}var C=[".CodeMirror",".cm-editor",".monaco-editor",".ace_editor",".ql-editor",".tiptap",".ProseMirror","[data-richclay-active]"],i=null,V=null,$=null,h=null;function H(e,t){if(h){if(h.inst===e)return h.cleanup;throw new Error("hyper-undo: another scope already owns the global Cmd+Z binding (bindKeys: true). Stop it first, or use bindKeys: false for additional scopes.")}let r=W(e,t);return h={inst:e,cleanup:r},r}function G(e){h&&h.inst===e&&(h.cleanup(),h=null)}var I={defaults:{shadowKeydownIn:C},start(e={}){let t=e.scope||(typeof document<"u"?document.body:null);if(!t)throw new Error("hyper-undo: no scope (need document.body or explicit { scope })");if(i){if(V===t)return console.warn("[hyper-undo] start() called again on existing singleton; ignoring new options"),i;throw new Error("hyper-undo: start() called with a different scope while the singleton is already started. Use undo.create({ scope }) for additional scopes, or call undo.stop() first.")}let r={...e,scope:t,shadowKeydownIn:e.shadowKeydownIn||C};return i=O(r),i.start(),V=t,e.bindKeys!==!1&&($=H(i,()=>I.stop())),i},stop(){i&&(G(i),$=null,i.stop(),i=null,V=null)},create(e={}){let t=e.scope||(typeof document<"u"?document.body:null);if(!t)throw new Error("hyper-undo: no scope (need document.body or explicit { scope })");let r={...e,scope:t,shadowKeydownIn:e.shadowKeydownIn||C},n=O(r),o=null,a={_config:n._config,commit:n.commit,commitCaptured:n.commitCaptured,discardCaptured:n.discardCaptured,flush:n.flush,record:n.record,recordValue:n.recordValue,undo:n.undo,redo:n.redo,clear:n.clear,pause:n.pause,resume:n.resume,on:n.on,off:n.off,get canUndo(){return n.canUndo},get canRedo(){return n.canRedo},get isPaused(){return n.isPaused},get history(){return n.history},get scope(){return n.scope},start(){e.bindKeys&&(o=H(n,()=>a.stop())),n.start()},stop(){G(n),o=null,n.stop()}};return a},commit(e,t){return i?i.commit(e,t):void 0},commitCaptured(e){return i?i.commitCaptured(e):void 0},discardCaptured(){return i?i.discardCaptured():void 0},record(e){return i?i.record(e):void 0},recordValue(e,t){return i?i.recordValue(e,t):void 0},undo(){return i?i.undo():void 0},redo(){return i?i.redo():void 0},clear(){return i?i.clear():void 0},pause(){return i?i.pause():void 0},resume(){return i?i.resume():void 0},flush(){return i?i.flush():void 0},on(e,t){return i?i.on(e,t):void 0},off(e,t){return i?i.off(e,t):void 0},get canUndo(){return i?i.canUndo:!1},get canRedo(){return i?i.canRedo:!1},get history(){return i?i.history:[]},get isPaused(){return i?i.isPaused:!1}};var ke=I;return fe(xe);})();
1
+ var hyperundo=(()=>{var T=Object.defineProperty;var se=Object.getOwnPropertyDescriptor;var ue=Object.getOwnPropertyNames;var le=Object.prototype.hasOwnProperty;var de=(e,t)=>{for(var r in t)T(e,r,{get:t[r],enumerable:!0})},ce=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of ue(t))!le.call(e,o)&&o!==r&&T(e,o,{get:()=>t[o],enumerable:!(n=se(t,o))||n.enumerable});return e};var fe=e=>ce(T({},"__esModule",{value:!0}),e);var xe={};de(xe,{default:()=>ke,undo:()=>I});function pe(e,t=null){let r=[];if(e.type==="attributes"){let n=e.target,o=e.attributeName,a=e.oldValue,u=n.getAttribute(o);return a==null&&u!=null?r.push({kind:"attr-add",target:n,name:o,newValue:u}):a!=null&&u==null?r.push({kind:"attr-remove",target:n,name:o,oldValue:a}):a!==u&&r.push({kind:"attr-set",target:n,name:o,oldValue:a,newValue:u}),r}if(e.type==="characterData")return r.push({kind:"text",target:e.target,oldValue:e.oldValue,newValue:e.target.data}),r;if(e.type==="childList"){let n=e.target,o=e.nextSibling,a=e.nextSibling;for(;a&&t?.(a);)a=a.nextSibling;let u=e.previousSibling;for(;u&&t?.(u);)u=u.previousSibling;let l=t?Array.from(e.addedNodes).filter(p=>!t(p)):Array.from(e.addedNodes),d=t?Array.from(e.removedNodes).filter(p=>!t(p)):Array.from(e.removedNodes);return l.length>0&&r.push({kind:"add",parent:n,nodes:l,before:o,afterAuthored:a,beforeAuthored:u}),d.length>0&&r.push({kind:"remove",parent:n,nodes:d,before:o,afterAuthored:a,beforeAuthored:u}),r}return r}function D(e,t=null){let r=[],n=new Map;for(let o of e){if(o.type==="attributes"){let a=o.target,u=o.attributeName,l=n.get(a);l||(l=new Map,n.set(a,l)),l.has(u)||(l.set(u,{idx:r.length,oldValue:o.oldValue}),r.push(null));continue}for(let a of pe(o,t))r.push(a)}for(let[o,a]of n)for(let[u,l]of a){let d=l.oldValue,p=o.getAttribute(u),m=null;d===p?m=null:d==null?m={kind:"attr-add",target:o,name:u,newValue:p}:p==null?m={kind:"attr-remove",target:o,name:u,oldValue:d}:m={kind:"attr-set",target:o,name:u,oldValue:d,newValue:p},r[l.idx]=m}return r.filter(o=>o!=null)}function j(e){switch(e.kind){case"attr-set":case"attr-add":e.target.setAttribute(e.name,e.newValue);return;case"attr-remove":e.target.removeAttribute(e.name);return;case"text":e.target.data=e.newValue;return;case"value":e.write?e.write(e.target,e.newValue):e.target[e.prop]=e.newValue;return;case"add":M(e);return;case"remove":for(let t of e.nodes)t.parentNode===e.parent&&e.parent.removeChild(t);return}}function U(e){switch(e.kind){case"attr-set":if(e.target.getAttribute(e.name)!==e.newValue)return;e.target.setAttribute(e.name,e.oldValue);return;case"attr-add":if(e.target.getAttribute(e.name)!==e.newValue)return;e.target.removeAttribute(e.name);return;case"attr-remove":if(e.target.hasAttribute(e.name))return;e.target.setAttribute(e.name,e.oldValue);return;case"text":if(e.target.data!==e.newValue)return;e.target.data=e.oldValue;return;case"value":if((e.read?e.read(e.target):e.target[e.prop])!==e.newValue)return;e.write?e.write(e.target,e.oldValue):e.target[e.prop]=e.oldValue;return;case"add":for(let t of e.nodes)t.parentNode===e.parent&&e.parent.removeChild(t);return;case"remove":M(e);return}}function M(e){if(e.afterAuthored?.parentNode===e.parent){for(let t of e.nodes)e.parent.insertBefore(t,e.afterAuthored);return}if(e.beforeAuthored?.parentNode===e.parent){let t=e.beforeAuthored;for(let r of e.nodes)t.after(r),t=r;return}for(let t of e.nodes)e.before?.parentNode===e.parent?e.parent.insertBefore(t,e.before):e.parent.appendChild(t)}var me=['[src^="chrome-extension://"]','[href^="chrome-extension://"]','[src^="moz-extension://"]','[href^="moz-extension://"]','[src^="safari-web-extension://"]','[href^="safari-web-extension://"]','[id="1p-menu-live-region"]',"com-1password-button","com-1password-menu","com-1password-notification","grammarly-extension","grammarly-desktop-integration","lt-div","lt-card","lt-toolbar","lt-highlighter","[data-lastpass-root]","[data-lastpass-icon-root]","[data-dashlane-shadowhost]","[data-klarna-extension]",'[class*="klarna-extension"]',".skiptranslate","#goog-gt-tt",".goog-te-banner-frame",".goog-te-balloon-frame","style.darkreader","style[data-darkreader-mode]","style[data-darkreader-scheme]","#loom-companion-mv3","loom-container","[ext-id]"],he=["data-grammarly","data-lt","data-1p","data-com-onepassword","data-lastpass","data-lp","data-kwimpala","data-bitwarden","data-bw","data-dashlane","data-np","data-protonpass","data-proton-pass","data-keeper","data-rf","data-roboform","data-honey","data-rakuten","data-capital-one","data-wikibuy","data-klarna","data-darkreader","data-evernote","data-pocket","data-pin"],X=me.join(","),B=new RegExp("^(?:"+he.join("|")+")(?:-|$)");var Se=Object.freeze({data:Object.freeze({tokens:["no-data"],bundles:["editor-ui"]}),save:Object.freeze({tokens:["no-save"],bundles:["editor-ui"]}),snapshot:Object.freeze({tokens:["no-snapshot"],bundles:["editor-ui"]}),watch:Object.freeze({tokens:["no-watch"],bundles:["editor-ui"]}),undo:Object.freeze({tokens:["no-undo"],bundles:["editor-ui"]}),history:Object.freeze({tokens:[],bundles:["editor-ui"]})}),ye=Object.freeze({"editor-ui":Object.freeze(["no-data","no-save","no-snapshot","no-watch","no-undo"])}),ge=Object.freeze(["no-save","no-snapshot","no-trigger-autosave","no-dirty","no-watch","no-undo","no-data","freeze","editor-ui","live"]);function E(e,t){if(!e||e.nodeType!==1)return!1;let r=e.getAttribute?.("clay");return!!(r&&r.split(/\s+/).includes(t)||e.hasAttribute?.(t))}function N(e,t){if(E(e,t))return!0;for(let[r,n]of Object.entries(ye))if(n.includes(t)&&E(e,r))return!0;return!1}function q(e){return e==="clay"||ge.includes(e)}var we=["mutations-ignore","save-remove","save-ignore","save-freeze","no-undo","no-watch"];function be(){if(typeof window>"u")return null;let e=window.clay?.region||window.hyperclay?.region;return e&&typeof e.resolveRegionPolicy=="function"?e.resolveRegionPolicy:null}function S(e){let t=be();if(t)try{if(!t(e).undoable)return!0}catch{}let r=e&&e.nodeType!==1?e.parentElement:e;if(r&&r.closest&&r.closest(X))return!0;for(;r&&r.nodeType===1;){if(N(r,"no-undo")||N(r,"no-watch"))return!0;for(let n of we)if(E(r,n))return!0;r=r.parentElement}return!1}function Ee(e){let t=e.target,r=t.cloneNode(!1),n=r;for(;t.parentElement;){t=t.parentElement;let o=t.cloneNode(!1);o.appendChild(r),r=o}return e.oldValue==null?n.removeAttribute(e.attributeName):n.setAttribute(e.attributeName,e.oldValue),S(n)}function R(e,t,r){if(r?.type==="attributes"&&q(r.attributeName)){if(S(e)&&Ee(r))return!0}else if(S(e))return!0;if(r&&r.type==="attributes"){if(r.attributeName&&B.test(r.attributeName.toLowerCase()))return!0;if(t)try{if(t(r.attributeName,r.target))return!0}catch{}}return!1}function F(){let e=new Map;function t(o,a){let u=e.get(o);return u||(u=new Set,e.set(o,u)),u.add(a),()=>r(o,a)}function r(o,a){let u=e.get(o);u&&u.delete(a)}function n(o,a){let u=e.get(o);if(u)for(let l of Array.from(u))try{l(a)}catch(d){console.error("[hyper-undo] listener threw",d)}}return{on:t,off:r,emit:n}}var ve={maxHistory:100,idleWindowMs:500,idleLabel:"Edit",ignoreAttribute:null,debug:!1};function O(e){let t={...ve,...e};if(!t.scope)throw new Error("hyper-undo: scope is required");let r=F(),n=[],o=[],a=[],u=null,l=null,d=0,p=!1;function m(...s){t.debug&&console.log("[hyper-undo]",...s)}function Y(){p||(p=!0,l=Z(g),l.observe(t.scope,{childList:!0,attributes:!0,characterData:!0,subtree:!0,attributeOldValue:!0,characterDataOldValue:!0}),m("started"))}function Z(s){let c=typeof document<"u"&&t.scope===document.body,f=typeof window<"u"&&(window.clay?.Mutation||window.hyperclay?.Mutation)||null;return c&&f&&typeof f.createObserver=="function"?(m("sourcing records from the platform Mutation hub (shared observer)"),f.createObserver(s)):new MutationObserver(s)}function v(){p&&(p=!1,l&&(l.disconnect(),l=null),y(),n.length=0,o.length=0,a=[],d=0,m("stopped"))}function P(){let s=t.scope;return!!(s&&s.nodeType===1&&s.isConnected===!1)}function g(s){if(d>0)return;let c=_(s);if(c.length>0){for(let f of c)a.push(f);K()}}function _(s){let c=s.filter(f=>!R(f.target,t.ignoreAttribute,f));return D(c,f=>R(f,t.ignoreAttribute))}function K(){y(),u=setTimeout(L,t.idleWindowMs)}function y(){u!=null&&(clearTimeout(u),u=null)}function L(){if(u=null,a.length===0)return;let s=a;a=[],k(t.idleLabel,s)}function k(s,c){for(n.push({label:s,timestamp:Date.now(),primitives:c}),o.length=0;n.length>t.maxHistory;)n.shift();m("commit",s,"primitives:",c.length),r.emit("commit")}function J(s,c){if(!p)throw new Error("hyper-undo: scope not started");g(l.takeRecords()),w();let f=c();if(f&&typeof f.then=="function")throw new Error("hyper-undo: commit() fn must be synchronous; returned a Promise");if(g(l.takeRecords()),a.length===0){r.emit("commit");return}y();let b=a;a=[],k(s,b)}function Q(s){if(!p)throw new Error("hyper-undo: scope not started");if(!l)return;if(d>1){l.takeRecords();return}w();let c=_(l.takeRecords());c.length!==0&&(y(),k(s,c))}function ee(){l&&l.takeRecords()}function z(s){!p||d>0||!s||(a.push(s),K())}function te(s,{prop:c="value",oldValue:f,newValue:b,read:ae,write:ie}={}){!s||f===b||z({kind:"value",target:s,prop:c,oldValue:f,newValue:b,read:ae,write:ie})}function w(){d===0&&l&&g(l.takeRecords()),a.length!==0&&(y(),L())}function x(){d===0&&l&&g(l.takeRecords()),d++,m("paused",d)}function A(){d!==0&&(d--,d===0&&l&&l.takeRecords(),m("resumed",d))}function re(){if(P()){v();return}w();let s=n.pop();if(s){x();try{for(let c=s.primitives.length-1;c>=0;c--)try{U(s.primitives[c])}catch(f){m("undo primitive failed (continuing)",f)}}finally{A()}o.push(s),m("undo",s.label),r.emit("undo")}}function ne(){if(P()){v();return}w();let s=o.pop();if(s){x();try{for(let c of s.primitives)try{j(c)}catch(f){m("redo primitive failed (continuing)",f)}}finally{A()}n.push(s),m("redo",s.label),r.emit("redo")}}function oe(){l&&l.takeRecords(),n.length=0,o.length=0,a=[],y(),m("cleared"),r.emit("clear")}return{_config:t,start:Y,stop:v,commit:J,commitCaptured:Q,discardCaptured:ee,flush:w,record:z,recordValue:te,undo:re,redo:ne,clear:oe,pause:x,resume:A,on:r.on,off:r.off,get canUndo(){return n.length>0},get canRedo(){return o.length>0},get isPaused(){return d>0},get history(){return n.map(s=>({label:s.label,timestamp:s.timestamp}))},get scope(){return t.scope}}}function W(e,t){let r=n=>{let o=e.scope;if(o&&o.nodeType===1&&o.isConnected===!1){t&&t();return}let a=n.target,u=e._config.shadowKeydownIn;if(a&&a.closest&&Array.isArray(u))for(let p of u)try{if(a.closest(p))return}catch{}if(!(n.metaKey||n.ctrlKey))return;let d=(n.key||"").toLowerCase();if(d==="z"&&!n.shiftKey){n.preventDefault(),n.stopPropagation(),e.undo();return}if(d==="z"&&n.shiftKey){n.preventDefault(),n.stopPropagation(),e.redo();return}if(d==="y"&&!n.shiftKey){n.preventDefault(),n.stopPropagation(),e.redo();return}};return window.addEventListener("keydown",r,!0),()=>window.removeEventListener("keydown",r,!0)}var C=[".CodeMirror",".cm-editor",".monaco-editor",".ace_editor",".ql-editor",".tiptap",".ProseMirror",".overtype-input","[data-richclay-active]"],i=null,V=null,$=null,h=null;function H(e,t){if(h){if(h.inst===e)return h.cleanup;throw new Error("hyper-undo: another scope already owns the global Cmd+Z binding (bindKeys: true). Stop it first, or use bindKeys: false for additional scopes.")}let r=W(e,t);return h={inst:e,cleanup:r},r}function G(e){h&&h.inst===e&&(h.cleanup(),h=null)}var I={defaults:{shadowKeydownIn:C},start(e={}){let t=e.scope||(typeof document<"u"?document.body:null);if(!t)throw new Error("hyper-undo: no scope (need document.body or explicit { scope })");if(i){if(V===t)return console.warn("[hyper-undo] start() called again on existing singleton; ignoring new options"),i;throw new Error("hyper-undo: start() called with a different scope while the singleton is already started. Use undo.create({ scope }) for additional scopes, or call undo.stop() first.")}let r={...e,scope:t,shadowKeydownIn:e.shadowKeydownIn||C};return i=O(r),i.start(),V=t,e.bindKeys!==!1&&($=H(i,()=>I.stop())),i},stop(){i&&(G(i),$=null,i.stop(),i=null,V=null)},create(e={}){let t=e.scope||(typeof document<"u"?document.body:null);if(!t)throw new Error("hyper-undo: no scope (need document.body or explicit { scope })");let r={...e,scope:t,shadowKeydownIn:e.shadowKeydownIn||C},n=O(r),o=null,a={_config:n._config,commit:n.commit,commitCaptured:n.commitCaptured,discardCaptured:n.discardCaptured,flush:n.flush,record:n.record,recordValue:n.recordValue,undo:n.undo,redo:n.redo,clear:n.clear,pause:n.pause,resume:n.resume,on:n.on,off:n.off,get canUndo(){return n.canUndo},get canRedo(){return n.canRedo},get isPaused(){return n.isPaused},get history(){return n.history},get scope(){return n.scope},start(){e.bindKeys&&(o=H(n,()=>a.stop())),n.start()},stop(){G(n),o=null,n.stop()}};return a},commit(e,t){return i?i.commit(e,t):void 0},commitCaptured(e){return i?i.commitCaptured(e):void 0},discardCaptured(){return i?i.discardCaptured():void 0},record(e){return i?i.record(e):void 0},recordValue(e,t){return i?i.recordValue(e,t):void 0},undo(){return i?i.undo():void 0},redo(){return i?i.redo():void 0},clear(){return i?i.clear():void 0},pause(){return i?i.pause():void 0},resume(){return i?i.resume():void 0},flush(){return i?i.flush():void 0},on(e,t){return i?i.on(e,t):void 0},off(e,t){return i?i.off(e,t):void 0},get canUndo(){return i?i.canUndo:!1},get canRedo(){return i?i.canRedo:!1},get history(){return i?i.history:[]},get isPaused(){return i?i.isPaused:!1}};var ke=I;return fe(xe);})();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hyper-undo",
3
- "version": "0.6.2",
3
+ "version": "0.6.4",
4
4
  "description": "DOM-state undo/redo via MutationObserver inverse-op replay. Standalone or paired with hyperclayjs.",
5
5
  "keywords": [
6
6
  "undo",
@@ -55,12 +55,19 @@ export function stripExtensionNoise(root) {
55
55
  // querySelectorAll('*') never returns the root itself, so an extension stamp on
56
56
  // <html> used to ride into every saved file. The root is the one element an
57
57
  // extension can mark on a page with no other match.
58
- for (const el of [root, ...root.querySelectorAll('*')]) {
59
- if (!el.attributes) continue
60
- for (const attr of [...el.attributes]) {
61
- if (EXTENSION_ATTR_PATTERN.test(attr.name.toLowerCase())) el.removeAttribute(attr.name)
58
+ // The attribute list is only copied when a marker is found on it.
59
+ const strip = (el) => {
60
+ const attrs = el.attributes
61
+ if (!attrs) return
62
+ let found = null
63
+ for (let i = 0; i < attrs.length; i++) {
64
+ const name = attrs[i].name
65
+ if (EXTENSION_ATTR_PATTERN.test(name.toLowerCase())) (found || (found = [])).push(name)
62
66
  }
67
+ if (found) for (const name of found) el.removeAttribute(name)
63
68
  }
69
+ strip(root)
70
+ for (const el of root.querySelectorAll('*')) strip(el)
64
71
  } catch (e) {
65
72
  if (typeof console !== 'undefined') console.warn('[hyperclay] stripExtensionNoise skipped:', e)
66
73
  }
package/src/index.js CHANGED
@@ -9,6 +9,10 @@ const DEFAULT_SHADOW_LIST = [
9
9
  '.ql-editor',
10
10
  '.tiptap',
11
11
  '.ProseMirror',
12
+ // OverType's textarea keeps the browser's own undo, and the preview redraws on
13
+ // its input event. hyper-undo's page stack only restores data-value there, so
14
+ // Cmd+Z appeared to do nothing and the next save wrote the un-undone text.
15
+ '.overtype-input',
12
16
  // richclay marks its live region with this and stamps no-undo on it, so the
13
17
  // page-level stack holds no record of what was typed there. Without the
14
18
  // bypass, Cmd+Z inside a richclay editor never reached Squire: it either did
@@ -1,6 +1,6 @@
1
1
  // GENERATED from clayjs/src/lib/content-dom.js. Edit ClayJS and run `npm run propagate:foundation`.
2
2
 
3
- import { capabilitySelector, hasCapability } from './region-capabilities.js'
3
+ import { capabilitySelector, hasCapability, CAPABILITIES, expandsTo, hasPolicyToken } from './region-capabilities.js'
4
4
 
5
5
  const UNSUPPORTED_SELECTOR = /:(?:focus(?:-within|-visible)?|hover|active|visited|defined)\b/i
6
6
 
@@ -9,10 +9,9 @@ function copyControlState(source, copy) {
9
9
  const type = (source.getAttribute?.('type') || '').toLowerCase()
10
10
  if ('value' in source && 'value' in copy && source.tagName !== 'OPTION' && type !== 'checkbox' && type !== 'radio' && type !== 'file') copy.value = source.value
11
11
  if (source.tagName === 'INPUT' && (type === 'checkbox' || type === 'radio')) copy.checked = source.checked
12
+ // Each surviving option carries its own selection, so a <select> whose excluded
13
+ // options were removed from the copy keeps the rest in step with the page.
12
14
  if (source.tagName === 'OPTION') copy.selected = source.selected
13
- if (source.tagName === 'SELECT') {
14
- for (let i = 0; i < source.options.length; i++) copy.options[i].selected = source.options[i].selected
15
- }
16
15
  if ('indeterminate' in source && 'indeterminate' in copy) copy.indeterminate = source.indeterminate
17
16
  }
18
17
 
@@ -27,46 +26,77 @@ function matchesWithin(node, selector, boundary, inherit) {
27
26
  return false
28
27
  }
29
28
 
30
- function importTree(source, targetDocument, capability, capabilityMatch, exclude, boundary, inherit, maps) {
31
- if (source.nodeType === 1 && (
32
- (inherit
33
- ? hasCapability(source, capability)
34
- : matchesWithin(source, capabilityMatch, boundary, false)) ||
35
- (exclude && (inherit && source !== boundary ? source.matches(exclude) : matchesWithin(source, exclude, boundary, inherit)))
36
- )) return null
37
- const copy = targetDocument.importNode(source, false)
29
+ // One native deep clone, then a lockstep walk of the two isomorphic trees that
30
+ // records provenance, collects controls, and marks excluded subtrees for removal.
31
+ // The browser's clone is far cheaper than importing node by node. The root answers
32
+ // for its ancestors once; below it the walk is top-down, so with inheritance each
33
+ // element answers only for its own markers: an excluded ancestor is never entered.
34
+ function excluded(source, capability, capabilityMatch, exclude, boundary, inherit) {
35
+ return (inherit
36
+ ? hasCapability(source, capability)
37
+ : matchesWithin(source, capabilityMatch, boundary, false)) ||
38
+ !!(exclude && (inherit && source !== boundary ? source.matches(exclude) : matchesWithin(source, exclude, boundary, inherit)))
39
+ }
40
+
41
+ // The test closestWithCapability makes at each level, for this element alone.
42
+ function hasOwnCapability(element, capability) {
43
+ const definition = CAPABILITIES[capability]
44
+ return definition.tokens.some(token => expandsTo(element, token)) ||
45
+ definition.bundles.some(bundle => hasPolicyToken(element, bundle))
46
+ }
47
+
48
+ const CONTROL_TAGS = new Set(['INPUT', 'TEXTAREA', 'SELECT', 'OPTION'])
49
+
50
+ function pairTree(source, copy, maps, drop) {
51
+ if (source.nodeType === 1 && drop(source)) { maps.dropped.push(copy); return }
38
52
  maps.cloneToLive.set(copy, source)
39
53
  maps.liveToClone.set(source, copy)
40
- const sourceChildren = source.nodeType === 1 && source.tagName === 'TEMPLATE' ? source.content : source
41
- const copyChildren = copy.nodeType === 1 && copy.tagName === 'TEMPLATE' ? copy.content : copy
42
- if (sourceChildren !== source) {
43
- maps.cloneToLive.set(copyChildren, sourceChildren)
44
- maps.liveToClone.set(sourceChildren, copyChildren)
45
- }
46
- for (const child of sourceChildren.childNodes || []) {
47
- const childCopy = importTree(child, targetDocument, capability, capabilityMatch, exclude, boundary, inherit, maps)
48
- if (childCopy) {
49
- copyChildren.appendChild(childCopy)
50
- if (child.nodeType === 1) copyControlState(child, childCopy)
54
+ let sourceChildren = source
55
+ let copyChildren = copy
56
+ if (source.nodeType === 1) {
57
+ if (CONTROL_TAGS.has(source.tagName)) maps.controls.push(source, copy)
58
+ if (source.tagName === 'TEMPLATE') {
59
+ // The deep clone also copied the template's own child nodes, which are not its
60
+ // content and were never part of the view.
61
+ while (copy.firstChild) copy.removeChild(copy.firstChild)
62
+ sourceChildren = source.content
63
+ copyChildren = copy.content
64
+ maps.cloneToLive.set(copyChildren, sourceChildren)
65
+ maps.liveToClone.set(sourceChildren, copyChildren)
51
66
  }
67
+ } else if (source.nodeType !== 11) return
68
+ let c = copyChildren.firstChild
69
+ for (let s = sourceChildren.firstChild; s && c; s = s.nextSibling) {
70
+ pairTree(s, c, maps, drop)
71
+ c = c.nextSibling
52
72
  }
53
- if (source.nodeType === 1) copyControlState(source, copy)
54
- return copy
55
73
  }
56
74
 
57
- export function createContentView(context, { capability = 'data', exclude = null, inherit = true } = {}) {
75
+ export function createContentView(context, { capability = 'data', exclude = null, inherit = true, provenance = null } = {}) {
58
76
  if (!context) throw new TypeError('createContentView requires a DOM context')
59
77
  const sourceDocument = context.nodeType === 9 ? context : context.ownerDocument
60
78
  if (!sourceDocument?.implementation?.createHTMLDocument) {
61
79
  throw new TypeError('createContentView requires an HTML DOM implementation')
62
80
  }
63
81
  const inertDocument = sourceDocument.implementation.createHTMLDocument('')
64
- const cloneToLive = new WeakMap()
82
+ const cloneToLive = provenance || new WeakMap()
65
83
  const liveToClone = new WeakMap()
66
84
  const sourceRoot = context.nodeType === 9 ? context.documentElement : context
67
85
  if (exclude) inertDocument.documentElement.matches(exclude)
68
86
  const capabilityMatch = capabilitySelector(capability)
69
- const root = importTree(sourceRoot, inertDocument, capability, capabilityMatch, exclude, sourceRoot, inherit, { cloneToLive, liveToClone })
87
+ const drop = inherit
88
+ ? (el) => hasOwnCapability(el, capability) || !!(exclude && el.matches(exclude))
89
+ : (el) => excluded(el, capability, capabilityMatch, exclude, sourceRoot, false)
90
+ let root = null
91
+ if (sourceRoot.nodeType !== 1 || !excluded(sourceRoot, capability, capabilityMatch, exclude, sourceRoot, inherit)) {
92
+ root = inertDocument.importNode(sourceRoot, true)
93
+ const maps = { cloneToLive, liveToClone, dropped: [], controls: [] }
94
+ pairTree(sourceRoot, root, maps, drop)
95
+ for (const node of maps.dropped) node.remove()
96
+ // Control state is copied once the copy holds only what the view keeps, so a
97
+ // <select> sees exactly the options the old node-by-node import gave it.
98
+ for (let i = 0; i < maps.controls.length; i += 2) copyControlState(maps.controls[i], maps.controls[i + 1])
99
+ }
70
100
  if (context.nodeType === 9 && root) {
71
101
  inertDocument.replaceChild(root, inertDocument.documentElement)
72
102
  liveToClone.set(context, inertDocument)
@@ -23,6 +23,7 @@ export const POLICY_TOKENS = Object.freeze([
23
23
  'no-data',
24
24
  'freeze',
25
25
  'editor-ui',
26
+ 'live',
26
27
  ])
27
28
 
28
29
  export function hasPolicyToken(element, token) {