import*as i18n from"../../core/i18n/i18n.js";import*as SDK from"../../core/sdk/sdk.js";import*as Buttons from"../../ui/components/buttons/buttons.js";import*as ComponentHelpers from"../../ui/components/helpers/helpers.js";import*as IconButton from"../../ui/components/icon_button/icon_button.js";import*as ReportView from"../../ui/components/report_view/report_view.js";import*as DataGrid from"../../ui/legacy/components/data_grid/data_grid.js";import*as ObjectUI from"../../ui/legacy/components/object_ui/object_ui.js";import*as UI from"../../ui/legacy/legacy.js";import*as LitHtml from"../../ui/lit-html/lit-html.js";import*as ApplicationComponents from"./components/components.js";import indexedDBViewsStyles from"./indexedDBViews.css.js";const UIStrings={version:"Version",objectStores:"Object stores",deleteDatabase:"Delete database",refreshDatabase:"Refresh database",pleaseConfirmDeleteOfSDatabase:'Please confirm delete of "{PH1}" database.',idb:"IDB",refresh:"Refresh",deleteSelected:"Delete selected",clearObjectStore:"Clear object store",dataMayBeStale:"Data may be stale",someEntriesMayHaveBeenModified:"Some entries may have been modified",keyString:"Key",primaryKey:"Primary key",valueString:"Value",indexedDb:"Indexed DB",keyPath:"Key path: ",showPreviousPage:"Show previous page",showNextPage:"Show next page",startFromKey:"Start from key",expandRecursively:"Expand Recursively",collapse:"Collapse",totalEntriesS:"Total entries: {PH1}",keyGeneratorValueS:"Key generator value: {PH1}"},str_=i18n.i18n.registerUIStrings("panels/application/IndexedDBViews.ts",UIStrings),i18nString=i18n.i18n.getLocalizedString.bind(void 0,str_);export class IDBDatabaseView extends ApplicationComponents.StorageMetadataView.StorageMetadataView{model;database;constructor(e,t){super(),this.model=e,t&&this.update(t)}getTitle(){return this.database?.databaseId.name}async renderReportContent(){return this.database?LitHtml.html`
      ${await super.renderReportContent()}
      ${this.key(i18nString(UIStrings.version))}
      ${this.value(this.database.version.toString())}
      ${this.key(i18nString(UIStrings.objectStores))}
      ${this.value(this.database.objectStores.size.toString())}
      <${ReportView.ReportView.ReportSectionDivider.litTagName}></${ReportView.ReportView.ReportSectionDivider.litTagName}>
      <${ReportView.ReportView.ReportSection.litTagName}>
      <${Buttons.Button.Button.litTagName}
          aria-label=${i18nString(UIStrings.deleteDatabase)}
          .variant=${"secondary"}
          @click=${this.deleteDatabase}>
        ${i18nString(UIStrings.deleteDatabase)}
      </${Buttons.Button.Button.litTagName}>&nbsp;
      <${Buttons.Button.Button.litTagName}
          aria-label=${i18nString(UIStrings.refreshDatabase)}
          .variant=${"secondary"}
          @click=${this.refreshDatabaseButtonClicked}>
        ${i18nString(UIStrings.refreshDatabase)}
      </${Buttons.Button.Button.litTagName}>
      </${ReportView.ReportView.ReportSection.litTagName}>
      `:LitHtml.nothing}refreshDatabaseButtonClicked(){this.model.refreshDatabase(this.database.databaseId)}update(e){this.database=e;const t=this.model.target().model(SDK.StorageBucketsModel.StorageBucketsModel)?.getBucketByName(e.databaseId.storageBucket.storageKey,e.databaseId.storageBucket.name);t?this.setStorageBucket(t):this.setStorageKey(e.databaseId.storageBucket.storageKey),this.render().then((()=>this.updatedForTests()))}updatedForTests(){}async deleteDatabase(){await UI.UIUtils.ConfirmDialog.show(i18nString(UIStrings.pleaseConfirmDeleteOfSDatabase,{PH1:this.database.databaseId.name}),this)&&this.model.deleteDatabase(this.database.databaseId)}wasShown(){super.wasShown()}}ComponentHelpers.CustomElements.defineComponent("devtools-idb-database-view",IDBDatabaseView);export class IDBDataView extends UI.View.SimpleView{model;databaseId;isIndex;refreshObjectStoreCallback;refreshButton;deleteSelectedButton;clearButton;needsRefresh;clearingObjectStore;pageSize;skipCount;entries;objectStore;index;keyInput;dataGrid;lastPageSize;lastSkipCount;pageBackButton;pageForwardButton;lastKey;summaryBarElement;constructor(e,t,a,i,s){super(i18nString(UIStrings.idb)),this.model=e,this.databaseId=t,this.isIndex=Boolean(i),this.refreshObjectStoreCallback=s,this.element.classList.add("indexed-db-data-view","storage-view"),this.refreshButton=new UI.Toolbar.ToolbarButton(i18nString(UIStrings.refresh),"refresh"),this.refreshButton.addEventListener(UI.Toolbar.ToolbarButton.Events.Click,this.refreshButtonClicked,this),this.deleteSelectedButton=new UI.Toolbar.ToolbarButton(i18nString(UIStrings.deleteSelected),"cross"),this.deleteSelectedButton.addEventListener(UI.Toolbar.ToolbarButton.Events.Click,(e=>{this.deleteButtonClicked(null)})),this.clearButton=new UI.Toolbar.ToolbarButton(i18nString(UIStrings.clearObjectStore),"clear"),this.clearButton.addEventListener(UI.Toolbar.ToolbarButton.Events.Click,(()=>{this.clearButtonClicked()}),this);const r=UI.UIUtils.createIconLabel({title:i18nString(UIStrings.dataMayBeStale),iconName:"warning",color:"var(--icon-warning)",width:"20px",height:"20px"});this.needsRefresh=new UI.Toolbar.ToolbarItem(r),this.needsRefresh.setVisible(!1),this.needsRefresh.setTitle(i18nString(UIStrings.someEntriesMayHaveBeenModified)),this.clearingObjectStore=!1,this.createEditorToolbar(),this.pageSize=50,this.skipCount=0,this.update(a,i),this.entries=[]}createDataGrid(){const e=this.isIndex&&this.index?this.index.keyPath:this.objectStore.keyPath,t=[],a={title:void 0,titleDOMFragment:void 0,sortable:!1,sort:void 0,align:void 0,width:void 0,fixedWidth:void 0,editable:void 0,nonSelectable:void 0,longText:void 0,disclosure:void 0,weight:void 0,allowInSortByEvenWhenHidden:void 0,dataType:void 0,defaultWeight:void 0};t.push({...a,id:"number",title:"#",sortable:!1,width:"50px"}),t.push({...a,id:"key",titleDOMFragment:this.keyColumnHeaderFragment(i18nString(UIStrings.keyString),e),sortable:!1}),this.isIndex&&t.push({...a,id:"primaryKey",titleDOMFragment:this.keyColumnHeaderFragment(i18nString(UIStrings.primaryKey),this.objectStore.keyPath),sortable:!1});const i=i18nString(UIStrings.valueString);t.push({...a,id:"value",title:i,sortable:!1});const s=new DataGrid.DataGrid.DataGridImpl({displayName:i18nString(UIStrings.indexedDb),columns:t,deleteCallback:this.deleteButtonClicked.bind(this),refreshCallback:this.updateData.bind(this,!0),editCallback:void 0});return s.setStriped(!0),s.addEventListener(DataGrid.DataGrid.Events.SelectedNode,(()=>this.updateToolbarEnablement()),this),s}keyColumnHeaderFragment(e,t){const a=document.createDocumentFragment();if(UI.UIUtils.createTextChild(a,e),null===t)return a;if(UI.UIUtils.createTextChild(a," ("+i18nString(UIStrings.keyPath)),Array.isArray(t)){UI.UIUtils.createTextChild(a,"[");for(let e=0;e<t.length;++e)0!==e&&UI.UIUtils.createTextChild(a,", "),a.appendChild(this.keyPathStringFragment(t[e]));UI.UIUtils.createTextChild(a,"]")}else{const e=t;a.appendChild(this.keyPathStringFragment(e))}return UI.UIUtils.createTextChild(a,")"),a}keyPathStringFragment(e){const t=document.createDocumentFragment();UI.UIUtils.createTextChild(t,'"');return t.createChild("span","source-code indexed-db-key-path").textContent=e,UI.UIUtils.createTextChild(t,'"'),t}createEditorToolbar(){const e=new UI.Toolbar.Toolbar("data-view-toolbar",this.element);e.appendToolbarItem(this.refreshButton),e.appendToolbarItem(new UI.Toolbar.ToolbarSeparator);const t=new IconButton.Icon.Icon;t.data={iconName:"triangle-left",color:"var(--icon-default)",width:"20px",height:"20px"},this.pageBackButton=new UI.Toolbar.ToolbarButton(i18nString(UIStrings.showPreviousPage),t),this.pageBackButton.addEventListener(UI.Toolbar.ToolbarButton.Events.Click,this.pageBackButtonClicked,this),e.appendToolbarItem(this.pageBackButton);const a=new IconButton.Icon.Icon;a.data={iconName:"triangle-right",color:"var(--icon-default)",width:"20px",height:"20px"},this.pageForwardButton=new UI.Toolbar.ToolbarButton(i18nString(UIStrings.showNextPage),a),this.pageForwardButton.setEnabled(!1),this.pageForwardButton.addEventListener(UI.Toolbar.ToolbarButton.Events.Click,this.pageForwardButtonClicked,this),e.appendToolbarItem(this.pageForwardButton),this.keyInput=new UI.Toolbar.ToolbarInput(i18nString(UIStrings.startFromKey),"",.5),this.keyInput.addEventListener(UI.Toolbar.ToolbarInput.Event.TextChanged,this.updateData.bind(this,!1)),e.appendToolbarItem(this.keyInput),e.appendToolbarItem(new UI.Toolbar.ToolbarSeparator),e.appendToolbarItem(this.clearButton),e.appendToolbarItem(this.deleteSelectedButton),e.appendToolbarItem(this.needsRefresh)}pageBackButtonClicked(){this.skipCount=Math.max(0,this.skipCount-this.pageSize),this.updateData(!1)}pageForwardButtonClicked(){this.skipCount=this.skipCount+this.pageSize,this.updateData(!1)}populateContextMenu(e,t){const a=t;a.valueObjectPresentation&&(e.revealSection().appendItem(i18nString(UIStrings.expandRecursively),(()=>{a.valueObjectPresentation&&a.valueObjectPresentation.objectTreeElement().expandRecursively()})),e.revealSection().appendItem(i18nString(UIStrings.collapse),(()=>{a.valueObjectPresentation&&a.valueObjectPresentation.objectTreeElement().collapse()})))}refreshData(){this.updateData(!0)}update(e,t){this.objectStore=e,this.index=t,this.dataGrid&&this.dataGrid.asWidget().detach(),this.dataGrid=this.createDataGrid(),this.dataGrid.setRowContextMenuCallback(this.populateContextMenu.bind(this)),this.dataGrid.asWidget().show(this.element),this.skipCount=0,this.updateData(!0)}parseKey(e){let t;try{t=JSON.parse(e)}catch(a){t=e}return t}updateData(e){const t=this.parseKey(this.keyInput.value()),a=this.pageSize;let i=this.skipCount,s=this.dataGrid.selectedNode?this.dataGrid.selectedNode.data.number:0;if(s=Math.max(s,this.skipCount),this.clearButton.setEnabled(!this.isIndex),!e&&this.lastKey===t&&this.lastPageSize===a&&this.lastSkipCount===i)return;function r(e,t){this.clear(),this.entries=e;let a=null;for(let t=0;t<e.length;++t){const r={};r.number=t+i,r.key=e[t].key,r.primaryKey=e[t].primaryKey,r.value=e[t].value;const n=new IDBDataGridNode(r);this.dataGrid.rootNode().appendChild(n),r.number<=s&&(a=n)}a&&a.select(),this.pageBackButton.setEnabled(Boolean(i)),this.pageForwardButton.setEnabled(t),this.needsRefresh.setVisible(!1),this.updateToolbarEnablement(),this.updatedDataForTests()}this.lastKey===t&&this.lastPageSize===a||(i=0,this.skipCount=0),this.lastKey=t,this.lastPageSize=a,this.lastSkipCount=i;const n=t?window.IDBKeyRange.lowerBound(t):null;this.isIndex&&this.index?this.model.loadIndexData(this.databaseId,this.objectStore.name,this.index.name,n,i,a,r.bind(this)):this.model.loadObjectStoreData(this.databaseId,this.objectStore.name,n,i,a,r.bind(this)),this.model.getMetadata(this.databaseId,this.objectStore).then(this.updateSummaryBar.bind(this))}updateSummaryBar(e){if(this.summaryBarElement||(this.summaryBarElement=this.element.createChild("div","object-store-summary-bar")),this.summaryBarElement.removeChildren(),!e)return;const t=this.summaryBarElement.createChild("span");t.textContent=i18nString(UIStrings.totalEntriesS,{PH1:String(e.entriesCount)}),this.objectStore.autoIncrement&&(t.textContent+=" ❘ ",t.textContent+=i18nString(UIStrings.keyGeneratorValueS,{PH1:String(e.keyGeneratorValue)}))}updatedDataForTests(){}refreshButtonClicked(){this.updateData(!0)}async clearButtonClicked(){this.clearButton.setEnabled(!1),this.clearingObjectStore=!0,await this.model.clearObjectStore(this.databaseId,this.objectStore.name),this.clearingObjectStore=!1,this.clearButton.setEnabled(!0),this.updateData(!0)}markNeedsRefresh(){this.clearingObjectStore||this.needsRefresh.setVisible(!0)}async deleteButtonClicked(e){if(!e&&!(e=this.dataGrid.selectedNode))return;const t=(this.isIndex?e.data.primaryKey:e.data.key).value;await this.model.deleteEntries(this.databaseId,this.objectStore.name,window.IDBKeyRange.only(t)),this.refreshObjectStoreCallback()}clear(){this.dataGrid.rootNode().removeChildren(),this.entries=[]}updateToolbarEnablement(){const e=!this.dataGrid||0===this.dataGrid.rootNode().children.length;this.deleteSelectedButton.setEnabled(!e&&null!==this.dataGrid.selectedNode)}wasShown(){super.wasShown(),this.registerCSSFiles([indexedDBViewsStyles])}}export class IDBDataGridNode extends DataGrid.DataGrid.DataGridNode{selectable;valueObjectPresentation;constructor(e){super(e,!1),this.selectable=!0,this.valueObjectPresentation=null}createCell(e){const t=super.createCell(e),a=this.data[e];switch(e){case"value":{t.removeChildren();const e=ObjectUI.ObjectPropertiesSection.ObjectPropertiesSection.defaultObjectPropertiesSection(a,void 0,!0,!0);t.appendChild(e.element),this.valueObjectPresentation=e;break}case"key":case"primaryKey":{t.removeChildren();const e=ObjectUI.ObjectPropertiesSection.ObjectPropertiesSection.defaultObjectPresentation(a,void 0,!0,!0);t.appendChild(e);break}}return t}}