-
Notifications
You must be signed in to change notification settings - Fork 0
/
1629.d39d5bee.iframe.bundle.js
1 lines (1 loc) · 53.7 KB
/
1629.d39d5bee.iframe.bundle.js
1
"use strict";(self.webpackChunkstorybook=self.webpackChunkstorybook||[]).push([[1629],{"../../packages/models/src/workbook/IWorkbookModel.ts":(__unused_webpack_module,__webpack_exports__,__webpack_require__)=>{__webpack_require__.d(__webpack_exports__,{A:()=>SheetVisibility,C:()=>WorkbookFindCellScope});let WorkbookFindCellScope=function(WorkbookFindCellScope){return WorkbookFindCellScope.Workbook="workbook",WorkbookFindCellScope.Sheet="sheet",WorkbookFindCellScope}({}),SheetVisibility=function(SheetVisibility){return SheetVisibility.Visible="visible",SheetVisibility.Hidden="hidden",SheetVisibility.VeryHidden="veryHidden",SheetVisibility}({})},"../../packages/models/src/workbook/WorkbookModel.ts":(__unused_webpack_module,__webpack_exports__,__webpack_require__)=>{__webpack_require__.d(__webpack_exports__,{_:()=>WorkbookModel});var CommonUtils=__webpack_require__("../../packages/common/src/utils/CommonUtils.ts"),Transaction=__webpack_require__("../../packages/models/src/transaction/Transaction.ts"),SheetStyle=__webpack_require__("../../packages/models/src/cell/SheetStyle.ts"),AddressUtils=__webpack_require__("../../packages/models/src/range/AddressUtils.ts"),RangeUtils=__webpack_require__("../../packages/models/src/range/RangeUtils.ts"),RangeCoordsRTree=__webpack_require__("../../packages/models/src/range/RangeCoordsRTree.ts");const MESSAGE_MODEL_CLOSED="NamedItems has been closed. No further operations are allowed.",sortSheetRanges=ranges=>!ranges||ranges.length<=1?ranges:(ranges=[...ranges],RangeUtils.X_(ranges,void 0,((a,b)=>a.sheetName.localeCompare(b.sheetName)))),REGEX_INVALID_NAME_FIRST_CHARS=/^[^a-zA-Z_\\]+$/,REGEX_INVALID_NAME_TRAILING_CHARS=/^[^a-zA-Z0-9_.]+$/;class NamedItems{_listeners=new Set;_closed=!1;constructor(options){this._options={...options};const _self=this;this._transactionStore=this._options.transactionStore??new Transaction.ys,this._transactionStoreRemoveListener=this._transactionStore.addChangeSetListener(this,{onRecordChange(_change){_self.notifyNamedItemsChange()}}),this._fromJSON(this._options?.initialJSON)}search(options){const state=this._getTransactionState();if(!state)return CommonUtils.Ml;const namedRanges=options?.bounds?state.itemsByBounds.search(options.bounds):state.itemsByBounds.all();if(!namedRanges||0===namedRanges.length)return CommonUtils.Ml;const mapScoped=new Set,mapGlobal=new Set;namedRanges.forEach((entry=>{const namedRange=entry.value;options?.type&&namedRange.type!==options.type||namedRange.ref&&0!==namedRange.ref.length&&(!1!==options?.allowExtrudes||RangeUtils.mT(entry,options.bounds))&&(!options?.scope||namedRange.scope!==options.scope&&"all"!==options.scope?namedRange.scope||mapGlobal.add(namedRange):mapScoped.add(namedRange))}));const mapRetValue=new Map;mapGlobal.forEach((namedRange=>{mapRetValue.set(namedRange.name,namedRange)})),mapScoped.forEach((namedRange=>{mapRetValue.set(namedRange.name,namedRange)}));let retValue=[];return mapRetValue.forEach((namedRange=>{retValue.push(namedRange)})),retValue=retValue.sort(((a,b)=>{let retValue=a.type.localeCompare(b.type);return 0!==retValue?retValue:a.name.localeCompare(b.name)})),retValue}lookupByName(name,anchor){if(!name)return null;const state=this._getTransactionState();if(!state)return null;if(0===state.itemsByKey.size)return null;if("string"!=typeof name)return null;const asGlobalKey=name.toLowerCase();if(anchor?.sheetName){const scopedKey=asGlobalKey+":"+anchor.sheetName.toLowerCase(),foundScoped=state.itemsByKey.get(scopedKey);if(foundScoped)return foundScoped.item}const found=state.itemsByKey.get(asGlobalKey);return found?.item??null}lookupByRanges(ranges){if(!ranges||0===ranges.length)return null;const state=this._getTransactionState();if(!state)return null;if(0===state.itemsByKey.size)return null;const sorted=sortSheetRanges(ranges);let asRangesString="";for(let i=0;i<sorted.length;i++)asRangesString+=this._options.encodeAddress(sorted[i]),i<sorted.length-1&&(asRangesString+=",");const asLowerCase=asRangesString.toLowerCase(),foundNames=state.itemsByFullRange.get(asLowerCase);if(!foundNames)return null;const retValue=[];return foundNames.forEach((name=>{const found=state.itemsByKey.get(name);found&&retValue.push(found.item)})),retValue.length>0?retValue:null}decodeAddress(address){return this._options.decodeAddress(address)}findValidateName(ranges,scope=null,template,replaceHidden=!0){ranges&&ranges.length,template||(template="Range_1");const _self=this,isValidName=candidate=>{try{return _self.validateNamedItem({name:candidate},scope,replaceHidden),!0}catch(error){}return!1};if(isValidName(template))return template;let index,token=new RegExp(/.(\d+)$/,"g").exec(template),newName=null;null!==token?(newName=template.substring(0,token.index),index=parseFloat(token[1])):index=1;let initialIndex=index;for(;index<initialIndex+1e3;){index++;const candidate=newName+"_"+index;try{if(isValidName(candidate))return candidate}catch(error){}}throw new Error(`Unable to find valid name for '${template}'.`)}validateNamedItem(namedRangeItem,scope=null,replaceHidden=!0){if(!namedRangeItem)throw new Error("No sheet range specified.");namedRangeItem.name&&this._validateRangeName(namedRangeItem.name,scope,replaceHidden),namedRangeItem.ref&&this._validateSheetAddress(namedRangeItem.ref)}_validateSheetAddress(address){if("string"==typeof address){if(!this.decodeAddress(address))throw new Error(`Invalid address '${address}'.`)}}_validateRangeName(name,scope,replaceHidden=!0){if(this._closed)throw new Error(MESSAGE_MODEL_CLOSED);if(!name||0===name.length)throw new Error("Name must be a non-empty string");if(name.length>255)throw new Error("Name must not exceed 255 characters.");if(-1!==name.indexOf(" "))throw new Error("Name must not contain any spaces.");const asTrimmed=name.trim().toLowerCase(),trailing=asTrimmed.substring(1,name.length-1);if(new RegExp(REGEX_INVALID_NAME_FIRST_CHARS).test(asTrimmed[0]))throw new Error("First letter must be either a letter, an underscore, or a backslash.");if(new RegExp(REGEX_INVALID_NAME_TRAILING_CHARS).test(trailing))throw new Error("Name must be either letters, numbers, periods or underscores.");if(1===asTrimmed.length&&("r"===asTrimmed[0]||"c"===asTrimmed[0]))throw new Error("Name can not be 'r' or 'c'.");if(this._options.decodeAddress(name))throw new Error(`'${name}' can not be an address.`);let asGlobalKey=name.toLowerCase()?.trim();scope&&(asGlobalKey=asGlobalKey+":"+scope.toLowerCase());const existing=this._getTransactionState()?.itemsByKey.get(asGlobalKey);if(existing&&(!replaceHidden||existing.item.ref||existing.item.ref?.length>0))throw new Error(`Named range '${name}' already exists${scope?`in scope ${scope}`:""}.`)}addNamedRange(namedRange,replaceHidden=!0){if(this._closed)throw new Error(MESSAGE_MODEL_CLOSED);namedRange?"string"==typeof namedRange&&(namedRange={name:namedRange}):namedRange={};const asNamedRange={...namedRange,type:"sheet"};asNamedRange.name||(asNamedRange.name=this.findValidateName(asNamedRange.ref,asNamedRange.scope,asNamedRange.name,replaceHidden)),this._validateRangeName(asNamedRange.name,asNamedRange.scope,replaceHidden);const transFromJSON=this._pushTransaction("Add Named Range"),ranges=this._addNamedItems([asNamedRange]);if(null===ranges)return null;const rangeAdded=ranges.itemsByKey.get(asNamedRange.name.toLowerCase()),_self=this;return this._updateTransactionState((prev=>({...prev,...ranges})),(prev=>{const sheet=_self._options?.workbook?.getSheet();let selectionView=null;return sheet&&(selectionView={sheet,view:sheet.getView(),selection:Object.freeze(sheet.getView().selection)}),{...prev,...ranges,selectionView}})),transFromJSON.commit(),rangeAdded?.item??null}updateNamedRange(name,namedRange){if(!namedRange||!namedRange.name)throw new Error("Range is not correctly formatted.");if(this._closed)throw new Error(MESSAGE_MODEL_CLOSED);const transFromJSON=this._pushTransaction("Update Named Range");let asGlobalKey=name.toLowerCase()?.trim();namedRange.scope&&(asGlobalKey=asGlobalKey+":"+namedRange.scope.toLowerCase());let existing=this._getTransactionState()?.itemsByKey.get(asGlobalKey);if(!existing)throw new Error(`Range '${name}' does not exist. Use add instead.`);if("sheet"!==existing.item.type)throw new Error("Only Named Ranges can be updated.");this.deleteNamedRange(existing.item),this.addNamedRange(namedRange);const rangeUpdated=this._getTransactionState()?.itemsByKey.get(asGlobalKey);return transFromJSON.commit(),rangeUpdated?.item??null}deleteNamedRange(namedRange){if(!namedRange)throw new Error("Name must be specified.");if(this._closed)throw new Error(MESSAGE_MODEL_CLOSED);"string"==typeof namedRange&&(namedRange={name:namedRange});const asNamedRange={...namedRange,type:"sheet"},transFromJSON=this._pushTransaction("Remove Named Range"),itemsByKey=this._getTransactionState()?.itemsByKey??new Map;let asGlobalKey=asNamedRange.name.toLowerCase(),itemEntry=null;if(asNamedRange.scope){const scopedKey=asGlobalKey+":"+asNamedRange.scope.toLowerCase();itemEntry=itemsByKey.get(scopedKey),itemEntry&&(asGlobalKey=scopedKey)}if(itemEntry||(itemEntry=itemsByKey.get(asGlobalKey)),!itemEntry)throw new Error(`Range '${asNamedRange.name}' does not exist.`);if("sheet"!==itemEntry.item.type)throw new Error("Only Named Ranges can be removed.");const itemsByBounds=this._getTransactionState()?.itemsByBounds??new RangeCoordsRTree.m,itemsByFullRange=this._getTransactionState()?.itemsByFullRange??new Map,itemsByPartialRange=this._getTransactionState()?.itemsByPartialRange??new Map,listenersByName=this._getTransactionState()?.listenersByName??new Map,itemsByKeyWrite=new Map(itemsByKey),itemsByBoundsWrite=itemsByBounds.clone(),itemsByFullRangeWrite=new Map(itemsByFullRange),itemsByPartialRangeWrite=new Map(itemsByPartialRange),listenersByNameWrite=new Map(listenersByName);this._indexRange(asGlobalKey,null,itemsByKeyWrite,itemsByBoundsWrite,itemsByFullRangeWrite,itemsByPartialRangeWrite);const handlers=listenersByNameWrite.get(asGlobalKey);if(handlers){for(let i=0;i<handlers.length;i++)handlers[i].unwatch();listenersByNameWrite.delete(asGlobalKey)}return this._updateTransactionState((prev=>({...prev,itemsByKey:itemsByKeyWrite,itemsByBounds:itemsByBoundsWrite,itemsByFullRange:itemsByFullRangeWrite,itemsByPartialRange:itemsByPartialRangeWrite,listenersByName:listenersByNameWrite})),(prev=>({...prev,itemsByKey:itemsByKeyWrite,itemsByBounds:itemsByBoundsWrite,itemsByFullRange:itemsByFullRangeWrite,itemsByPartialRange:itemsByPartialRangeWrite,listenersByName:listenersByNameWrite}))),transFromJSON.commit(),this.notifyNamedItemsChange(),itemEntry.item}_indexRange(key,newRange,itemsByKey,itemsByBounds,itemsByFullRange,itemsByPartialRange){const refKeys=ref=>{let asFullRange="",asPartialRanges=[],asRanges=[];const refsSorted=sortSheetRanges(Array.isArray(ref)?ref:[ref]);for(let i=0;i<refsSorted.length;i++){asRanges.push(refsSorted[i]);const asRangeString=this._options.encodeAddress(refsSorted[i]).toLowerCase();asPartialRanges.push(asRangeString),asFullRange+=asRangeString,i<refsSorted.length-1&&(asFullRange+=",")}return{asFullRange,asPartialRanges,asRanges}},original=itemsByKey.get(key);if(original){const{asFullRange,asPartialRanges}=refKeys(original.item.ref);for(let i=0;i<asPartialRanges.length;i++){const setPartial=itemsByPartialRange.get(asPartialRanges[i]);if(setPartial)if(1===setPartial.size)itemsByPartialRange.delete(asPartialRanges[i]);else{const clonedSetPartial=new Set(setPartial);clonedSetPartial.delete(key),itemsByPartialRange.set(asPartialRanges[i],clonedSetPartial)}}if(original.nodes)for(let i=0;i<original.nodes.length;i++)itemsByBounds.remove(original.nodes[i]);const setFull=itemsByFullRange.get(asFullRange);if(setFull)if(1===setFull.size)itemsByFullRange.delete(asFullRange);else{const clonedSetFull=new Set(setFull);clonedSetFull.delete(key),itemsByFullRange.set(asFullRange,clonedSetFull)}itemsByKey.delete(key)}if(newRange){const{asFullRange,asPartialRanges,asRanges}=refKeys(newRange.ref);let nodes=[];for(let i=0;i<asPartialRanges.length;i++){let setPartial=itemsByPartialRange.get(asPartialRanges[i]);const setPartialWrite=setPartial?new Set(setPartial):new Set;setPartialWrite.add(key),itemsByPartialRange.set(asPartialRanges[i],setPartialWrite),nodes.push({...asRanges[i],value:newRange})}if(itemsByBounds.load(nodes),asFullRange){let setFull=itemsByFullRange.get(asFullRange);const setFullWrite=setFull?new Set(setFull):new Set;setFullWrite.add(key),itemsByFullRange.set(asFullRange,setFullWrite),itemsByKey.set(key,{item:newRange,nodes})}}}_addNamedItems(ranges){if(this._closed)throw new Error(MESSAGE_MODEL_CLOSED);const itemsByKey=this._getTransactionState()?.itemsByKey??new Map,itemsByBounds=this._getTransactionState()?.itemsByBounds??new RangeCoordsRTree.m,itemsByFullRange=this._getTransactionState()?.itemsByFullRange??new Map,itemsByPartialRange=this._getTransactionState()?.itemsByPartialRange??new Map,listenersByName=this._getTransactionState()?.listenersByName??new Map;if(!ranges)return{itemsByKey,itemsByBounds,itemsByFullRange,itemsByPartialRange,listenersByName};const itemsByKeyWrite=new Map(itemsByKey),itemsByBoundsWrite=itemsByBounds.clone(),itemsByFullRangeWrite=new Map(itemsByFullRange),itemsByPartialRangeWrite=new Map(itemsByPartialRange),listenersByNameWrite=new Map(listenersByName);for(let i=0;i<ranges.length;i++){const range=ranges[i],name=range.name;let asGlobalKey=name.toLowerCase();try{let asNamedItem=null;asNamedItem="string"==typeof range?{ref:range}:range,asNamedItem.type="sheet",asNamedItem.name=name,"string"==typeof asNamedItem.ref&&(asNamedItem.ref=this.decodeAddress(asNamedItem.ref)),asNamedItem.scope&&(asGlobalKey=asGlobalKey+":"+asNamedItem.scope.toLowerCase());const handlers=[],addListener=(name,originalRefPart,index)=>{const unwatch=this._options.addRangeListener(originalRefPart,(event=>{const range=event.getRange(),handlersWrite=[...this._getTransactionState().listenersByName.get(name)],handler=handlersWrite[index],handlerWrite={...handler};handlersWrite[index]=handlerWrite;const rangeBounds=range.bounds();handlerWrite.refPart=rangeBounds;const originalRangePartial=this._options.encodeAddress(handler.refPart).toLowerCase(),originalPartialRanges=this._getTransactionState()?.itemsByPartialRange,originalSet=originalPartialRanges.get(originalRangePartial);if(!originalSet)return;if(!originalSet.has(asGlobalKey))return;const originalItemsByKey=this._getTransactionState()?.itemsByKey,originalItem=originalItemsByKey?.get(asGlobalKey)?.item;if(!originalItem)return void console.warn("this should never occur");const newItem={...originalItem};newItem.ref=[];for(let i=0;i<handlersWrite.length;i++)handlersWrite[i].refPart&&newItem.ref.push(handlersWrite[i].refPart);const listenersByNameWrite=new Map(listenersByName);listenersByNameWrite.set(name,handlersWrite);const itemsByKeyWriteListener=new Map(originalItemsByKey),itemsByBoundsWriteListener=this._getTransactionState()?.itemsByBounds.clone(),itemsByFullRangeWriteListener=new Map(this._getTransactionState()?.itemsByFullRange),itemsByPartialRangeWriteListener=new Map(originalPartialRanges);this._indexRange(asGlobalKey,newItem,itemsByKeyWriteListener,itemsByBoundsWriteListener,itemsByFullRangeWriteListener,itemsByPartialRangeWriteListener),this._updateTransactionState((prev=>({...prev,itemsByKey:itemsByKeyWriteListener,itemsByBounds:itemsByBoundsWriteListener,itemsByFullRange:itemsByFullRangeWriteListener,itemsByPartialRange:itemsByPartialRangeWriteListener,listenersByName:listenersByNameWrite})),(prev=>({...prev,itemsByKey})))}),{withinTransaction:!0,ignoreCellUpdates:!0});return{unwatch,refPart:originalRefPart}};if(Array.isArray(asNamedItem.ref))for(let i=0;i<asNamedItem.ref.length;i++)handlers.push(addListener(asGlobalKey,asNamedItem.ref[i],i));else asNamedItem.ref&&handlers.push(addListener(asGlobalKey,asNamedItem.ref,0));this._indexRange(asGlobalKey,asNamedItem,itemsByKeyWrite,itemsByBoundsWrite,itemsByFullRangeWrite,itemsByPartialRangeWrite),listenersByNameWrite.set(asGlobalKey,handlers)}catch(error){}}return{itemsByKey:itemsByKeyWrite,itemsByBounds:itemsByBoundsWrite,itemsByFullRange:itemsByFullRangeWrite,itemsByPartialRange:itemsByPartialRangeWrite,listenersByName:listenersByNameWrite}}pushTransaction(description){return this._pushTransaction(description)}_getTransactionState(){if(this._closed)throw new Error(MESSAGE_MODEL_CLOSED);return this._transactionStore.peekTransaction().getState(this)}_pushTransaction(description){return this._transactionStore.pushTransaction(description)}_updateTransactionState(state,inputs){if(!state)return;this._transactionStore.peekTransaction().updateState({record:this,state,inputs})}notifyNamedItemsChange(){const _self=this;this._listeners.forEach((listener=>{listener.onNamedItemsChange?.(_self)}))}notifyOnClose(){const _self=this;this._listeners.forEach((listener=>{listener.onClose?.(_self)}))}fromJSON(json){if(this._closed)throw new Error(MESSAGE_MODEL_CLOSED);this._fromJSON(json)}_fromJSON(json){const transFromJSON=this._pushTransaction("Load Named Ranges"),ranges=this._addNamedItems(json);this._updateTransactionState((prev=>({...prev,...ranges})),(prev=>({...prev,...ranges}))),transFromJSON.commit()}toJSON(){const state=this._getTransactionState();if(!state||0===state.itemsByKey.size)return null;const definedNames=[],keys=Array.from(state.itemsByKey.keys()).sort();for(let i=0;i<keys.length;i++){const namedRange=state.itemsByKey.get(keys[i]).item;if("sheet"!==namedRange.type)return;const asNamedItemJSON={...namedRange};if(delete asNamedItemJSON.type,asNamedItemJSON.ref){let asRangesString="";for(let i=0;i<asNamedItemJSON.ref.length;i++){const ref=asNamedItemJSON.ref[i];asRangesString+=this._options.encodeAddress(ref),i<asNamedItemJSON.ref.length-1&&(asRangesString+=",")}asNamedItemJSON.ref=asRangesString}definedNames.push(asNamedItemJSON)}return definedNames}addListener(listener){const listeners=this._listeners;return listeners.add(listener),()=>{listeners.delete(listener)}}isClosed(){return this._closed}close(){this._closed||(this.notifyOnClose(),this._closed=!0,this._listeners.clear(),this._transactionStore.clear(this),this._transactionStoreRemoveListener?.())}get isNamedItems(){return!0}}var SharedResource=__webpack_require__("../../packages/models/src/resource/SharedResource.ts"),ISheetModel=__webpack_require__("../../packages/models/src/sheet/ISheetModel.ts"),IWorkbookModel=__webpack_require__("../../packages/models/src/workbook/IWorkbookModel.ts"),SheetModel=__webpack_require__("../../packages/models/src/sheet/SheetModel.ts"),DocThemes=__webpack_require__("../../packages/models/src/theme/DocThemes.ts");const defaultWorkbookView={showFormulaBar:!0,showTabs:!0,tabRatio:600,showHorizontalScrollbar:!0,showVerticalScrollbar:!0,showStatusBar:!0,activeSheetId:null};const workbook_WorkbookView=class WorkbookView{_listeners=new Set;constructor(json={}){this.fromJSON(json)}get showFormulaBar(){return this._state.showFormulaBar}set showFormulaBar(newValue){this._state.showFormulaBar=newValue,this.notifyListeners()}get showTabs(){return this._state.showTabs}set showTabs(newValue){this._state.showTabs=newValue,this.notifyListeners()}get tabRatio(){return this._state.tabRatio}set tabRatio(newValue){this._state.tabRatio=newValue,this.notifyListeners()}get showHorizontalScrollbar(){return this._state.showHorizontalScrollbar}set showHorizontalScrollbar(newValue){this._state.showHorizontalScrollbar=newValue,this.notifyListeners()}get showVerticalScrollbar(){return this._state.showVerticalScrollbar}set showVerticalScrollbar(newValue){this._state.showVerticalScrollbar=newValue,this.notifyListeners()}get showStatusBar(){return this._state.showStatusBar}set showStatusBar(newValue){this._state.showStatusBar=newValue,this.notifyListeners()}get activeSheetId(){return this._state.activeSheetId}set activeSheetId(newValue){this._state.activeSheetId=newValue,this.notifyListeners()}notifyListeners(update=void 0){const _self=this;this._listeners.forEach((listener=>{listener.onViewChange?.(update||_self)}))}addListener(listener){const listeners=this._listeners;return listeners.add(listener),()=>{listeners.delete(listener)}}toJSON(){let json={};const keys=Object.keys(this._state);for(let k=0;k<keys.length;k++){const value=this._state[keys[k]];null!=value&&value!==defaultWorkbookView[keys[k]]&&(json[keys[k]]=value)}return 0===Object.keys(json).length&&(json=null),json}fromJSON(json,notify=!0){let view=json||{};this.update(view,notify)}update(view,notify=!0){this._state={...defaultWorkbookView,...this._state,...view},notify&&this.notifyListeners()}};var WorkbookUtils=__webpack_require__("../../packages/models/src/workbook/WorkbookUtils.ts");const MESSAGE_ERROR_INVALID_SHEET_KEY=key=>`Invalid SheetKey: ${key}`,MESSAGE_ERROR_SHEET_ONE="A workbook must contain at least one visible worksheet.",WorkbookModel_MESSAGE_MODEL_CLOSED="Workbook has been closed. No further operations are allowed.",MESSAGE_ERROR_SHEET_NOT_FOUND=sheetName=>`Sheet '${sheetName}' not found.`,DEFAULT_SHEET_NAME_CREATOR=index=>`Sheet${index}`,MESSAGE_ERROR_PROTECTION="This workbook structure is protected. To make a change, unprotect the workbook. You might be requested to enter a password.";class WorkbookModel{_namedRanges=null;_is1904DateSystem=!1;_closed=!1;_sheetsCreated=new Set;constructor(initialState,options){const _self=this;this._options={...options},this._theme=this._options.theme??DocThemes.I6.getDefaultTheme(),this._sheetStyle=this._options?.sheetStyle??new SheetStyle.l(this._theme),this._sheetStyle.getTheme()||this._sheetStyle.setTheme(this.getTheme()),this._transactionStore=this._options.transactionStore??new Transaction.ys,this._sharedResources=this._options.sharedResources??new SharedResource.M,this._sheetNameCreator=this._options.sheetNameCreator??DEFAULT_SHEET_NAME_CREATOR;let sheetCreatorCallback=this._options.sheetCreator;sheetCreatorCallback||(sheetCreatorCallback=(_name,initialStateSheet,optionsSheet)=>{const sheet=new SheetModel.A(initialStateSheet,optionsSheet);return _self._sheetsCreated.add(sheet),sheet}),this._sheetCreator=(name,initialStateSheet,optionsSheet)=>{const optionsSheetFromWB={isDate1904System:_self.is1904DateSystem(),transactionStore:_self._transactionStore,sheetStyle:_self._sheetStyle,sharedResources:_self._sharedResources,...optionsSheet,getName:model=>_self._refsByInstance.get(model)?.name??null,onBeforeDelete:model=>{_self._validateDeleteSheet(model)}};return(this._options.maxColumns||optionsSheet?.maxColumns)&&(optionsSheetFromWB.maxColumns=Math.min(this._options?.maxColumns??optionsSheet?.maxColumns??Number.MAX_SAFE_INTEGER)),(this._options.maxRows||optionsSheet?.maxRows)&&(optionsSheetFromWB.maxRows=Math.min(options.maxRows??optionsSheet?.maxRows??Number.MAX_SAFE_INTEGER)),sheetCreatorCallback(name,initialStateSheet,optionsSheetFromWB)},this._listeners=new Set,this._listenersSheets=new Map,this._namedRanges=new NamedItems({decodeAddress:address=>{const template={..._self.getSheet().getMaxCellBounds(),sheetName:_self.getSheetNames()[_self.getActiveSheetIndex()],fixedColStart:!0,fixedRowStart:!0,fixedColEnd:!0,fixedRowEnd:!0};return address?WorkbookUtils.ak(address,template,null,!0):WorkbookUtils.Kb(_self.getSheet().getView().selection,template)},encodeAddress:address=>{const defaultSheetRange={..._self.getSheet().getMaxCellBounds(),sheetName:_self.getSheet().getName(),fixedColStart:!0,fixedRowStart:!0,fixedColEnd:!0,fixedRowEnd:!0};let retValue=null;return retValue=address?AddressUtils.UC(address,defaultSheetRange):AddressUtils.Ey,retValue},addRangeListener:_self.addRangeListener.bind(_self),transactionStore:_self._transactionStore,workbook:_self}),Array.isArray(initialState)&&(initialState={values:initialState}),initialState?.values?this._fromJSON(null,initialState):this._fromJSON(initialState)}_initialize(){this._listenersSheets.forEach((removeListener=>{removeListener()})),this._listenersSheets.clear(),this._sheetRefsAll=[],this._sheetRefsVisibleAndHidden=[],this._sheetRefsVisible=[],this._refsById=new Map,this._sheetsById=new Map,this._refsByLowerCaseName=new Map,this._sheetsByLowerCaseName=new Map,this._refsByInstance=new Map,this._lastId=0,this._is1904DateSystem=this._options.isDate1904System??!1,this._theme=this._options.theme??DocThemes.I6.getDefaultTheme(),this._activeSheetOffset=0,this._sheetNames=[],this.setView(new workbook_WorkbookView);const _self=this;this._transactionStoreRemoveListener=this._transactionStore.addChangeSetListener(this,{onBeforeRecordChange(_uuid){},onRecordChange(_change,_description,_record,_isUndo){_self.notifyAllChange()}});const trans=this._pushTransaction("Load Workbook");this._updateTransactionState((prev=>({...prev,listenerRanges:new Set}))),trans.commit()}getView(){return this._view}setView(view){if(this._closed)throw new Error(WorkbookModel_MESSAGE_MODEL_CLOSED);if(!view)throw new Error("View can not be empty.");this._listenerWorkbookView?.(),this._listenerWorkbookView=view.addListener({onViewChange:update=>{this._activeSheetOffset=this._findOffsetForId(this._view.activeSheetId,this._sheetRefsVisible),this.notifyViewChange(update)}}),this._view=view,this.notifyViewChange(this._view)}is1904DateSystem(){return this._is1904DateSystem}set1904DateSystem(is1904Date){if(this._closed)throw new Error(WorkbookModel_MESSAGE_MODEL_CLOSED);this._is1904DateSystem=is1904Date,this.notifyAllChange()}sheetStyle(){return this._sheetStyle}getResources(){return this._sharedResources}getTheme(){return this._theme}getTransactionStore(){return this._transactionStore}setTheme(theme){if(this._closed)throw new Error(WorkbookModel_MESSAGE_MODEL_CLOSED);if(!theme)throw new Error("A value must be provided.");const retValue=this._theme;return this._theme=theme,this.sheetStyle().setTheme(theme),this.notifyThemeChange(theme),retValue}getSheetRefs(visibility=IWorkbookModel.A.Visible){return this._closed?[]:visibility===IWorkbookModel.A.Visible?this._sheetRefsVisible:visibility===IWorkbookModel.A.Hidden?this._sheetRefsVisibleAndHidden:visibility===IWorkbookModel.A.VeryHidden?this._sheetRefsAll:[]}getSheet(key){return this._closed?null:this.getSheetRef(key??this.getActiveSheetIndex())?.sheet??null}getSheetRef(key,visibility=IWorkbookModel.A.Visible){let retValue=null;return"number"==typeof key?visibility===IWorkbookModel.A.Visible?retValue=this._sheetRefsVisible[key]:visibility===IWorkbookModel.A.Hidden?retValue=this._sheetRefsVisibleAndHidden[key]:visibility===IWorkbookModel.A.VeryHidden&&(retValue=this._sheetRefsAll[key]):"string"==typeof key?retValue=this._refsByLowerCaseName.get(key.toLowerCase()):key instanceof SheetModel.A?retValue=this._refsByInstance.get(key):key?.id&&key.sheet&&(retValue=this._refsById.get(key.id)),retValue}getSheetRefById(id){const retValue=this._refsById.get(id);if(!retValue)throw new Error((id=>`Invalid id: ${id}`)(id));return retValue}_validateSheetName(sheetName,checkDuplicates=!0){if(null==sheetName)return sheetName;if(RangeUtils.fZ(sheetName),checkDuplicates&&this._sheetsByLowerCaseName.has(sheetName.toLowerCase()))throw new Error("That name is already taken. Try a different one.");return sheetName.substring(0,31)}getSheetNames(){return this._sheetNames}findValidSheetName(str){try{if(this._validateSheetName(str))return str}catch(error){}let template,index,token=new RegExp(RangeUtils.xg,"g").exec(str);for(null!==token?(template=str.substring(0,token.index),index=parseFloat(token[1])):(template=str+" ",index=1);;){index++;const candidate=template+"("+index+")";try{if(this._validateSheetName(candidate))return candidate}catch(error){}}}addSheet(sheetName=null,index=null){if(this._closed)throw new Error(WorkbookModel_MESSAGE_MODEL_CLOSED);if(this.getProtection()?.lockStructure)throw new Error(MESSAGE_ERROR_PROTECTION);let sheetNameLowerCase=sheetName?sheetName.toLowerCase():null;if(sheetName&&this._sheetsByLowerCaseName.has(sheetNameLowerCase))throw new Error((sheetName=>`The sheet name '${sheetName}' already exist in workbook.`)(sheetName));for(sheetNameLowerCase=(sheetName=this._validateSheetName(sheetName))?sheetName.toLowerCase():null;!sheetName;){const sheetNameCandidate=this._sheetNameCreator(this._lastId+1),sheetNameCandidateLowerCase=sheetNameCandidate.toLowerCase();this._sheetsByLowerCaseName.has(sheetNameCandidateLowerCase)?this._lastId++:sheetName=sheetNameCandidate}this._lastId++;const sheet=this._sheetCreator(sheetName);if(!sheet)throw new Error(RangeUtils.QD);const sheetRefAdd=Object.freeze({id:this._lastId,name:sheetName,visibility:IWorkbookModel.A.Visible,sheet});return this._addSheetRef(sheetRefAdd,index),this._adjustSheetNamesIfRequired(),this.notifySheetRefsChange(this._sheetRefsVisible),sheetRefAdd.sheet}_updateSheetRefStates(sheetRefs){if(this._closed)throw new Error(WorkbookModel_MESSAGE_MODEL_CLOSED);if(this.getProtection()?.lockStructure)throw new Error(MESSAGE_ERROR_PROTECTION);this._sheetRefsAll=sheetRefs,this._sheetRefsVisible=[],this._sheetRefsVisibleAndHidden=[];for(let i=0;i<this._sheetRefsAll.length;i++)this._sheetRefsAll[i].visibility===IWorkbookModel.A.Visible?(this._sheetRefsVisible.push(this._sheetRefsAll[i]),this._sheetRefsVisibleAndHidden.push(this._sheetRefsAll[i])):this._sheetRefsAll[i].visibility===IWorkbookModel.A.Hidden&&this._sheetRefsVisibleAndHidden.push(this._sheetRefsAll[i])}_addSheetRef(sheetRefAdd,index=null){const indexAdd=Math.max(0,Math.min(this._sheetRefsAll.length,index??this._sheetRefsAll.length));let cloneAdded=[...this._sheetRefsAll.slice(0,indexAdd),sheetRefAdd,...this._sheetRefsAll.slice(indexAdd)];this._updateSheetRefStates(cloneAdded);const sheet=sheetRefAdd.sheet,addLowerCaseName=sheetRefAdd.name.toLowerCase();this._refsById.set(sheetRefAdd.id,sheetRefAdd),this._refsByLowerCaseName.set(addLowerCaseName,sheetRefAdd),this._refsByInstance.set(sheet,sheetRefAdd),this._sheetsById.set(sheetRefAdd.id,sheet),this._sheetsByLowerCaseName.set(addLowerCaseName,sheet);const _self=this;if(void 0!==sheet){const removeListener=sheet.addListener({onCellsChange(){_self._refsByInstance.get(sheet)&&_self.notifyCellChange()},onDelete(sheetDelete){let sheetRefDelete=_self.getSheetRef(sheetDelete,IWorkbookModel.A.VeryHidden);if(!sheetRefDelete)return;const indexDelete=_self._findOffsetForId(sheetRefDelete.id,_self._sheetRefsAll);let cloned=[..._self._sheetRefsAll];cloned.splice(indexDelete,1),_self._updateSheetRefStates(cloned),_self._listenersSheets.get(sheetRefDelete.id)(),_self._refsById.delete(sheetRefDelete.id),_self._sheetsById.delete(sheetRefDelete.id);const removeLowerCaseName=sheetRefDelete.name.toLowerCase();_self._refsByLowerCaseName.delete(removeLowerCaseName),_self._sheetsByLowerCaseName.delete(removeLowerCaseName),_self._refsByInstance.delete(sheetDelete),_self._listenersSheets.delete(sheetRefDelete.id),_self._adjustRemoveSelectionIfRequired(indexDelete,sheetRefDelete.id),_self._adjustSheetNamesIfRequired(),_self.notifySheetRefsChange(this._sheetRefsVisible),_self._sheetsCreated.has(sheet)&&(_self._sheetsCreated.delete(sheet),sheetDelete?.close())}});this._listenersSheets.set(sheetRefAdd.id,removeListener)}return this._lastId=Math.max(this._lastId,sheetRefAdd.id),sheetRefAdd}_adjustRemoveSelectionIfRequired(indexRemove,id){if(this._view.activeSheetId===id){let newActiveId;newActiveId=indexRemove<this._sheetRefsVisible.length?this._sheetRefsVisible[indexRemove].id:this._sheetRefsVisible[indexRemove-1].id,this._view.activeSheetId=newActiveId}}_adjustSheetNamesIfRequired(){this._sheetNames=this._sheetRefsVisible.map((ref=>ref.name)),this._activeSheetOffset=this._findOffsetForId(this._view.activeSheetId??this._lastId,this._sheetRefsVisible)}_validateDeleteSheet(key){if(this._closed)throw new Error(WorkbookModel_MESSAGE_MODEL_CLOSED);if(this.getProtection()?.lockStructure)throw new Error(MESSAGE_ERROR_PROTECTION);let ref=this.getSheetRef(key);if(!ref)throw new Error((key=>`Invalid reference for remove: ${key}`)(key));if(1===this._sheetRefsVisible.length&&this._sheetRefsVisible[0].id===ref.id)throw new Error(MESSAGE_ERROR_SHEET_ONE)}deleteSheet(key){const ref=this.getSheetRef(key);return this._validateDeleteSheet(key),ref.sheet.delete(),ref.sheet}_findOffsetForId(id,refs){for(let i=0;i<refs.length;i++)if(refs[i].id===id)return i;throw new Error("Internal error no visible sheetRefs")}getActiveAddressCoordsA1(){if(this._closed)throw AddressUtils.Ey;const activeSheet=this.getSheet();return AddressUtils.UC(RangeUtils.ug(activeSheet.getActiveAddressCoords()),{...activeSheet.getMaxCellBounds(),sheetName:activeSheet.getName()})}getActiveAddressCoords(){const activeSheet=this.getSheet();return{...activeSheet.getActiveAddressCoords(),sheetName:activeSheet.getName()}}getActiveSheetIndex(){return this._activeSheetOffset}_scanFind(findText,options,onFind){if(this._closed)throw new Error(WorkbookModel_MESSAGE_MODEL_CLOSED);const isWorkbookScan="workbook"===options.scope,isReverse=options?.isReverse,isWrap=!options?.disableWrap,startSheetIndex=this.getActiveSheetIndex(),startSheet=this.getSheet(),refs=this.getSheetRefs();let found=null,currentSheetIndex=startSheetIndex,currentSheet=startSheet,includeFrom=!1,startFrom=null,fromAsRange=null;if(options?.from){const rangesParsed=this.decodeAddress(options?.from);fromAsRange=rangesParsed?.[0]}fromAsRange?(startFrom={colIndex:fromAsRange.colStart,rowIndex:fromAsRange.rowStart},includeFrom=!0):startFrom=startSheet.getActiveAddressCoords();const originalStartFrom=startFrom,originalStartSheet=startSheet;let startTo=null,bounds=null;isWorkbookScan||1===currentSheet.getView().selection.ranges.length&&(bounds=currentSheet.getView().selection.ranges[0]);const doFind=()=>{let from=startFrom,to=startTo;for(;!found&¤tSheet;){const sheetOptions={includeFrom,isReverse,...options,disableWrap:isWorkbookScan,bounds,from,to,onFound:pair=>{let shouldBreak=options.onFound?.(pair);return shouldBreak||(shouldBreak=onFind(currentSheet,pair.coords,pair.value),shouldBreak&&(found=pair),shouldBreak)}};currentSheet?.find(findText,sheetOptions),isWorkbookScan&&(currentSheetIndex+=sheetOptions.isReverse?-1:1,currentSheetIndex<0?currentSheetIndex=refs.length-1:currentSheetIndex>=refs.length&&(currentSheetIndex=0),currentSheet=this.getSheet(refs[currentSheetIndex]),from=null,to=null),currentSheetIndex===startSheetIndex&&(currentSheetIndex=null,currentSheet=null)}};doFind(),!found&&null!==currentSheetIndex&&startFrom&&!startTo&&isWrap&&(currentSheetIndex=0,currentSheet=this.getSheet(refs[currentSheetIndex]),startTo=startFrom,startFrom=currentSheet===originalStartSheet?originalStartFrom:null,doFind())}find(findText,options){let found=null;return this._scanFind(findText,options,((sheet,coords,cell)=>(found={coords:{...coords,sheetName:sheet.getName()},value:cell},!0))),found}replace(findText,replaceText,options){if(options?.findOptions.fields?.includes(ISheetModel.U6.Value))throw new Error("Can not replace values. Use formula instead");const optionsFind={...options?.findOptions},startSheet=this.getSheet(),startCoords=startSheet.getActiveAddressCoords(),isReplaceAll=options?.isReplaceAll??!1;optionsFind.from||(optionsFind.from=startSheet.getActiveAddressCoords());let next=null,count=0;const transReplace=this._transactionStore.pushTransaction("Replace");let lastSheet=startSheet,pairs=[],firstCommit=null;const commitReplaces=()=>{0!==pairs.length&&null!==lastSheet&&(lastSheet.setCellPairs(pairs,{parseTextAsValue:!0,...options}),pairs=[])};try{if(this._scanFind(findText,optionsFind,((sheet,coords,_cell)=>{if(next={...coords,sheetName:sheet.getName()},firstCommit){if(RangeUtils.rv(firstCommit,coords))return!0}else firstCommit=coords;return count++,lastSheet!==sheet&&commitReplaces(),lastSheet=sheet,!isReplaceAll&&pairs.length>0||(pairs.push({address:coords,update:replaceText}),options?.onReplaceText?.(coords,replaceText),(startSheet!==sheet||!RangeUtils.rv(startCoords,coords))&&!isReplaceAll)})),commitReplaces(),next&&!isReplaceAll){let updateSelection=!1,coords=next;const activeSelection=lastSheet.getView().selection;let selection=activeSelection;const isCoordsSame=RangeUtils.rv(coords,activeSelection.activeCoords);let inRangeIndex=-1;for(let i=0;-1===inRangeIndex&&i<activeSelection.ranges.length;i++)RangeUtils.LX(coords,activeSelection.ranges[i])&&(inRangeIndex=i);if(-1===inRangeIndex)updateSelection=!0;else if(!isCoordsSame){const newSelection={...activeSelection,activeCoords:coords,activeRangeIndex:inRangeIndex};selection=newSelection}!0===updateSelection&&(selection={activeCoords:coords}),this._transactionStore.peekTransaction().updateState({record:lastSheet,state:prevValue=>prevValue,inputs:prevValue=>({...prevValue,selectionView:Object.freeze(selection)})})}transReplace.commit()}catch(e){throw transReplace.rollback(),e}return{next:isReplaceAll?null:next,count}}_nextSheetIndex(index,refs=this.getSheetRefs()){return 1===refs.length||index>=refs.length-1?0:index+1}_prevSheetIndex(index,refs=this.getSheetRefs()){return 1===refs.length?0:index<=0?refs.length-1:index-1}activateNextSheet(){if(this._closed)throw new Error(WorkbookModel_MESSAGE_MODEL_CLOSED);const refs=this.getSheetRefs();return this.setActiveSheet(refs[this._nextSheetIndex(this.getActiveSheetIndex(),refs)]??null)}activatePreviousSheet(){if(this._closed)throw new Error(WorkbookModel_MESSAGE_MODEL_CLOSED);const refs=this.getSheetRefs();return this.setActiveSheet(refs[this._prevSheetIndex(this.getActiveSheetIndex(),refs)]??null)}async duplicateSheet(key){if(this._closed)throw new Error(WorkbookModel_MESSAGE_MODEL_CLOSED);if(this.getProtection()?.lockStructure)throw new Error(MESSAGE_ERROR_PROTECTION);const refs=this.getSheetRefs(),currentOffset=this.getActiveSheetIndex();let ref=null;if(key){if(ref=this.getSheetRef(key),!ref)throw new Error(MESSAGE_ERROR_INVALID_SHEET_KEY(ref))}else ref=refs[currentOffset];if(!ref)return null;const sheetModel=ref.sheet,currentRef=this._refsByInstance.get(sheetModel),persistStyles=this.sheetStyle().beginPersist(),persistResources=this.getResources().beginPersist();try{const asJson=await sheetModel.toJSON(),newId=refs.length+1,newName=this.findValidSheetName(currentRef.name),sheetNew=this._sheetCreator(newName,asJson),newRef=this._addSheetRef(Object.freeze({name:newName,id:newId,visibility:currentRef.visibility||IWorkbookModel.A.Visible,sheet:sheetNew}),currentOffset);return this._adjustSheetNamesIfRequired(),this.notifySheetRefsChange(this._sheetRefsVisible),newRef.sheet}catch(error){throw error}finally{persistStyles.endPersist(),persistResources.endPersist()}}getCell(address){if(this._closed)throw new Error(WorkbookModel_MESSAGE_MODEL_CLOSED);const rangesParsed=this.decodeAddress(address??this.getActiveAddressCoordsA1());if(1!==rangesParsed.length)throw new Error(AddressUtils.sF(address));const rangeParsed=rangesParsed[0],sheetRef=this.getSheetRef(rangeParsed.sheetName,IWorkbookModel.A.VeryHidden);if(!sheetRef)throw new Error(MESSAGE_ERROR_SHEET_NOT_FOUND(rangeParsed.sheetName));const retValue=sheetRef.sheet.getCell({colIndex:rangeParsed.colStart,rowIndex:rangeParsed.rowStart});return this._options.onGetCellAt?.(rangeParsed.sheetName,AddressUtils.ho({colIndex:rangeParsed.colStart,rowIndex:rangeParsed.rowStart}),retValue),retValue}setCell(address,value,options){if(this._closed)throw new Error(WorkbookModel_MESSAGE_MODEL_CLOSED);const rangesParsed=this.decodeAddress(address??this.getActiveAddressCoordsA1());if(1!==rangesParsed.length)throw new Error(AddressUtils.sF(address));const rangeParsed=rangesParsed[0],sheetRef=this.getSheetRef(rangeParsed.sheetName,IWorkbookModel.A.VeryHidden);if(!sheetRef)throw new Error(MESSAGE_ERROR_SHEET_NOT_FOUND(rangeParsed.sheetName));return sheetRef.sheet.setCell({colIndex:rangeParsed.colStart,rowIndex:rangeParsed.rowStart},value,options)}getRange(address){let rangeSheet,sheet;if(address){const rangesParsed=this.decodeAddress(address??this.getActiveAddressCoordsA1());if(!rangesParsed)throw new Error(AddressUtils.sF(address));const rangeParsed=rangesParsed[0],sheetRef=this.getSheetRef(rangeParsed.sheetName,IWorkbookModel.A.VeryHidden);if(!sheetRef){const activeSheet=this.getSheet();return activeSheet?(delete rangeParsed.sheetName,((address,defaultRange)=>address?Object.freeze({...WorkbookUtils.aU,toString:()=>AddressUtils.UC(address,defaultRange)}):WorkbookUtils.aU)(rangeParsed,{sheetName:AddressUtils.Ey,...activeSheet.getMaxCellBounds()})):void console.warn("Internal error no visible sheetRefs")}rangeSheet=sheetRef.sheet.getRange(rangeParsed),sheet=sheetRef.sheet}else sheet=this.getSheet(),rangeSheet=sheet.getRange();return this._sheetRangeToWorkbookRange(rangeSheet,sheet,this)}decodeAddress(address){const _self=this;if("string"==typeof address){const asLowerCase=address.trim().toLowerCase();if("r"===asLowerCase||"c"===asLowerCase){const activeAddress=this.getActiveAddressCoords(),anchor={};"r"===asLowerCase?anchor.rowStart=anchor.rowEnd=activeAddress.rowIndex:anchor.colStart=anchor.colEnd=activeAddress.colIndex,address=anchor}}return WorkbookUtils.ak(address,{...this.getSheet().getMaxCellBounds(),sheetName:this.getSheetNames()[this.getActiveSheetIndex()]},(name=>{let range=_self.getNamedItems().lookupByName(name,_self.getActiveAddressCoords());if(!range)return null;if(!range.ref)throw new Error(`Invalid sheet reference '${name}'.`);return range?range.ref:null}))}_updateSheetRef(refOriginal,refNew){let refsNew=[...this._sheetRefsAll];refsNew[this._findOffsetForId(refOriginal.id,this._sheetRefsAll)]=refNew,this._updateSheetRefStates(refsNew),this._refsById.set(refOriginal.id,refNew);const originalLowerName=refOriginal.name.toLowerCase(),newLowerName=refNew.name.toLowerCase();this._refsByLowerCaseName.delete(originalLowerName),this._refsByLowerCaseName.set(newLowerName,refNew);let refSheet=this._sheetsByLowerCaseName.get(originalLowerName);return this._sheetsByLowerCaseName.delete(originalLowerName),this._sheetsByLowerCaseName.set(newLowerName,refSheet),this._refsByInstance.set(refSheet,refNew),refNew}setSheetName(key,sheetName){if(this._closed)throw new Error(WorkbookModel_MESSAGE_MODEL_CLOSED);if(this.getProtection()?.lockStructure)throw new Error(MESSAGE_ERROR_PROTECTION);const refOriginal=this.getSheetRef(key);if(!refOriginal)throw new Error(MESSAGE_ERROR_INVALID_SHEET_KEY(key));if(sheetName===refOriginal.name)return refOriginal.sheet;sheetName=this._validateSheetName(sheetName);const refNew=Object.freeze({...refOriginal,name:sheetName}),newSheetRef=this._updateSheetRef(refOriginal,refNew);this._adjustSheetNamesIfRequired(),this.notifySheetRefsChange(this._sheetRefsVisible);return this._getTransactionState().listenerRanges.forEach((node=>{if(node.sheetRef===refOriginal||null===node.sheetRef){null!==node.sheetRef&&(node.sheetRef=refNew);try{const event={getSheet:()=>refNew.sheet,getRange:()=>refNew.sheet.getRange(node.range??refNew.sheet.getMaxCellBounds()),trigger:"setSheetName"};node.listener(event)}catch(error){console.warn(error)}}})),newSheetRef.sheet}setSheetVisibility(key,visibility){if(this._closed)throw new Error(WorkbookModel_MESSAGE_MODEL_CLOSED);if(this.getProtection()?.lockStructure)throw new Error(MESSAGE_ERROR_PROTECTION);const refOriginal=this.getSheetRef(key);if(!refOriginal)return null;if(visibility===refOriginal.visibility)return;if(visibility!==IWorkbookModel.A.Visible&&1===this._sheetRefsVisible.length&&this._sheetRefsVisible[0].id===refOriginal.id)throw new Error(MESSAGE_ERROR_SHEET_ONE);const refNew={...refOriginal,visibility};let indexHidden=-1;visibility!==IWorkbookModel.A.Visible&&(indexHidden=this._findOffsetForId(refOriginal.id,this._sheetRefsVisible));const newSheetRef=this._updateSheetRef(refOriginal,refNew);return visibility!==IWorkbookModel.A.Visible&&this._adjustRemoveSelectionIfRequired(indexHidden,refOriginal.id),this._adjustSheetNamesIfRequired(),this.notifySheetRefsChange(this._sheetRefsVisible),newSheetRef.sheet}moveSheet(indexFrom,indexTo){if(this._closed)throw new Error(WorkbookModel_MESSAGE_MODEL_CLOSED);if(this.getProtection()?.lockStructure)throw new Error(MESSAGE_ERROR_PROTECTION);if(indexFrom===indexTo)return;if(!this._sheetRefsVisible[indexFrom])throw new Error(`No sheet at index: ${indexFrom}`);if(indexTo<0||indexTo>this._sheetRefsVisible.length-1)throw new Error(`Invalid to index: ${indexTo}`);const indexFromActual=this._findOffsetForId(this._sheetRefsVisible[indexFrom].id,this._sheetRefsAll),indexToActual=this._findOffsetForId(this._sheetRefsVisible[indexTo].id,this._sheetRefsAll);if(indexFromActual===indexToActual)return;const refFrom=this._sheetRefsAll[indexFromActual];if(!refFrom)throw new Error(`Invalid from index: ${indexFrom}`);let cloned=[...this._sheetRefsAll];return cloned.splice(indexFromActual,1),cloned.splice(indexToActual,0,refFrom),this._updateSheetRefStates(cloned),this._adjustSheetNamesIfRequired(),this.notifySheetRefsChange(this._sheetRefsVisible),refFrom.sheet}setActiveSheet(key){if(this._closed)throw new Error(WorkbookModel_MESSAGE_MODEL_CLOSED);const ref=this.getSheetRef(key);if(!ref)throw new Error(MESSAGE_ERROR_INVALID_SHEET_KEY(key));return ref.visibility!==IWorkbookModel.A.Visible&&this.setSheetVisibility(ref,IWorkbookModel.A.Visible),this._view.activeSheetId=ref.id,ref.sheet}getProtection(){return this._protection??null}_defaultProtection(protection){if(!protection)return null;let retValue=CommonUtils.r(this._protection,protection);return retValue=CommonUtils.$_(retValue)??CommonUtils.t0,retValue=CommonUtils.r(WorkbookUtils.j_,retValue),retValue}setProtection(protection){if(this._closed)throw new Error(WorkbookModel_MESSAGE_MODEL_CLOSED);this._protection=this._defaultProtection(protection),this.notifyProtectionChange(this._protection)}getNamedItems(){return this._namedRanges}notifyProtectionChange(update){const param=update??this._protection;this._listeners.forEach((listener=>{listener.onProtectionChange?.(param)}))}notifyCellChange(){this._listeners.forEach((listener=>{listener.onCellsChange?.()}))}notifySheetRefsChange(update=null){const param=update??this._sheetRefsVisible;this._listeners.forEach((listener=>{listener.onSheetsRefsChange?.(param)}))}notifyThemeChange(update=null){const param=update??this._theme;this._listeners.forEach((listener=>{listener.onThemeChange?.(param)}))}notifyViewChange(update=null){const param=update??this._view;this._listeners.forEach((listener=>{listener.onViewChange?.(param)}))}notifyAllChange(){this.notifyCellChange(),this.notifySheetRefsChange(this._sheetRefsVisible),this.notifyViewChange(),this._listeners.forEach((listener=>{listener.onAllChange?.()}))}addListener(listener){if(this._closed)throw new Error(WorkbookModel_MESSAGE_MODEL_CLOSED);const listeners=this._listeners;return listeners.add(listener),function(){listeners.delete(listener)}}_sheetRangeToWorkbookRange(range,sheet,workbook){const bounds=()=>range.bounds()&&sheet?{...range.bounds(),sheetName:sheet.getName()}:null;return{...range,bounds,toString:()=>AddressUtils.UC(bounds(),{...sheet.getMaxCellBounds(),sheetName:sheet.getName()}),workbook:()=>workbook,isWorkbookRange:!0}}addRangeListener(address,listener,options){if(this._closed)throw new Error(WorkbookModel_MESSAGE_MODEL_CLOSED);if(!address)throw new Error(AddressUtils.Bn);const rangesParsed=this.decodeAddress(address);if(1!==rangesParsed.length)throw new Error(AddressUtils.sF(address));const rangeWorkbook=rangesParsed[0],sheetRef=rangeWorkbook?this.getSheetRef(rangeWorkbook.sheetName,IWorkbookModel.A.VeryHidden):null,self=this;let range=null;if(rangeWorkbook){if(!sheetRef)return()=>{};range={...rangeWorkbook}}delete range?.sheetName;let removeListener=null;const listenerSheet=event=>{const eventWB={getWorkbook:()=>self,getSheet:event.getSheet,getRange:()=>this._sheetRangeToWorkbookRange(event.getRange(),event.getSheet(),self),trigger:event.trigger};listener(eventWB)};sheetRef&&(removeListener=sheetRef.sheet.addRangeListener(range,listenerSheet,options));const listenerRangesRead=this._getTransactionState().listenerRanges,listenerRangesWrite=new Set(listenerRangesRead),refListener={listener:listenerSheet,sheetRef,range,removeListener};listenerRangesWrite.add(refListener),this._updateTransactionState((prev=>({...prev,listenerRanges:listenerRangesWrite})));const _self=this,removeListenerWrapper=()=>{const listenerRangesRead=_self._getTransactionState().listenerRanges,listenerRangesWrite=new Set(listenerRangesRead);this._updateTransactionState((prev=>({...prev,listenerRanges:listenerRangesWrite}))),listenerRangesWrite.delete(refListener),removeListener?.()};return()=>removeListenerWrapper()}fromJSON(json){if(this._closed)throw new Error(WorkbookModel_MESSAGE_MODEL_CLOSED);this._fromJSON(json),this.notifyAllChange()}_fromJSON(json,rangeUpdate){let oldSheetRefs=this.getSheetRefs();for(let i=oldSheetRefs&&oldSheetRefs.length-1;i>=0;i--);this._initialize();const parsedJson=json||{sheets:[{name:this._sheetNameCreator(1),sheet:{data:[]}}]};if(!parsedJson.sheets||0===parsedJson.sheets.length)throw new Error(MESSAGE_ERROR_SHEET_ONE);parsedJson.theme&&(this._theme=new DocThemes.uJ(parsedJson.theme),this._sheetStyle.setTheme(this._theme));const persistResources=this._sharedResources.beginPersist(),persistStyles=this._sheetStyle.beginPersist();try{persistResources.fromJSON(parsedJson.resources),persistStyles.fromJSON(parsedJson.style),parsedJson.date1904&&(this._is1904DateSystem=!0),parsedJson.view||(parsedJson.view={});let activeSheetId=parsedJson.view.activeSheetId??null;null!==activeSheetId&&(activeSheetId=Math.min(Math.max(1,activeSheetId),parsedJson.sheets.length));let lastVisibleId=null;for(let i=0;i<parsedJson.sheets.length;i++){const sheetRefJSON=parsedJson.sheets[i],sheet=this._sheetCreator(sheetRefJSON.name,rangeUpdate??sheetRefJSON.sheet),visibility=sheetRefJSON.visibility||IWorkbookModel.A.Visible,id=i+1;visibility===IWorkbookModel.A.Visible?lastVisibleId=id:null!==activeSheetId&&activeSheetId===id&&(activeSheetId=null),sheetRefJSON.sheet&&this._addSheetRef(Object.freeze({name:sheetRefJSON.name,id,visibility,sheet}))}parsedJson.view.activeSheetId=activeSheetId??lastVisibleId,this._view.fromJSON(parsedJson.view,!1),parsedJson.protection&&(this._protection=this._defaultProtection(parsedJson.protection))}finally{persistStyles.endPersist(),persistResources.endPersist()}this._adjustSheetNamesIfRequired(),this._namedRanges.fromJSON(parsedJson.definedNames)}async toJSON(){if(this._closed)throw new Error(WorkbookModel_MESSAGE_MODEL_CLOSED);const json={sheets:[]},jsonTheme=this._theme.toJSON();(jsonTheme?Object.keys(jsonTheme).length:0)>0&&(json.theme=jsonTheme);const persistStyles=this._sheetStyle.beginPersist(),persistResources=this._sharedResources.beginPersist();try{const originalActiveSheetId=this.getSheetRef(this.getActiveSheetIndex()).id;let activeSheetId=originalActiveSheetId,lastVisibleId=null;for(let i=0;i<this._sheetRefsAll.length;i++){const sheetRef=this._sheetRefsAll[i],id=i+1,jsonSheet=await this._sheetsById.get(sheetRef.id).toJSON(),sheetRefJson={name:sheetRef.name,sheet:jsonSheet};sheetRef.visibility===IWorkbookModel.A.Visible?lastVisibleId=id:sheetRefJson.visibility=sheetRef.visibility,sheetRef.id===originalActiveSheetId&&(activeSheetId=id),json.sheets.push(sheetRefJson)}const sheetStyle=persistStyles.toJSON();if(sheetStyle&&Object.keys(sheetStyle).length>0&&(json.style=sheetStyle),this._protection){json.protection={};const keys=Object.keys(this._protection);for(let k=0;k<keys.length;k++){const value=this._protection[keys[k]];null!=value&&value!==WorkbookUtils.j_[keys[k]]&&(json.protection[keys[k]]=value)}}const sharedResources=await persistResources.toJSON();sharedResources&&sharedResources.length>0&&(json.resources=sharedResources);const jsonDefinedNames=this._namedRanges.toJSON();jsonDefinedNames&&jsonDefinedNames.length>0&&(json.definedNames=jsonDefinedNames);const jsonView=this._view.toJSON();jsonView&&(activeSheetId!==lastVisibleId?jsonView.activeSheetId=activeSheetId:delete jsonView.activeSheetId,Object.keys(jsonView).length>0&&(json.view=jsonView))}finally{persistStyles.endPersist(),persistResources.endPersist()}return this._is1904DateSystem&&(json.date1904=!0),json}isClosed(){return this._closed}close(){if(this._closed)return;const _self=this;this._listeners.forEach((listener=>{listener.onClose?.(_self)})),this._closed=!0,this._listenersSheets.forEach((removeListener=>{removeListener()})),this._listenersSheets.clear();for(let i=this._sheetRefsAll.length-1;i>=0;i--)try{this._sheetRefsAll[i].sheet.close()}catch(error){console.warn("error on close",error)}this._listeners.clear(),this._transactionStoreRemoveListener?.()}pushTransaction(description){if(this._closed)throw new Error(WorkbookModel_MESSAGE_MODEL_CLOSED);return this._pushTransaction(description)}_getTransactionState(){return this._transactionStore.peekTransaction().getState(this)}_pushTransaction(description){return this._transactionStore.pushTransaction(description,(transaction=>{transaction.depth}))}_updateTransactionState(updaterState,updaterInputs){(updaterState||updaterInputs)&&this._transactionStore.peekTransaction().updateState({record:this,state:updaterState,inputs:updaterInputs})}get options(){return this._options}get isIWorkbookModel(){return!0}}},"../../packages/models/src/workbook/WorkbookUtils.ts":(__unused_webpack_module,__webpack_exports__,__webpack_require__)=>{__webpack_require__.d(__webpack_exports__,{Kb:()=>cellSelectionToRanges,aU:()=>RANGE_INVALID_REF,ak:()=>decodeWorkbookRange,j_:()=>DEFAULT_WORKBOOK_PROTECTION});var _range__WEBPACK_IMPORTED_MODULE_1__=__webpack_require__("../../packages/models/src/range/AddressUtils.ts"),_range__WEBPACK_IMPORTED_MODULE_2__=__webpack_require__("../../packages/models/src/range/RangeUtils.ts"),_sheet__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__("../../packages/models/src/sheet/SheetUtils.ts");const DEFAULT_WORKBOOK_PROTECTION={lockStructure:!1,lockWindows:!1,lockRevision:!1,workbookPassword:null,revisionsPassword:null},RANGE_INVALID_REF=Object.freeze({..._sheet__WEBPACK_IMPORTED_MODULE_0__.aU,bounds:()=>null,sheet:()=>null,workbook:()=>null,isWorkbookRange:!0}),decodeWorkbookRange=(range,defaultRange,rangeLookup,allowR1C1)=>{if(!range)return null;if(range.isSheetRange&&(range=range.bounds()),"string"==typeof range){const decoded=_range__WEBPACK_IMPORTED_MODULE_1__.QE(range,defaultRange,allowR1C1);return decoded||rangeLookup?.(range)}const parseAsObject=rangeObj=>{if(void 0!==rangeObj.rowIndex&&void 0!==rangeObj.colIndex){const cellCoords=_range__WEBPACK_IMPORTED_MODULE_2__.ug(rangeObj),retValue={...defaultRange,...cellCoords};return rangeObj.sheetName&&(retValue.sheetName=rangeObj.sheetName),retValue}if(void 0!==rangeObj.rowStart||void 0!==rangeObj.colStart||void 0!==rangeObj.rowEnd||void 0!==rangeObj.colEnd)return{...defaultRange,...rangeObj}};if(Array.isArray(range)){const retValue=[];for(let i=0;i<range.length;i++){const asObj=parseAsObject(range[i]);asObj&&retValue.push(asObj)}return retValue}{const asObj=parseAsObject(range);if(asObj)return[asObj]}return null},cellSelectionToRanges=(cellSelection,template)=>{const ranges=_sheet__WEBPACK_IMPORTED_MODULE_0__.Kb(cellSelection),retValue=[];for(let i=0;i<ranges.length;i++)retValue.push({...template,...ranges[i]});return retValue}}}]);