@ag-grid-enterprise/clipboard
Version:
Advanced Data Grid / Data Table supporting Javascript / Typescript / React / Angular / Vue
7 lines (6 loc) • 18 kB
JavaScript
var __defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__hasOwnProp=Object.prototype.hasOwnProperty,__export=(d,e)=>{for(var t in e)__defProp(d,t,{get:e[t],enumerable:!0})},__copyProps=(d,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of __getOwnPropNames(e))!__hasOwnProp.call(d,o)&&o!==t&&__defProp(d,o,{get:()=>e[o],enumerable:!(s=__getOwnPropDesc(e,o))||s.enumerable});return d},__toCommonJS=d=>__copyProps(__defProp({},"__esModule",{value:!0}),d),main_exports={};__export(main_exports,{ClipboardModule:()=>ClipboardModule}),module.exports=__toCommonJS(main_exports);var import_core2=require("@ag-grid-community/core"),import_csv_export=require("@ag-grid-community/csv-export"),import_core3=require("@ag-grid-enterprise/core");function copyToClipboard(d,e){d.clipboardService?.copyToClipboard(e)}function cutToClipboard(d,e){d.clipboardService?.cutToClipboard(e)}function copySelectedRowsToClipboard(d,e){d.clipboardService?.copySelectedRowsToClipboard(e)}function copySelectedRangeToClipboard(d,e){d.clipboardService?.copySelectedRangeToClipboard(e)}function copySelectedRangeDown(d){d.clipboardService?.copyRangeDown()}function pasteFromClipboard(d){d.clipboardService?.pasteFromClipboard()}var import_core=require("@ag-grid-community/core"),SOURCE_PASTE="paste",EXPORT_TYPE_DRAG_COPY="dragCopy",EXPORT_TYPE_CLIPBOARD="clipboard",apiError=d=>`AG Grid: Unable to use the Clipboard API (navigator.clipboard.${d}()). The reason why it could not be used has been logged in the previous line. For this reason the grid has defaulted to using a workaround which doesn't perform as well. Either fix why Clipboard API is blocked, OR stop this message from appearing by setting grid property suppressClipboardApi=true (which will default the grid to using the workaround rather than the API.`,ClipboardService=class S extends import_core.BeanStub{constructor(){super(...arguments),this.beanName="clipboardService",this.lastPasteOperationTime=0,this.navigatorApiFailed=!1}wireBeans(e){this.csvCreator=e.csvCreator,this.selectionService=e.selectionService,this.rowModel=e.rowModel,this.ctrlsService=e.ctrlsService,this.valueService=e.valueService,this.focusService=e.focusService,this.rowRenderer=e.rowRenderer,this.visibleColsService=e.visibleColsService,this.funcColsService=e.funcColsService,this.cellNavigationService=e.cellNavigationService,this.cellPositionUtils=e.cellPositionUtils,this.rowPositionUtils=e.rowPositionUtils,this.rangeService=e.rangeService}postConstruct(){(0,import_core._isClientSideRowModel)(this.gos)&&(this.clientSideRowModel=this.rowModel),this.ctrlsService.whenReady(this,e=>{this.gridCtrl=e.gridCtrl})}pasteFromClipboard(){!this.gos.get("suppressClipboardApi")&&!this.navigatorApiFailed&&navigator.clipboard&&navigator.clipboard.readText?navigator.clipboard.readText().then(this.processClipboardData.bind(this)).catch(t=>{(0,import_core._warnOnce)(`${t}
${apiError("readText")}`),this.navigatorApiFailed=!0,this.pasteFromClipboardLegacy()}):this.pasteFromClipboardLegacy()}pasteFromClipboardLegacy(){let e=!1;const t=s=>{const o=new Date().getTime();o-this.lastPasteOperationTime<50&&(e=!0,s.preventDefault()),this.lastPasteOperationTime=o};this.executeOnTempElement(s=>{s.addEventListener("paste",t),s.focus({preventScroll:!0})},s=>{const o=s.value;e?this.refocusLastFocusedCell():this.processClipboardData(o),s.removeEventListener("paste",t)})}refocusLastFocusedCell(){const e=this.focusService.getFocusedCell();e&&this.focusService.setFocusedCell({rowIndex:e.rowIndex,column:e.column,rowPinned:e.rowPinned,forceBrowserFocus:!0})}getClipboardDelimiter(){const e=this.gos.get("clipboardDelimiter");return(0,import_core._exists)(e)?e:" "}processClipboardData(e){if(e==null)return;let t=S.stringToArray(e,this.getClipboardDelimiter());const s=this.gos.getCallback("processDataFromClipboard");if(s&&(t=s({data:t})),t==null)return;this.gos.get("suppressLastEmptyLineOnPaste")&&this.removeLastLineIfBlank(t);const o=(i,r,l,a)=>{this.rangeService?.isMoreThanOneCell()&&!this.hasOnlyOneValueToPaste(t)?this.pasteIntoActiveRange(this.rangeService,t,i,r,a):this.pasteStartingFromFocusedCell(t,i,r,l,a)};this.doPasteOperation(o)}static stringToArray(e,t=","){const s=[],o=r=>r==="\r"||r===`
`;let i=!1;if(e==="")return[[""]];for(let r=0,l=0,a=0;a<e.length;a++){const n=e[a-1],u=e[a],c=e[a+1],h=()=>{s[r]||(s[r]=[]),s[r][l]||(s[r][l]="")};if(h(),u==='"'&&(i?c==='"'?(s[r][l]+='"',a++):i=!1:(n===void 0||n===t||o(n))&&(i=!0)),!i&&u!=='"'){if(u===t){l++,h();continue}else if(o(u)){l=0,r++,h(),u==="\r"&&c===`
`&&a++;continue}}s[r][l]+=u}return s}doPasteOperation(e){const t="clipboard";this.eventService.dispatchEvent({type:"pasteStart",source:t});let s;if(this.clientSideRowModel){const a=this.gos.get("aggregateOnlyChangedColumns");s=new import_core.ChangedPath(a,this.clientSideRowModel.getRootNode())}const o={},i=[],r=this.focusService.getFocusedCell();e(o,i,r,s);const l=[...i];s&&(this.clientSideRowModel.doAggregate(s),s.forEachChangedNodeDepthFirst(a=>{l.push(a)})),this.rowRenderer.refreshCells({rowNodes:l}),this.dispatchFlashCells(o),this.fireRowChanged(i),this.refocusLastFocusedCell(),this.eventService.dispatchEvent({type:"pasteEnd",source:t})}pasteIntoActiveRange(e,t,s,o,i){const r=this.getRangeSize(e)%t.length!=0;let l=0,a=0;const n=(u,c,h,p)=>{if(p-l>=t.length){if(r)return;l+=a,a=0}const C=t[p-l];o.push(c);const w=this.gos.getCallback("processCellFromClipboard");h.forEach((v,f)=>{if(!v.isCellEditable(c)||v.isSuppressPaste(c))return;f>=C.length&&(f=f%C.length);const b=this.processCell(c,v,C[f],EXPORT_TYPE_DRAG_COPY,w,!0);c.setDataValue(v,b,SOURCE_PASTE),i&&i.addParentNode(c.parent,[v]);const{rowIndex:m,rowPinned:R}=u,y=this.cellPositionUtils.createIdFromValues({rowIndex:m,column:v,rowPinned:R});s[y]=!0}),a++};this.iterateActiveRanges(!1,n)}getDisplayedColumnsStartingAt(e){let t=e;const s=[];for(;t!=null;)s.push(t),t=this.visibleColsService.getColAfter(t);return s}pasteStartingFromFocusedCell(e,t,s,o,i){if(!o)return;const r={rowIndex:o.rowIndex,rowPinned:o.rowPinned},l=this.getDisplayedColumnsStartingAt(o.column);this.isPasteSingleValueIntoRange(e)?this.pasteSingleValueIntoRange(e,s,t,i):this.pasteMultipleValues(e,r,s,l,t,EXPORT_TYPE_CLIPBOARD,i)}isPasteSingleValueIntoRange(e){return this.hasOnlyOneValueToPaste(e)&&this.rangeService!=null&&!this.rangeService.isEmpty()}pasteSingleValueIntoRange(e,t,s,o){const i=e[0][0],r=(l,a,n)=>{t.push(a),n.forEach(u=>this.updateCellValue(a,u,i,s,EXPORT_TYPE_CLIPBOARD,o))};this.iterateActiveRanges(!1,r)}hasOnlyOneValueToPaste(e){return e.length===1&&e[0].length===1}copyRangeDown(){if(!this.rangeService||this.rangeService.isEmpty())return;const e=[],t=(s,o,i,r)=>{const l=this.gos.getCallback("processCellForClipboard"),a=this.gos.getCallback("processCellFromClipboard"),n=(u,c,h)=>{e.length?(o.push(c),h.forEach((p,g)=>{if(!p.isCellEditable(c)||p.isSuppressPaste(c))return;const C=this.processCell(c,p,e[g],EXPORT_TYPE_DRAG_COPY,a,!0);c.setDataValue(p,C,SOURCE_PASTE),r&&r.addParentNode(c.parent,[p]);const{rowIndex:w,rowPinned:v}=u,f=this.cellPositionUtils.createIdFromValues({rowIndex:w,column:p,rowPinned:v});s[f]=!0})):h.forEach(p=>{const g=this.processCell(c,p,this.valueService.getValue(p,c),EXPORT_TYPE_DRAG_COPY,l,!1,!0);e.push(g)})};this.iterateActiveRanges(!0,n)};this.doPasteOperation(t)}removeLastLineIfBlank(e){const t=(0,import_core._last)(e);if(t&&t.length===1&&t[0]===""){if(e.length===1)return;(0,import_core._removeFromArray)(e,t)}}fireRowChanged(e){this.gos.get("editType")==="fullRow"&&e.forEach(t=>{this.eventService.dispatchEvent({type:"rowValueChanged",node:t,data:t.data,rowIndex:t.rowIndex,rowPinned:t.rowPinned})})}pasteMultipleValues(e,t,s,o,i,r,l){let a=t;const n=this.clientSideRowModel!=null&&!this.gos.get("enableGroupEdit")&&!this.gos.get("treeData"),u=()=>{for(;;){if(!a)return null;const c=this.rowPositionUtils.getRowNode(a);if(a=this.cellNavigationService.getRowBelow({rowPinned:a.rowPinned,rowIndex:a.rowIndex}),c==null)return null;if(!(c.detail||c.footer||n&&c.group))return c}};e.forEach(c=>{const h=u();h&&(c.forEach((p,g)=>this.updateCellValue(h,o[g],p,i,r,l)),s.push(h))})}updateCellValue(e,t,s,o,i,r){if(!e||!t||!t.isCellEditable(e)||t.isSuppressPaste(e))return;const l=this.processCell(e,t,s,i,this.gos.getCallback("processCellFromClipboard"),!0);e.setDataValue(t,l,SOURCE_PASTE);const{rowIndex:a,rowPinned:n}=e,u=this.cellPositionUtils.createIdFromValues({rowIndex:a,column:t,rowPinned:n});o[u]=!0,r&&r.addParentNode(e.parent,[t])}copyToClipboard(e={}){this.copyOrCutToClipboard(e)}cutToClipboard(e={},t="api"){this.gos.get("suppressCutToClipboard")||(this.eventService.dispatchEvent({type:"cutStart",source:t}),this.copyOrCutToClipboard(e,!0),this.eventService.dispatchEvent({type:"cutEnd",source:t}))}copyOrCutToClipboard(e,t){let{includeHeaders:s,includeGroupHeaders:o}=e;s==null&&(s=this.gos.get("copyHeadersToClipboard")),o==null&&(o=this.gos.get("copyGroupHeadersToClipboard"));const i={includeHeaders:s,includeGroupHeaders:o},r=this.gos.get("rowSelection"),l=this.gos.get("cellSelection");let a=null;this.shouldCopyCells(l,r)?(this.copySelectedRangeToClipboard(i),a=0):this.shouldCopyRows(r)?(this.copySelectedRowsToClipboard(i),a=1):this.focusService.isAnyCellFocused()&&(this.copyFocusedCellToClipboard(i),a=2),t&&a!==null&&this.clearCellsAfterCopy(a)}shouldCopyCells(e,t){if(!this.rangeService||this.rangeService.isEmpty())return!1;if(e)return!(typeof t=="object"&&t.copySelectedRows&&!this.selectionService.isEmpty());{const s=this.gos.get("suppressCopySingleCellRanges");return!(!this.rangeService.isMoreThanOneCell()&&s)}}shouldCopyRows(e){return this.selectionService.isEmpty()?!1:e&&typeof e!="string"?e.copySelectedRows??!1:!this.gos.get("suppressCopyRowsToClipboard")}clearCellsAfterCopy(e){if(this.eventService.dispatchEvent({type:"keyShortcutChangedCellStart"}),e===0)this.rangeService.clearCellRangeCellValues({cellEventSource:"clipboardService"});else if(e===1)this.clearSelectedRows();else{const t=this.focusService.getFocusedCell();if(t==null)return;const s=this.rowPositionUtils.getRowNode(t);s&&this.clearCellValue(s,t.column)}this.eventService.dispatchEvent({type:"keyShortcutChangedCellEnd"})}clearSelectedRows(){const e=this.selectionService.getSelectedNodes(),t=this.visibleColsService.getAllCols();for(const s of e)for(const o of t)this.clearCellValue(s,o)}clearCellValue(e,t){if(!t.isCellEditable(e))return;const s=this.valueService.getDeleteValue(t,e);e.setDataValue(t,s,"clipboardService")}iterateActiveRanges(e,t,s){if(!this.rangeService||this.rangeService.isEmpty())return;const o=this.rangeService.getCellRanges();e?this.iterateActiveRange(o[0],t,s,!0):o.forEach((i,r)=>this.iterateActiveRange(i,t,s,r===o.length-1))}iterateActiveRange(e,t,s,o){if(!this.rangeService)return;let i=this.rangeService.getRangeStartRow(e);const r=this.rangeService.getRangeEndRow(e);s&&e.columns&&s(e.columns);let l=0,a=!1;for(;!a&&i!=null;){const n=this.rowPositionUtils.getRowNode(i);a=this.rowPositionUtils.sameRow(i,r),t(i,n,e.columns,l++,a&&o),i=this.cellNavigationService.getRowBelow(i)}}copySelectedRangeToClipboard(e={}){if(!this.rangeService||this.rangeService.isEmpty())return;const t=this.rangeService.areAllRangesAbleToMerge(),{data:s,cellsToFlash:o}=t?this.buildDataFromMergedRanges(this.rangeService,e):this.buildDataFromRanges(this.rangeService,e);this.copyDataToClipboard(s),this.dispatchFlashCells(o)}buildDataFromMergedRanges(e,t){const s=new Set,o=e.getCellRanges(),i=new Map,r=[],l={};o.forEach(c=>{c.columns.forEach(g=>s.add(g));const{rowPositions:h,cellsToFlash:p}=this.getRangeRowPositionsAndCellsToFlash(e,c);h.forEach(g=>{const C=`${g.rowIndex}-${g.rowPinned||"null"}`;i.get(C)||(i.set(C,!0),r.push(g))}),Object.assign(l,p)});const a=this.visibleColsService.getAllCols(),n=Array.from(s);return n.sort((c,h)=>{const p=a.indexOf(c),g=a.indexOf(h);return p-g}),{data:this.buildExportParams({columns:n,rowPositions:r,includeHeaders:t.includeHeaders,includeGroupHeaders:t.includeGroupHeaders}),cellsToFlash:l}}buildDataFromRanges(e,t){const s=e.getCellRanges(),o=[],i={};return s.forEach(r=>{const{rowPositions:l,cellsToFlash:a}=this.getRangeRowPositionsAndCellsToFlash(e,r);Object.assign(i,a),o.push(this.buildExportParams({columns:r.columns,rowPositions:l,includeHeaders:t.includeHeaders,includeGroupHeaders:t.includeGroupHeaders}))}),{data:o.join(`
`),cellsToFlash:i}}getRangeRowPositionsAndCellsToFlash(e,t){const s=[],o={},i=e.getRangeStartRow(t),r=e.getRangeEndRow(t);let l=i;for(;l&&(s.push(l),t.columns.forEach(a=>{const{rowIndex:n,rowPinned:u}=l,c=this.cellPositionUtils.createIdFromValues({rowIndex:n,column:a,rowPinned:u});o[c]=!0}),!this.rowPositionUtils.sameRow(l,r));)l=this.cellNavigationService.getRowBelow(l);return{rowPositions:s,cellsToFlash:o}}getCellsToFlashFromRowNodes(e){const t=this.visibleColsService.getAllCols(),s={};for(let o=0;o<e.length;o++){const{rowIndex:i,rowPinned:r}=e[o];if(i!=null)for(let l=0;l<t.length;l++){const a=t[l],n=this.cellPositionUtils.createIdFromValues({rowIndex:i,column:a,rowPinned:r});s[n]=!0}}return s}copyFocusedCellToClipboard(e={}){const t=this.focusService.getFocusedCell();if(t==null)return;const s=this.cellPositionUtils.createId(t),o={rowPinned:t.rowPinned,rowIndex:t.rowIndex},i=t.column,r=this.buildExportParams({columns:[i],rowPositions:[o],includeHeaders:e.includeHeaders,includeGroupHeaders:e.includeGroupHeaders});this.copyDataToClipboard(r),this.dispatchFlashCells({[s]:!0})}copySelectedRowsToClipboard(e={}){const{columnKeys:t,includeHeaders:s,includeGroupHeaders:o}=e,i=this.buildExportParams({columns:t,includeHeaders:s,includeGroupHeaders:o});this.copyDataToClipboard(i);const r=this.selectionService.getSelectedNodes()||[];this.dispatchFlashCells(this.getCellsToFlashFromRowNodes(r))}buildExportParams(e){const{columns:t,rowPositions:s,includeHeaders:o=!1,includeGroupHeaders:i=!1}=e,r={columnKeys:t,rowPositions:s,skipColumnHeaders:!o,skipColumnGroupHeaders:!i,suppressQuotes:!0,columnSeparator:this.getClipboardDelimiter(),onlySelected:!s,processCellCallback:this.gos.getCallback("processCellForClipboard"),processRowGroupCallback:l=>this.processRowGroupCallback(l),processHeaderCallback:this.gos.getCallback("processHeaderForClipboard"),processGroupHeaderCallback:this.gos.getCallback("processGroupHeaderForClipboard")};return this.csvCreator.getDataAsCsv(r,!0)}processRowGroupCallback(e){const{node:t,column:s}=e,o=this.gos.get("treeData"),i=this.gos.get("suppressGroupMaintainValueType");let l=(()=>{if(o||i||!s)return t.key;const n=t.groupData?.[s.getId()];return!n||!t.rowGroupColumn||t.rowGroupColumn.getColDef().useValueFormatterForExport===!1?n:this.valueService.formatValue(t.rowGroupColumn,t,n)??n})();if(e.node.footer){let n="";l&&l.length&&(n=` ${l}`),l=`Total${n}`}const a=this.gos.getCallback("processCellForClipboard");if(a){let n=t.rowGroupColumn;return!n&&t.footer&&t.level===-1&&(n=this.funcColsService.getRowGroupColumns()[0]),a({value:l,node:t,column:n,type:"clipboard",formatValue:u=>this.valueService.formatValue(n,t,u)??u,parseValue:u=>this.valueService.parseValue(n,t,u,this.valueService.getValue(n,t))})}return l}dispatchFlashCells(e){window.setTimeout(()=>{this.eventService.dispatchEvent({type:"flashCells",cells:e})},0)}processCell(e,t,s,o,i,r,l){return i?i({column:t,node:e,value:s,type:o,formatValue:n=>this.valueService.formatValue(t,e??null,n)??n,parseValue:n=>this.valueService.parseValue(t,e??null,n,this.valueService.getValue(t,e))}):r&&t.getColDef().useValueParserForImport!==!1?this.valueService.parseValue(t,e??null,s,this.valueService.getValue(t,e)):l&&t.getColDef().useValueFormatterForExport!==!1?this.valueService.formatValue(t,e??null,s)??s:s}copyDataToClipboard(e){const t=this.gos.getCallback("sendToClipboard");if(t){t({data:e});return}if(!this.gos.get("suppressClipboardApi")&&navigator.clipboard){navigator.clipboard.writeText(e).catch(o=>{(0,import_core._warnOnce)(`${o}
${apiError("writeText")}`),this.copyDataToClipboardLegacy(e)});return}this.copyDataToClipboardLegacy(e)}copyDataToClipboardLegacy(e){this.executeOnTempElement(t=>{const s=(0,import_core._getDocument)(this.gos),o=(0,import_core._getActiveDomElement)(this.gos);t.value=e||" ",t.select(),t.focus({preventScroll:!0}),s.execCommand("copy")||(0,import_core._warnOnce)("Browser did not allow document.execCommand('copy'). Ensure api.copySelectedRowsToClipboard() is invoked via a user event, i.e. button click, otherwise the browser will prevent it for security reasons."),o!=null&&o.focus!=null&&o.focus({preventScroll:!0})})}executeOnTempElement(e,t){const s=(0,import_core._getDocument)(this.gos),o=s.createElement("textarea");o.style.width="1px",o.style.height="1px",o.style.top=s.documentElement.scrollTop+"px",o.style.left=s.documentElement.scrollLeft+"px",o.style.position="absolute",o.style.opacity="0";const i=this.gridCtrl.getGui();i.appendChild(o);try{e(o)}catch{(0,import_core._warnOnce)("Browser does not support document.execCommand('copy') for clipboard operations")}t?window.setTimeout(()=>{t(o),i.removeChild(o)},100):i.removeChild(o)}getRangeSize(e){const t=e.getCellRanges();let s=0,o=0;return t.length>0&&(s=e.getRangeStartRow(t[0]).rowIndex,o=e.getRangeEndRow(t[0]).rowIndex),s-o+1}},VERSION="32.3.8",ClipboardCoreModule=(0,import_core2._defineModule)({version:VERSION,moduleName:`${import_core2.ModuleNames.ClipboardModule}-core`,beans:[ClipboardService],dependantModules:[import_core3.EnterpriseCoreModule,import_csv_export.CsvExportModule]}),ClipboardApiModule=(0,import_core2._defineModule)({version:VERSION,moduleName:`${import_core2.ModuleNames.ClipboardModule}-api`,apiFunctions:{copyToClipboard,cutToClipboard,copySelectedRowsToClipboard,copySelectedRangeToClipboard,copySelectedRangeDown,pasteFromClipboard},dependantModules:[ClipboardCoreModule]}),ClipboardModule=(0,import_core2._defineModule)({version:VERSION,moduleName:import_core2.ModuleNames.ClipboardModule,dependantModules:[ClipboardCoreModule,ClipboardApiModule]});