@8sheets/data-grid 1.1.1 → 1.2.0
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/README.md +1 -1
- package/a11y/cell-alt-text.js +1 -1
- package/api/serialize.js +1 -1
- package/api/style-refs.js +1 -1
- package/calc/adjust.js +1 -1
- package/calc/compile.js +1 -1
- package/calc/engine.js +1 -1
- package/calc/functions/array.js +1 -1
- package/calc/functions/database.js +1 -1
- package/calc/functions/date.js +1 -1
- package/calc/functions/engineering.js +1 -1
- package/calc/functions/financial.js +1 -1
- package/calc/functions/helpers.js +1 -1
- package/calc/functions/index.js +3 -2
- package/calc/functions/info.js +1 -1
- package/calc/functions/logical.js +1 -1
- package/calc/functions/lookup.js +1 -1
- package/calc/functions/math.js +1 -1
- package/calc/functions/stat.js +1 -1
- package/calc/functions/text.js +1 -1
- package/calc/parser.js +2 -2
- package/calc/shown-refs.js +1 -0
- package/calc/values.js +1 -1
- package/calcx/calc-control.js +1 -0
- package/calcx/external-read.js +1 -1
- package/calcx/external.js +1 -1
- package/calcx/lang/convert.js +1 -1
- package/cells/axis-ops.js +1 -1
- package/cells/book-css.js +7 -2
- package/cells/cell-styles-xml.js +1 -1
- package/cells/cf-engine.js +1 -1
- package/cells/cf-file.js +1 -1
- package/cells/docprops-xml.js +2 -2
- package/cells/filter-eval.js +1 -0
- package/cells/filter-file.js +1 -1
- package/cells/find-engine.js +2 -2
- package/cells/find.js +1 -1
- package/cells/goto.js +1 -1
- package/cells/link-model.js +1 -0
- package/cells/name-box.js +1 -1
- package/cells/note-box.js +3 -0
- package/cells/options.js +1 -1
- package/cells/outline-column.js +1 -1
- package/cells/protected-menu.js +1 -0
- package/cells/rich-data-xml.js +1 -1
- package/cells/selection-modes.js +1 -1
- package/cells/sheet-views-file.js +2 -0
- package/cells/shift-check.js +1 -1
- package/cells/sort-compare.js +1 -0
- package/cells/ui-kit.js +1 -1
- package/cells/undo-group.js +1 -1
- package/celltypes/dropdowns.js +2 -2
- package/core/address.js +1 -1
- package/core/autofill.js +1 -1
- package/core/axis.js +1 -1
- package/core/cond-format.js +1 -1
- package/core/culture.js +5 -1
- package/core/custom-views.js +1 -1
- package/core/data-tools.js +1 -0
- package/core/date-codes.js +1 -0
- package/core/default-names.js +1 -1
- package/core/edit-ranges.js +1 -0
- package/core/formula-refs.js +1 -1
- package/core/host-rules.js +1 -0
- package/core/input.js +1 -1
- package/core/numfmt.js +1 -1
- package/core/precision.js +1 -0
- package/core/protection.js +1 -1
- package/core/region-input.js +1 -1
- package/core/rule-refs.js +1 -0
- package/core/shared-view.js +1 -0
- package/core/sheet.js +1 -1
- package/core/sparklines.js +1 -1
- package/core/sparse.js +1 -1
- package/core/spills.js +1 -0
- package/core/strings.js +1 -1
- package/core/structure.js +1 -1
- package/core/table-columns.js +1 -0
- package/core/tables.js +2 -2
- package/core/validation-ranges.js +1 -1
- package/core/whatif.js +1 -1
- package/core/workbook.js +1 -1
- package/datasheets/formula.js +1 -1
- package/datasheets/manager.js +1 -1
- package/datasheets/path-binding.js +1 -1
- package/datasheets/persist-writer.js +1 -1
- package/datasheets/persist.js +1 -1
- package/datasheets/report.js +1 -1
- package/extras/getdata/persist.js +2 -2
- package/extras/getdata/rows.js +1 -1
- package/extras/getdata/shared-steps.js +1 -0
- package/extras/getdata/steps-formula.js +1 -0
- package/extras/getdata/steps-more.js +1 -0
- package/extras/getdata/steps-tables.js +1 -0
- package/extras/getdata/steps.js +1 -1
- package/i18n/de/a11y.js +1 -0
- package/i18n/de/cells.js +2 -0
- package/i18n/de/charts.js +1 -0
- package/i18n/de/common.js +1 -0
- package/i18n/de/datasheets.js +1 -0
- package/i18n/de/format.js +1 -0
- package/i18n/de/misc.js +1 -0
- package/i18n/de/pivot.js +1 -0
- package/i18n/de/proofing.js +1 -0
- package/i18n/de/ribbon.js +1 -0
- package/i18n/de/shapes.js +1 -0
- package/i18n/de/shell.js +3 -0
- package/i18n/de/touch.js +1 -0
- package/i18n/de.js +1 -0
- package/i18n/en/cells.js +2 -1
- package/i18n/en/charts.js +1 -1
- package/i18n/en/format.js +1 -1
- package/i18n/en/misc.js +1 -1
- package/i18n/en/pivot.js +1 -1
- package/i18n/en/proofing.js +1 -1
- package/i18n/en/ribbon.js +1 -1
- package/i18n/en/shapes.js +1 -1
- package/i18n/en/shell.js +3 -2
- package/i18n/en/touch.js +1 -1
- package/i18n/es/a11y.js +1 -0
- package/i18n/es/cells.js +2 -0
- package/i18n/es/charts.js +1 -0
- package/i18n/es/common.js +1 -0
- package/i18n/es/datasheets.js +1 -0
- package/i18n/es/format.js +1 -0
- package/i18n/es/misc.js +1 -0
- package/i18n/es/pivot.js +1 -0
- package/i18n/es/proofing.js +1 -0
- package/i18n/es/ribbon.js +1 -0
- package/i18n/es/shapes.js +1 -0
- package/i18n/es/shell.js +3 -0
- package/i18n/es/touch.js +1 -0
- package/i18n/es.js +1 -0
- package/i18n/fr/a11y.js +1 -0
- package/i18n/fr/cells.js +2 -0
- package/i18n/fr/charts.js +1 -0
- package/i18n/fr/common.js +1 -0
- package/i18n/fr/datasheets.js +1 -0
- package/i18n/fr/format.js +1 -0
- package/i18n/fr/misc.js +1 -0
- package/i18n/fr/pivot.js +1 -0
- package/i18n/fr/proofing.js +1 -0
- package/i18n/fr/ribbon.js +1 -0
- package/i18n/fr/shapes.js +1 -0
- package/i18n/fr/shell.js +3 -0
- package/i18n/fr/touch.js +1 -0
- package/i18n/fr.js +1 -0
- package/i18n/index.js +1 -1
- package/i18n/languages.js +1 -1
- package/i18n/pl/cells.js +2 -1
- package/i18n/pl/charts.js +1 -1
- package/i18n/pl/format.js +1 -1
- package/i18n/pl/misc.js +1 -1
- package/i18n/pl/pivot.js +1 -1
- package/i18n/pl/proofing.js +1 -1
- package/i18n/pl/ribbon.js +1 -1
- package/i18n/pl/shapes.js +1 -1
- package/i18n/pl/shell.js +3 -2
- package/i18n/pl/touch.js +1 -1
- package/io/blob-sink.js +1 -0
- package/io/canonical-xml.js +1 -0
- package/io/client.js +1 -1
- package/io/crypto/cfb-build.js +1 -0
- package/io/crypto/cfb-read.js +1 -1
- package/io/crypto/cfb-write.js +1 -1
- package/io/crypto/errors.js +1 -1
- package/io/csv.js +8 -8
- package/io/encoding.js +1 -0
- package/io/foreign-sheets.js +2 -2
- package/io/io.worker.js +1 -1
- package/io/open-package.js +1 -0
- package/io/package-paths.js +1 -1
- package/io/plan.js +1 -1
- package/io/text-split.js +3 -3
- package/io/xls/chart-sheet.js +1 -0
- package/io/xls/chart.js +1 -0
- package/io/xls/crypt.js +1 -0
- package/io/xls/dml-color.js +1 -0
- package/io/xls/drawing.js +1 -0
- package/io/xls/formula.js +1 -0
- package/io/xls/geometry.js +1 -0
- package/io/xls/index.js +1 -0
- package/io/xls/pictures.js +1 -0
- package/io/xls/pivot.js +1 -0
- package/io/xls/props.js +1 -0
- package/io/xls/records.js +1 -0
- package/io/xls/shapes.js +1 -0
- package/io/xls/sheet-ext.js +1 -0
- package/io/xls/sheet.js +1 -0
- package/io/xls/styles.js +1 -0
- package/io/xls/vba.js +1 -0
- package/io/xls/workbook.js +1 -0
- package/io/xlsb/filter.js +1 -0
- package/io/xlsb/formula.js +2 -0
- package/io/xlsb/functions.js +1 -0
- package/io/xlsb/index.js +1 -0
- package/io/xlsb/parts.js +1 -0
- package/io/xlsb/pivot.js +1 -0
- package/io/xlsb/records.js +1 -0
- package/io/xlsb/sheet-ext.js +1 -0
- package/io/xlsb/sheet.js +1 -0
- package/io/xlsb/slicer.js +1 -0
- package/io/xlsb/styles.js +1 -0
- package/io/xlsb/workbook.js +1 -0
- package/io/xlsb/xml.js +2 -0
- package/io/xlsx-read.js +1 -1
- package/io/xlsx-styles.js +2 -2
- package/io/xlsx-tail.js +1 -1
- package/io/xlsx-write.js +2 -2
- package/io/xml-escape.js +1 -1
- package/io/xml-scan.js +2 -2
- package/io/zip-reader.js +1 -1
- package/objects/chart-model.js +1 -1
- package/objects/drawing-xml.js +1 -1
- package/package.json +1 -1
- package/pivot/calc-items.js +1 -0
- package/pivot/engine.js +1 -1
- package/pivot/xml.js +2 -2
- package/print/note-pages.js +2 -0
- package/print/page-setup.js +1 -1
- package/print/paginate.js +1 -1
- package/print/pdf-crypt.js +1 -0
- package/print/pdf-links.js +1 -0
- package/print/pdf-tags.js +1 -0
- package/print/pdf.js +24 -13
- package/print/render-page.js +3 -3
- package/print/shown-notes.js +1 -0
- package/shapes/form-xml.js +1 -1
- package/slicers/custom-styles.js +1 -1
- package/slicers/format.js +1 -1
- package/slicers/structured.js +1 -1
- package/slicers/write.js +1 -1
- package/table-view/files.js +1 -1
- package/table-view/mount.js +1 -1
- package/table-view/version.js +1 -1
- package/ui/dialogs.js +3 -3
- package/ui/icons.js +1 -1
- package/ui/menu-base.js +1 -1
- package/ui/protection-ui.js +1 -1
package/cells/cell-styles-xml.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{child as m,children as y,parseTree as X,unescapeOoxml as b,unescapeXstring as g}from"../io/xml-scan.js";import{xmlAttr as h}from"../io/xml-escape.js";function $(l){const t=new Map;for(const e of y(m(l,"cellStyles"),"cellStyle")){const n=Number(e.a.xfId??0);t.has(n)||t.set(n,{name:b(e.a.name),builtinId:e.a.builtinId===void 0?void 0:Number(e.a.builtinId)})}return t}function C(l,t){const e=$(t);return e.size<=1||y(m(t,"cellXfs"),"xf").forEach((n,c)=>{const s=e.get(Number(n.a.xfId??0));s&&s.name!=="Normal"&&l[c]&&(l[c].namedStyle=s.name)}),l}function P(l,t,e){const n=X(new TextEncoder().encode(l)),c=l.replace(/<cellXfs\b[\s\S]*?<\/cellXfs>/,"").replace(/<cellXfs\b[^>]*\/>/,"").replace(/cellStyleXfs/g,"cellXfs"),s=e(new TextEncoder().encode(c),t),o=y(m(n,"cellStyleXfs"),"xf"),u=new Map;for(const r of y(m(n,"cellStyles"),"cellStyle")){const i=Number(r.a.xfId??0),a=s[i];if(!a||!r.a.name)continue;const f=o[i]?.a??{},d=x=>x!=="0"&&x!=="false",p={number:d(f.applyNumberFormat),alignment:d(f.applyAlignment),font:d(f.applyFont),border:d(f.applyBorder),fill:d(f.applyFill),protection:d(f.applyProtection)},S=b(r.a.name);u.set(S,{name:S,style:a,builtinId:r.a.builtinId===void 0?void 0:Number(r.a.builtinId),xfId:i,includes:p,inFile:!0})}return u}function B(l){const t=l.namedStyles;if(!t||t.size===0)return null;const e=[];let n=Math.max(1,l.styleXfCount??1);for(const c of t.values()){if(c.deleted&&!c.inFile)continue;if(l.source!==null&&c.inFile&&!c.changed&&!c.deleted){e.push({name:c.name,xfId:c.xfId,keep:!0});continue}const s=!c.inFile&&c.name!=="Normal";s&&(c.pendingXf=n++),e.push({name:c.name,builtinId:c.builtinId,style:c.style,includes:c.includes,xfId:s?c.pendingXf:c.xfId??0,isNew:s,deleted:c.deleted===!0})}return l.styleXfNext=n,e}function M(l,t,e=!0){if(l.namedStyles){for(const n of t??[]){const c=n.name,s=l.namedStyles.get(c);if(s){if(n.deleted&&!s.deleted){s.inFile=!1;continue}if(n.deleted){l.namedStyles.delete(c);continue}!s.inFile&&s.name!=="Normal"&&(s.xfId=n.xfId),s.inFile=!0,e&&(s.changed=!1)}}l.styleXfNext&&(l.styleXfCount=l.styleXfNext)}}const N=l=>l.number?' applyNumberFormat="1"':' applyNumberFormat="0"';function F(l,t){let e=l.replace(/\s+xfId="\d+"/,"").replace(/\s+apply(?:NumberFormat|Font|Fill|Border|Alignment|Protection)="\d"/g,"");const n=t??{number:!0,font:!0,fill:!0,border:!0,alignment:!0,protection:!0},c=`${N(n)}${n.font?' applyFont="1"':' applyFont="0"'}${n.fill?' applyFill="1"':' applyFill="0"'}${n.border?' applyBorder="1"':' applyBorder="0"'}${n.alignment?' applyAlignment="1"':' applyAlignment="0"'}${n.protection?' applyProtection="1"':' applyProtection="0"'}`;return e=e.replace(/^<xf\b/,"<xf").replace(/(<xf\b[^>]*?)(\/?>)/,`$1${c}$2`),e}function E(l,t){if(!t)return{styles:l,finish:()=>null};const e=new Map([["Normal",0]]);for(const o of t)o.deleted||e.set(o.name,o.xfId);const n=t.filter(o=>!o.keep&&!o.deleted),c=l.map(o=>o.namedStyle&&e.has(o.namedStyle)?{...o,_xfId:e.get(o.namedStyle)}:o),s=c.length;return{styles:[...c,...n.map(o=>o.style)],finish(o){const u=o.xfs.slice(s);o.xfs=o.xfs.slice(0,s);let r=null;const i=new Map,a=[];return n.forEach((f,d)=>{const p=F(u[d],f.includes);f.isNew?a.push(p):i.set(f.xfId,p),f.name==="Normal"&&(r=u[d])}),{replaced:i,appended:a,rows:t,ids:e,normalCell:r}}}}function I(l,t,e){const n=/^(?:Row|Col)Level_([1-7])$/.exec(l);return`<cellStyle name="${h(l)}" xfId="${t}"${e!==void 0?` builtinId="${e}"`:""}${n?` iLevel="${Number(n[1])-1}"`:""}/>`}function j(l){const t='<xf numFmtId="0" fontId="0" fillId="0" borderId="0"/>';if(!l?.rows)return`<cellStyleXfs count="1">${t}</cellStyleXfs>`;const e=[l.replaced?.get(0)??t,...l.appended??[]];return`<cellStyleXfs count="${e.length}">${e.join("")}</cellStyleXfs>`}function v(l){const t=['<cellStyle name="Normal" xfId="0" builtinId="0"/>'];if(l?.rows)for(const e of l.rows)!e.deleted&&e.name!=="Normal"&&t.push(I(e.name,l.ids.get(e.name),e.builtinId));return`<cellStyles count="${t.length}">${t.join("")}</cellStyles>`}function L(l){const t=/<cellStyleXfs\b[^>]*>([\s\S]*?)<\/cellStyleXfs>/.exec(l);return t?(t[1].match(/<xf\b/g)??[]).length:0}function T(l,t){if(!t?.rows)return l;let e=l;/<cellStyleXfs\b/.test(e)||(e=e.replace(/<cellXfs\b/,'<cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs><cellXfs')),e=e.replace(/<cellStyleXfs\b[^>]*>([\s\S]*?)<\/cellStyleXfs>/,(r,i)=>{const a=[...i.matchAll(/<xf\b[^>]*?(?:\/>|>[\s\S]*?<\/xf>)/g)].map(f=>f[0]);for(const[f,d]of t.replaced)f<a.length&&(a[f]=d);return a.push(...t.appended),`<cellStyleXfs count="${a.length}">${a.join("")}</cellStyleXfs>`}),t.normalCell&&(e=e.replace(/(<cellXfs\b[^>]*>)\s*<xf\b[^>]*?(?:\/>|>[\s\S]*?<\/xf>)/,(r,i)=>`${i}${t.normalCell.replace(/\s+xfId="\d+"/,' xfId="0"')}`));const n=/<cellStyles\b[^>]*>([\s\S]*?)<\/cellStyles>/.exec(e),c=n?[...n[1].matchAll(/<cellStyle\b[^>]*?(?:\/>|>[\s\S]*?<\/cellStyle>)/g)].map(r=>r[0]):['<cellStyle name="Normal" xfId="0" builtinId="0"/>'],s=r=>{const i=/\bname="([^"]*)"/.exec(r)?.[1];return i===void 0?void 0:g(i)},o=c.filter(r=>!t.rows.some(i=>i.deleted&&i.name===s(r)));for(const r of t.rows)r.deleted||r.keep||o.some(i=>s(i)===r.name)||o.push(I(r.name,t.ids.get(r.name),r.builtinId));const u=`<cellStyles count="${o.length}">${o.join("")}</cellStyles>`;return n?e.replace(/<cellStyles\b[^>]*>[\s\S]*?<\/cellStyles>/,u):e.replace("</cellXfs>"
|
|
1
|
+
import{child as m,children as y,parseTree as X,unescapeOoxml as b,unescapeXstring as g}from"../io/xml-scan.js";import{xmlAttr as h}from"../io/xml-escape.js";function $(l){const t=new Map;for(const e of y(m(l,"cellStyles"),"cellStyle")){const n=Number(e.a.xfId??0);t.has(n)||t.set(n,{name:b(e.a.name),builtinId:e.a.builtinId===void 0?void 0:Number(e.a.builtinId)})}return t}function C(l,t){const e=$(t);return e.size<=1||y(m(t,"cellXfs"),"xf").forEach((n,c)=>{const s=e.get(Number(n.a.xfId??0));s&&s.name!=="Normal"&&l[c]&&(l[c].namedStyle=s.name)}),l}function P(l,t,e){const n=X(new TextEncoder().encode(l)),c=l.replace(/<cellXfs\b[\s\S]*?<\/cellXfs>/,"").replace(/<cellXfs\b[^>]*\/>/,"").replace(/cellStyleXfs/g,"cellXfs"),s=e(new TextEncoder().encode(c),t),o=y(m(n,"cellStyleXfs"),"xf"),u=new Map;for(const r of y(m(n,"cellStyles"),"cellStyle")){const i=Number(r.a.xfId??0),a=s[i];if(!a||!r.a.name)continue;const f=o[i]?.a??{},d=x=>x!=="0"&&x!=="false",p={number:d(f.applyNumberFormat),alignment:d(f.applyAlignment),font:d(f.applyFont),border:d(f.applyBorder),fill:d(f.applyFill),protection:d(f.applyProtection)},S=b(r.a.name);u.set(S,{name:S,style:a,builtinId:r.a.builtinId===void 0?void 0:Number(r.a.builtinId),xfId:i,includes:p,inFile:!0})}return u}function B(l){const t=l.namedStyles;if(!t||t.size===0)return null;const e=[];let n=Math.max(1,l.styleXfCount??1);for(const c of t.values()){if(c.deleted&&!c.inFile)continue;if(l.source!==null&&c.inFile&&!c.changed&&!c.deleted){e.push({name:c.name,xfId:c.xfId,keep:!0});continue}const s=!c.inFile&&c.name!=="Normal";s&&(c.pendingXf=n++),e.push({name:c.name,builtinId:c.builtinId,style:c.style,includes:c.includes,xfId:s?c.pendingXf:c.xfId??0,isNew:s,deleted:c.deleted===!0})}return l.styleXfNext=n,e}function M(l,t,e=!0){if(l.namedStyles){for(const n of t??[]){const c=n.name,s=l.namedStyles.get(c);if(s){if(n.deleted&&!s.deleted){s.inFile=!1;continue}if(n.deleted){l.namedStyles.delete(c);continue}!s.inFile&&s.name!=="Normal"&&(s.xfId=n.xfId),s.inFile=!0,e&&(s.changed=!1)}}l.styleXfNext&&(l.styleXfCount=l.styleXfNext)}}const N=l=>l.number?' applyNumberFormat="1"':' applyNumberFormat="0"';function F(l,t){let e=l.replace(/\s+xfId="\d+"/,"").replace(/\s+apply(?:NumberFormat|Font|Fill|Border|Alignment|Protection)="\d"/g,"");const n=t??{number:!0,font:!0,fill:!0,border:!0,alignment:!0,protection:!0},c=`${N(n)}${n.font?' applyFont="1"':' applyFont="0"'}${n.fill?' applyFill="1"':' applyFill="0"'}${n.border?' applyBorder="1"':' applyBorder="0"'}${n.alignment?' applyAlignment="1"':' applyAlignment="0"'}${n.protection?' applyProtection="1"':' applyProtection="0"'}`;return e=e.replace(/^<xf\b/,"<xf").replace(/(<xf\b[^>]*?)(\/?>)/,`$1${c}$2`),e}function E(l,t){if(!t)return{styles:l,finish:()=>null};const e=new Map([["Normal",0]]);for(const o of t)o.deleted||e.set(o.name,o.xfId);const n=t.filter(o=>!o.keep&&!o.deleted),c=l.map(o=>o.namedStyle&&e.has(o.namedStyle)?{...o,_xfId:e.get(o.namedStyle)}:o),s=c.length;return{styles:[...c,...n.map(o=>o.style)],finish(o){const u=o.xfs.slice(s);o.xfs=o.xfs.slice(0,s);let r=null;const i=new Map,a=[];return n.forEach((f,d)=>{const p=F(u[d],f.includes);f.isNew?a.push(p):i.set(f.xfId,p),f.name==="Normal"&&(r=u[d])}),{replaced:i,appended:a,rows:t,ids:e,normalCell:r}}}}function I(l,t,e){const n=/^(?:Row|Col)Level_([1-7])$/.exec(l);return`<cellStyle name="${h(l)}" xfId="${t}"${e!==void 0?` builtinId="${e}"`:""}${n?` iLevel="${Number(n[1])-1}"`:""}/>`}function j(l){const t='<xf numFmtId="0" fontId="0" fillId="0" borderId="0"/>';if(!l?.rows)return`<cellStyleXfs count="1">${t}</cellStyleXfs>`;const e=[l.replaced?.get(0)??t,...l.appended??[]];return`<cellStyleXfs count="${e.length}">${e.join("")}</cellStyleXfs>`}function v(l){const t=['<cellStyle name="Normal" xfId="0" builtinId="0"/>'];if(l?.rows)for(const e of l.rows)!e.deleted&&e.name!=="Normal"&&t.push(I(e.name,l.ids.get(e.name),e.builtinId));return`<cellStyles count="${t.length}">${t.join("")}</cellStyles>`}function L(l){const t=/<cellStyleXfs\b[^>]*>([\s\S]*?)<\/cellStyleXfs>/.exec(l);return t?(t[1].match(/<xf\b/g)??[]).length:0}function T(l,t){if(!t?.rows)return l;let e=l;/<cellStyleXfs\b/.test(e)||(e=e.replace(/<cellXfs\b/,'<cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs><cellXfs')),e=e.replace(/<cellStyleXfs\b[^>]*>([\s\S]*?)<\/cellStyleXfs>/,(r,i)=>{const a=[...i.matchAll(/<xf\b[^>]*?(?:\/>|>[\s\S]*?<\/xf>)/g)].map(f=>f[0]);for(const[f,d]of t.replaced)f<a.length&&(a[f]=d);return a.push(...t.appended),`<cellStyleXfs count="${a.length}">${a.join("")}</cellStyleXfs>`}),t.normalCell&&(e=e.replace(/(<cellXfs\b[^>]*>)\s*<xf\b[^>]*?(?:\/>|>[\s\S]*?<\/xf>)/,(r,i)=>`${i}${t.normalCell.replace(/\s+xfId="\d+"/,' xfId="0"')}`));const n=/<cellStyles\b[^>]*>([\s\S]*?)<\/cellStyles>/.exec(e),c=n?[...n[1].matchAll(/<cellStyle\b[^>]*?(?:\/>|>[\s\S]*?<\/cellStyle>)/g)].map(r=>r[0]):['<cellStyle name="Normal" xfId="0" builtinId="0"/>'],s=r=>{const i=/\bname="([^"]*)"/.exec(r)?.[1];return i===void 0?void 0:g(i)},o=c.filter(r=>!t.rows.some(i=>i.deleted&&i.name===s(r)));for(const r of t.rows)r.deleted||r.keep||o.some(i=>s(i)===r.name)||o.push(I(r.name,t.ids.get(r.name),r.builtinId));const u=`<cellStyles count="${o.length}">${o.join("")}</cellStyles>`;return n?e.replace(/<cellStyles\b[^>]*>[\s\S]*?<\/cellStyles>/,()=>u):e.replace("</cellXfs>",()=>`</cellXfs>${u}`)}export{L as countStyleXfs,M as namedStylesCommitted,B as namedStylesPlan,v as newCellStyles,j as newStyleSections,T as patchStyleSections,P as readNamedStyles,C as tagNamedStyles,E as withNamedStyles};
|
package/cells/cf-engine.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{parseRangeRef as R}from"../core/address.js";import{CHUNK_BITS as C,CHUNK_MASK as N,DIRTY as D,KIND_MASK as T,NUM as B}from"../core/sheet.js";import{partsToSerial as V,serialToParts as k}from"../core/numfmt.js";import{compareValues as v,XlError as b}from"../calc/values.js";import{wildcardRegex as q}from"../calc/functions/helpers.js";import{resolveColor as P}from"../io/xlsx-styles.js";const W=c=>c.split(/\s+/).map(R).filter(Boolean),K=1<<19,w=Object.freeze({}),E=new Set(["colorScale","dataBar","iconSet"]),$=c=>[parseInt(c.slice(1,3),16),parseInt(c.slice(3,5),16),parseInt(c.slice(5,7),16)],F=c=>(c<16?"0":"")+c.toString(16),I=c=>c<0?0:c>1?1:c;function U(c,s){const o={...s,...c};return(c.fill!==void 0||c.pattern!==void 0||c.gradient!==void 0||c.noFill)&&(c.pattern===void 0&&delete o.pattern,c.gradient===void 0&&delete o.gradient,c.fill===void 0&&delete o.fill,c.noFill||delete o.noFill),c.borders&&s.borders&&(o.borders={l:c.borders.l??s.borders.l,r:c.borders.r??s.borders.r,t:c.borders.t??s.borders.t,b:c.borders.b??s.borders.b}),o}const O=c=>c instanceof b?String(c.code??c.message??c).toLowerCase():typeof c=="boolean"?c?"true":"false":String(c).toLowerCase();class H{constructor(s,o,n){this.book=s,this.sheet=o,this.colorOf=n??(e=>P(e,s.theme??[])),this.cache=new Map,this.stats=new Map,this.data=new Map,this.flat=null,this.flatOf=null,this.today=0}invalidate(){this.cache.clear(),this.stats.clear(),this.data.clear(),this.flat=null,this.today=0}_rules(){const{cf:s}=this.sheet;if(this.flat!==null&&this.flatOf===s)return this.flat;const o=[];for(const n of s??[]){n._ranges===void 0&&(n._ranges=W(n.sqref));const e=n._ranges;if(e.length===0)continue;let t=1/0,r=1/0,i=-1,l=-1;for(const a of e)a.r0<t&&(t=a.r0),a.c0<r&&(r=a.c0),a.r1>i&&(i=a.r1),a.c1>l&&(l=a.c1);n._base={r0:t,c0:r};for(const a of n.rules)o.push({rule:a,block:n,r0:t,c0:r,r1:i,c1:l,single:e.length===1})}return o.sort((n,e)=>n.rule.priority-e.rule.priority),this.flat=o,this.flatOf=s,this.stoppers=o.filter(n=>n.rule.stopIfTrue&&!E.has(n.rule.type)),o}stoppedBefore(s,o,n){this._rules();for(const e of this.stoppers){if(e.rule.priority>=s)break;if(!(o<e.r0||o>e.r1||n<e.c0||n>e.c1)&&!(!e.single&&!e.block._ranges.some(t=>o>=t.r0&&o<=t.r1&&n>=t.c0&&n<=t.c1))&&this._evaluate(e.rule,e.block,o,n)!==null)return!0}return!1}at(s,o){this.valueRevision!==this.book.formatValueRevision&&(this.invalidate(),this.valueRevision=this.book.formatValueRevision);const n=s*16384+o,e=this.cache.get(n);if(e!==void 0)return e;const t=this._rules();let r=null;for(let i=0;i<t.length;i++){const l=t[i];if(s<l.r0||s>l.r1||o<l.c0||o>l.c1)continue;if(!l.single){const h=l.block._ranges;let d=!1;for(let f=0;f<h.length&&!d;f++){const m=h[f];d=s>=m.r0&&s<=m.r1&&o>=m.c0&&o<=m.c1}if(!d)continue}const a=this._evaluate(l.rule,l.block,s,o);if(a===null)continue;const u=l.block.managedBy?{...a,fieldWarning:a}:a;if(r=r===null?u:U(r,u),l.rule.stopIfTrue&&!E.has(l.rule.type))break}return this.cache.size>=K&&this.cache.clear(),this.cache.set(n,r),r}_value(s,o){return this.book.engine?this.book.engine.read(this.sheet,s,o):null}_stat(s){let o=this.stats.get(s);if(o!==void 0)return o;const{sheet:n}=this,{engine:e}=this.book;let t=new Float64Array(1024),r=0;for(const u of s._ranges){const h=Math.min(u.c1,n.maxCol),d=Math.min(u.r1,n.maxRow);for(let f=u.c0;f<=h;f++){const m=n.columns[f];if(m!==void 0)for(let p=u.r0>>>C;p<=d>>>C;p++){const _=m[p];if(_===void 0)continue;const x=p<<C,y=Math.max(u.r0-x,0),M=Math.min(d-x,N),{kinds:A,values:L}=_;if(r+(M-y+1)>t.length){const g=new Float64Array(Math.max(t.length*2,r+M-y+1));g.set(t),t=g}for(let g=y;g<=M;g++){const S=A[g];S!==0&&(S&D?(e&&e.read(n,x+g,f),(A[g]&T)===B&&(t[r++]=L[g])):(S&T)===B&&(t[r++]=L[g]))}}}}t=t.subarray(0,r).sort();let i=0;for(let u=0;u<r;u++)i+=t[u];const l=r?i/r:0;let a=0;for(let u=0;u<r;u++)a+=(t[u]-l)**2;return o={nums:t,n:r,mean:l,stdP:r>0?Math.sqrt(a/r):0,min:r?t[0]:0,max:r?t[r-1]:0,others:null,texts:null,wild:null},this.stats.set(s,o),o}_others(s){const o=this._stat(s);if(o.others!==null)return o.others;const n=new Map;for(const e of s._ranges)this.book.engine?.scan({sheet:this.sheet,r0:e.r0,c0:e.c0,r1:e.r1,c1:e.c1},t=>{if(typeof t=="number")return;const r=O(t);n.set(r,(n.get(r)??0)+1)});return o.others=n,n}_numberCount(s,o){const{nums:n,n:e}=this._stat(s);let t=0,r=e;for(;t<r;){const i=t+r>>>1;n[i]<o?t=i+1:r=i}return t>=e||n[t]!==o?0:t+1<e&&n[t+1]===o?2:1}_wildcardCount(s,o){const n=this._stat(s);if(n.texts===null){n.texts=new Map;for(const r of s._ranges)this.book.engine?.scan({sheet:this.sheet,r0:r.r0,c0:r.c0,r1:r.r1,c1:r.c1},i=>{typeof i=="string"&&n.texts.set(i.toLowerCase(),(n.texts.get(i.toLowerCase())??0)+1)})}n.wild??=new Map;const e=o.toLowerCase();let t=n.wild.get(e);if(t===void 0){const r=q(o);t=0;for(const[i,l]of n.texts)r.test(i)&&(t+=l);n.wild.set(e,t)}return t}_occurrences(s,o){if(typeof o=="string"&&/[*?]/.test(o))return this._wildcardCount(s,o);const n=this._others(s);if(typeof o=="number")return this._numberCount(s,o)+(n.get(String(o))??0);const e=O(o),t=n.get(e)??0;return typeof o=="string"&&e!==""&&!Number.isNaN(Number(e))?t+this._numberCount(s,Number(e)):t}_template(s,o,n,e){const t=this._ruleData(s),r=`t${o}`;if(t[r]===void 0){const i=e._base;t[r]=this.book.engine.template(n,i.r0,i.c0)}return t[r]}_formula(s,o,n,e,t){const{engine:r}=this.book,i=s.formulas?.[o];return i===void 0||!r?null:this._run(this._template(s,o,i,n),e,t)}_run(s,o,n){const{engine:e}=this.book,t=e.legacy;e.legacy=!0;try{let r=s.fn(o,n,this.sheet);return(r&&r.sheet||r&&r.refs)&&(r=e.refAuto(r,o,n)),r&&r.data&&([r]=r.data),r===void 0?null:r}catch(r){return r instanceof b?r:null}finally{e.legacy=t}}_dxf(s){return s.dxf?s.dxf:s.dxfId!==null&&s.dxfId!==void 0?this.book.dxfs?.[s.dxfId]??w:w}_threshold(s,o){const n=this._stat(o);switch(s.type){case"min":return n.min;case"max":return n.max;case"autoMin":return Math.min(n.min,0);case"autoMax":return Math.max(n.max,0);default:break}const e=s.val;let t;if(typeof e=="string"&&!/^\s*[-+]?[\d.]+(?:[eE][-+]?\d+)?\s*$/.test(e)){const{engine:r}=this.book;if(!r)return 0;const i=o._base,l=this._run(r.template(e,i.r0,i.c0),i.r0,i.c0);t=typeof l=="number"?l:0}else t=e==null?0:Number(e);switch(s.type){case"percent":return n.min+(n.max-n.min)*t/100;case"percentile":{if(n.n===0)return 0;const r=I(t/100)*(n.n-1),i=Math.floor(r);return i+1<n.n?n.nums[i]+(r-i)*(n.nums[i+1]-n.nums[i]):n.nums[i]}default:return t}}_ruleData(s){let o=this.data.get(s);return o===void 0&&(o={},this.data.set(s,o)),o}_evaluate(s,o,n,e){switch(s.type){case"cellIs":{const t=this._value(n,e);if(t instanceof b)return null;const r=this._formula(s,0,o,n,e);if(r instanceof b)return null;const i=s.operator;let l=!1;if(i==="between"||i==="notBetween"){const a=this._formula(s,1,o,n,e);if(a instanceof b)return null;const u=v(r,a)<=0,h=u?r:a,d=u?a:r,f=v(t,h)>=0&&v(t,d)<=0;l=i==="between"?f:!f}else{const a=v(t,r);l=i==="greaterThan"?a>0:i==="lessThan"?a<0:i==="greaterThanOrEqual"?a>=0:i==="lessThanOrEqual"?a<=0:i==="equal"?a===0:i==="notEqual"?a!==0:!1}return l?this._dxf(s):null}case"expression":{const t=this._formula(s,0,o,n,e);return typeof t=="boolean"?t?this._dxf(s):null:typeof t=="number"&&t!==0?this._dxf(s):null}case"containsText":case"notContainsText":case"beginsWith":case"endsWith":return this._textRule(s,o,n,e)?this._dxf(s):null;case"containsBlanks":{const t=this._value(n,e);return t===null||typeof t=="string"&&t.trim()===""?this._dxf(s):null}case"notContainsBlanks":{const t=this._value(n,e);return t!==null&&!(t instanceof b)&&!(typeof t=="string"&&t.trim()==="")?this._dxf(s):null}case"containsErrors":return this._value(n,e)instanceof b?this._dxf(s):null;case"notContainsErrors":return this._value(n,e)instanceof b?null:this._dxf(s);case"duplicateValues":case"uniqueValues":{const t=this._value(n,e);if(t===null)return null;const r=this._occurrences(o,t);return(s.type==="duplicateValues"?r>1:r===1)?this._dxf(s):null}case"top10":{const t=this._value(n,e);if(typeof t!="number")return null;const r=this._stat(o);let i=s.rank??10;return s.percent&&(i=Math.max(1,Math.floor(r.n*i/100))),i=Math.min(i,r.n),i<=0?null:(s.bottom?t<=r.nums[i-1]:t>=r.nums[r.n-i])?this._dxf(s):null}case"aboveAverage":{const t=this._value(n,e);if(typeof t!="number")return null;const r=this._stat(o),i=s.aboveAverage!==!1,l=r.mean+(i?1:-1)*(s.stdDev||0)*r.stdP;return(i?s.equalAverage?t>=l:t>l:s.equalAverage?t<=l:t<l)?this._dxf(s):null}case"timePeriod":{const t=this._value(n,e);return typeof t=="number"&&this._inPeriod(t,s.timePeriod)?this._dxf(s):null}case"colorScale":{const t=this._value(n,e);return typeof t=="number"?this._colorScale(s,o,t):null}case"dataBar":{const t=this._value(n,e);return typeof t=="number"?this._dataBar(s,o,t):null}case"iconSet":{const t=this._value(n,e);return typeof t=="number"?this._iconSet(s,o,t):null}default:return null}}_textRule(s,o,n,e){if(s.formulas&&s.formulas.length>0&&this.book.engine){const l=this._formula(s,0,o,n,e);return l===!0||typeof l=="number"&&l!==0}const t=this._value(n,e),r=String(s.text??"").toLowerCase();if(t instanceof b)return s.type==="notContainsText";const i=t===null?"":typeof t=="boolean"?t?"true":"false":String(t).toLowerCase();switch(s.type){case"containsText":return i.includes(r);case"notContainsText":return!i.includes(r);case"beginsWith":return i.startsWith(r);default:return i.endsWith(r)}}_colorScale(s,o,n){const e=this._ruleData(s);if(e.stops===void 0){const{cfvo:i,colors:l}=s.colorScale;e.stops=i.map(a=>this._threshold(a,o)),e.css=l.map(a=>this.colorOf({a})??"#FFFFFF"),e.rgb=e.css.map($),e.ends=e.css.map(a=>({fill:a}))}const{stops:t}=e,r=t.length-1;if(n>=t[r])return e.ends[r];if(n<=t[0])return e.ends[0];for(let i=1;i<=r;i++)if(n<t[i]){const l=t[i]-t[i-1],a=l===0?1:(n-t[i-1])/l,u=e.rgb[i-1],h=e.rgb[i];return{fill:`#${F(Math.round(u[0]+(h[0]-u[0])*a))}${F(Math.round(u[1]+(h[1]-u[1])*a))}${F(Math.round(u[2]+(h[2]-u[2])*a))}`}}return e.ends[r]}_barStyle(s,o){const n=this._ruleData(s);if(n.bar!==void 0)return n.bar;const e=s.dataBar,t=e.ext,r=t?.cfvo??e.cfvo;let i=this._threshold(r[0],o),l=this._threshold(r[1],o);l<i&&([i,l]=[l,i]);const a=this.colorOf({a:e.color})??"#638EC6",u=(_,x)=>_?this.colorOf({a:_})??x:x,h=(t?t.minLength:e.minLength??10)/100,d=(t?t.maxLength:e.maxLength??90)/100,f=t?t.axisPosition??"automatic":"none";let m=-1;f==="middle"?m=.5:f==="automatic"&&(i<0&&l>0?m=-i/(l-i):l<=0&&i<0&&(m=1));const p=t?.border?u(t.borderColor,a):null;return n.bar={lo:i,hi:l,minL:h,maxL:d,start:t?h/2:h,axisAt:m,color:a,gradient:t?t.gradient!==!1:!0,border:p,negColor:t&&!t.negFillSame?u(t.negFill,"#FF0000"):a,negBorder:t?.border&&t.negBorderSame===!1?u(t.negBorder,"#FF0000"):p,axisColor:t?u(t.axisColor,"#000000"):"#000000",direction:t?.direction??"context",hide:e.showValue===!1},n.bar}_dataBar(s,o,n){const e=this._barStyle(s,o),{lo:t,hi:r,minL:i,maxL:l,axisAt:a,start:u}=e,h=l-i;let d,f;if(a<0)d=0,f=u+h*(r===t?1:I((n-t)/(r-t)));else{const _=s.dataBar.ext?.axisPosition==="middle"?Math.max(Math.abs(t),Math.abs(r)):n>=0?r:-t,y=(n>=0?1-a:a)*(u+h*(_>0?I(Math.abs(n)/_):0));n>=0?(d=a,f=a+y):(f=a,d=a-y)}return{bar:{style:e,x0:d,x1:f,negative:n<0,pct:f-d,color:n<0?e.negColor:e.color},hideValue:e.hide}}_iconSet(s,o,n){const e=this._ruleData(s),t=s.iconSet;if(e.levels===void 0){e.thresholds=t.cfvo.map(u=>this._threshold(u,o));const a=t.cfvo.length;e.levels=t.cfvo.map((u,h)=>{const d=t.reverse?a-1-h:h,f=t.custom?.[h],m=f?f.iconSet:t.name,p=f?f.iconId:d,_=t.showValue===!1;return m==="NoIcons"?{hideValue:_}:{icon:{name:m,level:p,count:a},hideValue:_}})}const{thresholds:r,levels:i}=e;let l=0;for(let a=r.length-1;a>=1;a--){const u=r[a];if(t.cfvo[a].gte===!1?n>u:n>=u){l=a;break}}return i[l]}_inPeriod(s,o){if(this.today===0){const a=new Date;this.today=V(a.getFullYear(),a.getMonth()+1,a.getDate())}const{today:n}=this,e=Math.floor(s);if(e<0)return!1;switch(o){case"today":return e===n;case"yesterday":return e===n-1;case"tomorrow":return e===n+1;case"last7Days":return e<=n&&e>n-7;default:break}const t=a=>a-k(a).weekday;switch(o){case"thisWeek":return t(e)===t(n);case"lastWeek":return t(e)===t(n)-7;case"nextWeek":return t(e)===t(n)+7;default:break}const r=k(e),i=k(n),l=(r.year-i.year)*12+r.month-i.month;switch(o){case"thisMonth":return l===0;case"lastMonth":return l===-1;case"nextMonth":return l===1;default:return!1}}}function j(c,s){if(!c.cfEval){if(!s)return null;c.cfEval=new H(s,c)}return c.cfEval}function z(c,s,o,n){if(!c.cf||c.cf.length===0)return null;const e=j(c,n),t=e?e.at(s,o):null;return t===null?null:{fill:t.fill??null,noFill:t.noFill===!0,color:t.color??null,iconSet:t.icon?.name??null,iconId:t.icon?.level??null}}function tt(c,s,o,n){const e=z(c,s,o,n);return e&&e.iconSet!==null?{iconSet:e.iconSet,iconId:e.iconId}:null}export{H as CondFormats,z as cfEffectAt,j as evaluatorOf,tt as iconAt};
|
|
1
|
+
import{parseRangeRef as E}from"../core/address.js";import{CHUNK_BITS as S,CHUNK_MASK as N,DIRTY as D,KIND_MASK as A,NUM as B}from"../core/sheet.js";import{partsToSerial as P,serialToParts as F}from"../core/numfmt.js";import{compareValues as v,XlError as b}from"../calc/values.js";import{wildcardRegex as V}from"../calc/functions/helpers.js";import{hasConditionalFormats as q,hostFormats as W}from"../core/host-rules.js";import{resolveColor as H}from"../io/xlsx-styles.js";const K=c=>c.split(/\s+/).map(E).filter(Boolean),$=1<<19,O=Object.freeze({}),R=new Set(["colorScale","dataBar","iconSet"]),U=c=>[parseInt(c.slice(1,3),16),parseInt(c.slice(3,5),16),parseInt(c.slice(5,7),16)],k=c=>(c<16?"0":"")+c.toString(16),I=c=>c<0?0:c>1?1:c;function j(c,s){const o={...s,...c};return(c.fill!==void 0||c.pattern!==void 0||c.gradient!==void 0||c.noFill)&&(c.pattern===void 0&&delete o.pattern,c.gradient===void 0&&delete o.gradient,c.fill===void 0&&delete o.fill,c.noFill||delete o.noFill),c.borders&&s.borders&&(o.borders={l:c.borders.l??s.borders.l,r:c.borders.r??s.borders.r,t:c.borders.t??s.borders.t,b:c.borders.b??s.borders.b}),o}const w=c=>c instanceof b?String(c.code??c.message??c).toLowerCase():typeof c=="boolean"?c?"true":"false":String(c).toLowerCase();class z{constructor(s,o,n){this.book=s,this.sheet=o,this.colorOf=n??(e=>H(e,s.theme??[])),this.cache=new Map,this.stats=new Map,this.data=new Map,this.flat=null,this.flatOf=null,this.flatHost=null,this.today=0}invalidate(){this.cache.clear(),this.stats.clear(),this.data.clear(),this.flat=null,this.today=0}_rules(){const{cf:s,hostRules:o}=this.sheet;if(this.flat!==null&&this.flatOf===s&&this.flatHost===o)return this.flat;const n=(t,r)=>t.rule.priority-r.rule.priority,e=[...this._entries(s??[]).sort(n),...this._entries(W(this.sheet))];return this.flat=e,this.flatOf=s,this.flatHost=o,this.stoppers=e.filter(t=>t.rule.stopIfTrue&&!R.has(t.rule.type)),e}_entries(s){const o=[];for(const n of s){n._ranges===void 0&&(n._ranges=K(n.sqref));const e=n._ranges;if(e.length===0)continue;let t=1/0,r=1/0,i=-1,l=-1;for(const a of e)a.r0<t&&(t=a.r0),a.c0<r&&(r=a.c0),a.r1>i&&(i=a.r1),a.c1>l&&(l=a.c1);n._base={r0:t,c0:r};for(const a of n.rules)o.push({rule:a,block:n,r0:t,c0:r,r1:i,c1:l,single:e.length===1})}return o}stoppedBefore(s,o,n){this._rules();for(const e of this.stoppers){if(e.rule.priority>=s)break;if(!(o<e.r0||o>e.r1||n<e.c0||n>e.c1)&&!(!e.single&&!e.block._ranges.some(t=>o>=t.r0&&o<=t.r1&&n>=t.c0&&n<=t.c1))&&this._evaluate(e.rule,e.block,o,n)!==null)return!0}return!1}at(s,o){this.valueRevision!==this.book.formatValueRevision&&(this.invalidate(),this.valueRevision=this.book.formatValueRevision);const n=s*16384+o,e=this.cache.get(n);if(e!==void 0)return e;const t=this._rules();let r=null;for(let i=0;i<t.length;i++){const l=t[i];if(s<l.r0||s>l.r1||o<l.c0||o>l.c1)continue;if(!l.single){const h=l.block._ranges;let d=!1;for(let f=0;f<h.length&&!d;f++){const m=h[f];d=s>=m.r0&&s<=m.r1&&o>=m.c0&&o<=m.c1}if(!d)continue}const a=this._evaluate(l.rule,l.block,s,o);if(a===null)continue;const u=l.block.managedBy?{...a,fieldWarning:a}:a;if(r=r===null?u:j(r,u),l.rule.stopIfTrue&&!R.has(l.rule.type))break}return this.cache.size>=$&&this.cache.clear(),this.cache.set(n,r),r}_value(s,o){return this.book.engine?this.book.engine.read(this.sheet,s,o):null}_stat(s){let o=this.stats.get(s);if(o!==void 0)return o;const{sheet:n}=this,{engine:e}=this.book;let t=new Float64Array(1024),r=0;for(const u of s._ranges){const h=Math.min(u.c1,n.maxCol),d=Math.min(u.r1,n.maxRow);for(let f=u.c0;f<=h;f++){const m=n.columns[f];if(m!==void 0)for(let p=u.r0>>>S;p<=d>>>S;p++){const _=m[p];if(_===void 0)continue;const x=p<<S,y=Math.max(u.r0-x,0),M=Math.min(d-x,N),{kinds:L,values:T}=_;if(r+(M-y+1)>t.length){const g=new Float64Array(Math.max(t.length*2,r+M-y+1));g.set(t),t=g}for(let g=y;g<=M;g++){const C=L[g];C!==0&&(C&D?(e&&e.read(n,x+g,f),(L[g]&A)===B&&(t[r++]=T[g])):(C&A)===B&&(t[r++]=T[g]))}}}}t=t.subarray(0,r).sort();let i=0;for(let u=0;u<r;u++)i+=t[u];const l=r?i/r:0;let a=0;for(let u=0;u<r;u++)a+=(t[u]-l)**2;return o={nums:t,n:r,mean:l,stdP:r>0?Math.sqrt(a/r):0,min:r?t[0]:0,max:r?t[r-1]:0,others:null,texts:null,wild:null},this.stats.set(s,o),o}_others(s){const o=this._stat(s);if(o.others!==null)return o.others;const n=new Map;for(const e of s._ranges)this.book.engine?.scan({sheet:this.sheet,r0:e.r0,c0:e.c0,r1:e.r1,c1:e.c1},t=>{if(typeof t=="number")return;const r=w(t);n.set(r,(n.get(r)??0)+1)});return o.others=n,n}_numberCount(s,o){const{nums:n,n:e}=this._stat(s);let t=0,r=e;for(;t<r;){const i=t+r>>>1;n[i]<o?t=i+1:r=i}return t>=e||n[t]!==o?0:t+1<e&&n[t+1]===o?2:1}_wildcardCount(s,o){const n=this._stat(s);if(n.texts===null){n.texts=new Map;for(const r of s._ranges)this.book.engine?.scan({sheet:this.sheet,r0:r.r0,c0:r.c0,r1:r.r1,c1:r.c1},i=>{typeof i=="string"&&n.texts.set(i.toLowerCase(),(n.texts.get(i.toLowerCase())??0)+1)})}n.wild??=new Map;const e=o.toLowerCase();let t=n.wild.get(e);if(t===void 0){const r=V(o);t=0;for(const[i,l]of n.texts)r.test(i)&&(t+=l);n.wild.set(e,t)}return t}_occurrences(s,o){if(typeof o=="string"&&/[*?]/.test(o))return this._wildcardCount(s,o);const n=this._others(s);if(typeof o=="number")return this._numberCount(s,o)+(n.get(String(o))??0);const e=w(o),t=n.get(e)??0;return typeof o=="string"&&e!==""&&!Number.isNaN(Number(e))?t+this._numberCount(s,Number(e)):t}_template(s,o,n,e){const t=this._ruleData(s),r=`t${o}`;if(t[r]===void 0){const i=e._base;t[r]=this.book.engine.template(n,i.r0,i.c0)}return t[r]}_formula(s,o,n,e,t){const{engine:r}=this.book,i=s.formulas?.[o];return i===void 0||!r?null:this._run(this._template(s,o,i,n),e,t)}_run(s,o,n){const{engine:e}=this.book,t=e.legacy;e.legacy=!1;try{let r=s.fn(o,n,this.sheet);return(r&&r.sheet||r&&r.refs)&&(r=e.refAuto(r,o,n)),r&&r.data&&([r]=r.data),r===void 0?null:r}catch(r){return r instanceof b?r:null}finally{e.legacy=t}}_dxf(s){return s.dxf?s.dxf:s.dxfId!==null&&s.dxfId!==void 0?this.book.dxfs?.[s.dxfId]??O:O}_threshold(s,o){const n=this._stat(o);switch(s.type){case"min":return n.min;case"max":return n.max;case"autoMin":return Math.min(n.min,0);case"autoMax":return Math.max(n.max,0);default:break}const e=s.val;let t;if(typeof e=="string"&&!/^\s*[-+]?[\d.]+(?:[eE][-+]?\d+)?\s*$/.test(e)){const{engine:r}=this.book;if(!r)return 0;const i=o._base,l=this._run(r.template(e,i.r0,i.c0),i.r0,i.c0);t=typeof l=="number"?l:0}else t=e==null?0:Number(e);switch(s.type){case"percent":return n.min+(n.max-n.min)*t/100;case"percentile":{if(n.n===0)return 0;const r=I(t/100)*(n.n-1),i=Math.floor(r);return i+1<n.n?n.nums[i]+(r-i)*(n.nums[i+1]-n.nums[i]):n.nums[i]}default:return t}}_ruleData(s){let o=this.data.get(s);return o===void 0&&(o={},this.data.set(s,o)),o}_evaluate(s,o,n,e){switch(s.type){case"cellIs":{const t=this._value(n,e);if(t instanceof b)return null;const r=this._formula(s,0,o,n,e);if(r instanceof b)return null;const i=s.operator;let l=!1;if(i==="between"||i==="notBetween"){const a=this._formula(s,1,o,n,e);if(a instanceof b)return null;const u=v(r,a)<=0,h=u?r:a,d=u?a:r,f=v(t,h)>=0&&v(t,d)<=0;l=i==="between"?f:!f}else{const a=v(t,r);l=i==="greaterThan"?a>0:i==="lessThan"?a<0:i==="greaterThanOrEqual"?a>=0:i==="lessThanOrEqual"?a<=0:i==="equal"?a===0:i==="notEqual"?a!==0:!1}return l?this._dxf(s):null}case"expression":{const t=this._formula(s,0,o,n,e);return typeof t=="boolean"?t?this._dxf(s):null:typeof t=="number"&&t!==0?this._dxf(s):null}case"containsText":case"notContainsText":case"beginsWith":case"endsWith":return this._textRule(s,o,n,e)?this._dxf(s):null;case"containsBlanks":{const t=this._value(n,e);return t===null||typeof t=="string"&&t.trim()===""?this._dxf(s):null}case"notContainsBlanks":{const t=this._value(n,e);return t!==null&&!(t instanceof b)&&!(typeof t=="string"&&t.trim()==="")?this._dxf(s):null}case"containsErrors":return this._value(n,e)instanceof b?this._dxf(s):null;case"notContainsErrors":return this._value(n,e)instanceof b?null:this._dxf(s);case"duplicateValues":case"uniqueValues":{const t=this._value(n,e);if(t===null)return null;const r=this._occurrences(o,t);return(s.type==="duplicateValues"?r>1:r===1)?this._dxf(s):null}case"top10":{const t=this._value(n,e);if(typeof t!="number")return null;const r=this._stat(o);let i=s.rank??10;return s.percent&&(i=Math.max(1,Math.floor(r.n*i/100))),i=Math.min(i,r.n),i<=0?null:(s.bottom?t<=r.nums[i-1]:t>=r.nums[r.n-i])?this._dxf(s):null}case"aboveAverage":{const t=this._value(n,e);if(typeof t!="number")return null;const r=this._stat(o),i=s.aboveAverage!==!1,l=r.mean+(i?1:-1)*(s.stdDev||0)*r.stdP,a=v(t,l);return s.equalAverage&&a===0||(i?a>0:a<0)?this._dxf(s):null}case"timePeriod":{const t=this._value(n,e);return typeof t=="number"&&this._inPeriod(t,s.timePeriod)?this._dxf(s):null}case"colorScale":{const t=this._value(n,e);return typeof t=="number"?this._colorScale(s,o,t):null}case"dataBar":{const t=this._value(n,e);return typeof t=="number"?this._dataBar(s,o,t):null}case"iconSet":{const t=this._value(n,e);return typeof t=="number"?this._iconSet(s,o,t):null}default:return null}}_textRule(s,o,n,e){if(s.formulas&&s.formulas.length>0&&this.book.engine){const l=this._formula(s,0,o,n,e);return l===!0||typeof l=="number"&&l!==0}const t=this._value(n,e),r=String(s.text??"").toLowerCase();if(t instanceof b)return s.type==="notContainsText";const i=t===null?"":typeof t=="boolean"?t?"true":"false":String(t).toLowerCase();switch(s.type){case"containsText":return i.includes(r);case"notContainsText":return!i.includes(r);case"beginsWith":return i.startsWith(r);default:return i.endsWith(r)}}_colorScale(s,o,n){const e=this._ruleData(s);if(e.stops===void 0){const{cfvo:i,colors:l}=s.colorScale;e.stops=i.map(a=>this._threshold(a,o)),e.css=l.map(a=>this.colorOf({a})??"#FFFFFF"),e.rgb=e.css.map(U),e.ends=e.css.map(a=>({fill:a}))}const{stops:t}=e,r=t.length-1;if(n>=t[r])return e.ends[r];if(n<=t[0])return e.ends[0];for(let i=1;i<=r;i++)if(n<t[i]){const l=t[i]-t[i-1],a=l===0?1:(n-t[i-1])/l,u=e.rgb[i-1],h=e.rgb[i];return{fill:`#${k(Math.round(u[0]+(h[0]-u[0])*a))}${k(Math.round(u[1]+(h[1]-u[1])*a))}${k(Math.round(u[2]+(h[2]-u[2])*a))}`}}return e.ends[r]}_barStyle(s,o){const n=this._ruleData(s);if(n.bar!==void 0)return n.bar;const e=s.dataBar,t=e.ext,r=t?.cfvo??e.cfvo;let i=this._threshold(r[0],o),l=this._threshold(r[1],o);l<i&&([i,l]=[l,i]);const a=this.colorOf({a:e.color})??"#638EC6",u=(_,x)=>_?this.colorOf({a:_})??x:x,h=(t?t.minLength:e.minLength??10)/100,d=(t?t.maxLength:e.maxLength??90)/100,f=t?t.axisPosition??"automatic":"none";let m=-1;f==="middle"?m=.5:f==="automatic"&&(i<0&&l>0?m=-i/(l-i):l<=0&&i<0&&(m=1));const p=t?.border?u(t.borderColor,a):null;return n.bar={lo:i,hi:l,minL:h,maxL:d,start:t?h/2:h,axisAt:m,color:a,gradient:t?t.gradient!==!1:!0,border:p,negColor:t&&!t.negFillSame?u(t.negFill,"#FF0000"):a,negBorder:t?.border&&t.negBorderSame===!1?u(t.negBorder,"#FF0000"):p,axisColor:t?u(t.axisColor,"#000000"):"#000000",direction:t?.direction??"context",hide:e.showValue===!1},n.bar}_dataBar(s,o,n){const e=this._barStyle(s,o),{lo:t,hi:r,minL:i,maxL:l,axisAt:a,start:u}=e,h=l-i;let d,f;if(a<0)d=0,f=u+h*(r===t?1:I((n-t)/(r-t)));else{const _=s.dataBar.ext?.axisPosition==="middle"?Math.max(Math.abs(t),Math.abs(r)):n>=0?r:-t,y=(n>=0?1-a:a)*(u+h*(_>0?I(Math.abs(n)/_):0));n>=0?(d=a,f=a+y):(f=a,d=a-y)}return{bar:{style:e,x0:d,x1:f,negative:n<0,pct:f-d,color:n<0?e.negColor:e.color},hideValue:e.hide}}_iconSet(s,o,n){const e=this._ruleData(s),t=s.iconSet;if(e.levels===void 0){e.thresholds=t.cfvo.map(u=>this._threshold(u,o));const a=t.cfvo.length;e.levels=t.cfvo.map((u,h)=>{const d=t.reverse?a-1-h:h,f=t.custom?.[h],m=f?f.iconSet:t.name,p=f?f.iconId:d,_=t.showValue===!1;return m==="NoIcons"?{hideValue:_}:{icon:{name:m,level:p,count:a},hideValue:_}})}const{thresholds:r,levels:i}=e;let l=0;for(let a=r.length-1;a>=1;a--){const u=r[a];if(t.cfvo[a].gte===!1?n>u:n>=u){l=a;break}}return i[l]}_inPeriod(s,o){if(this.today===0){const a=new Date;this.today=P(a.getFullYear(),a.getMonth()+1,a.getDate())}const{today:n}=this;if(s<0)return!1;const e=Math.floor(s)+(this.book.dateOffset??0);switch(o){case"today":return e===n;case"yesterday":return e===n-1;case"tomorrow":return e===n+1;case"last7Days":return e<=n&&e>n-7;default:break}const t=a=>a-F(a).weekday;switch(o){case"thisWeek":return t(e)===t(n);case"lastWeek":return t(e)===t(n)-7;case"nextWeek":return t(e)===t(n)+7;default:break}const r=F(e),i=F(n),l=(r.year-i.year)*12+r.month-i.month;switch(o){case"thisMonth":return l===0;case"lastMonth":return l===-1;case"nextMonth":return l===1;default:return!1}}}function Y(c,s){if(!c.cfEval){if(!s)return null;c.cfEval=new z(s,c)}return c.cfEval}function X(c,s,o,n){if(!q(c))return null;const e=Y(c,n),t=e?e.at(s,o):null;return t===null?null:{fill:t.fill??null,noFill:t.noFill===!0,color:t.color??null,iconSet:t.icon?.name??null,iconId:t.icon?.level??null}}function st(c,s,o,n){const e=X(c,s,o,n);return e&&e.iconSet!==null?{iconSet:e.iconSet,iconId:e.iconId}:null}export{z as CondFormats,X as cfEffectAt,Y as evaluatorOf,st as iconAt};
|
package/cells/cf-file.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{child as a,children as p,parseTree as N,unescapeOoxml as P}from"../io/xml-scan.js";import{escapeMarkup as $,xmlAttr as E}from"../io/xml-escape.js";const V=new TextEncoder,u=t=>t==="1"||t==="true",L="http://schemas.microsoft.com/office/spreadsheetml/2009/9/main",T="http://schemas.microsoft.com/office/excel/2006/main",R="{B025F937-C7B1-47D3-B67F-A62EFF666E3E}",M="{78C0D931-6437-407d-A8EE-F0AAD7539E65}",D=new Set(["3Stars","3Triangles","5Boxes"]),j=()=>{const t=()=>Math.floor(Math.random()*65536).toString(16).padStart(4,"0");return`{${t()}${t()}-${t()}-4${t().slice(1)}-a${t().slice(1)}-${t()}${t()}${t()}}`.toUpperCase()};function ot(t,e){const o=a(e,"dataBar");o&&t.dataBar&&(o.a.minLength!==void 0&&(t.dataBar.minLength=Number(o.a.minLength)),o.a.maxLength!==void 0&&(t.dataBar.maxLength=Number(o.a.maxLength)));for(const n of p(a(e,"extLst"),"ext")){const i=a(n,"id");i&&(t.id=i.t.trim())}return t}const F=t=>t.map(e=>{const o=a(e,"f"),n={type:e.a.type,val:o?o.t:e.a.val??null};return e.a.gte!==void 0&&!u(e.a.gte)&&(n.gte=!1),n}),w=t=>{const e=t.type==="autoMin"?"min":t.type==="autoMax"?"max":t.type;return e==="min"||e==="max"?{type:e}:{type:e,val:t.val}};function q(t){const e=t.a,o=n=>a(t,n)?.a??null;return{cfvo:F(p(t,"cfvo")),minLength:e.minLength!==void 0?Number(e.minLength):10,maxLength:e.maxLength!==void 0?Number(e.maxLength):90,gradient:e.gradient===void 0?!0:u(e.gradient),border:u(e.border),borderColor:o("borderColor"),negFill:o("negativeFillColor"),negBorder:o("negativeBorderColor"),negFillSame:u(e.negativeBarColorSameAsPositive),negBorderSame:e.negativeBarBorderColorSameAsPositive===void 0?!0:u(e.negativeBarBorderColorSameAsPositive),axisPosition:e.axisPosition??"automatic",axisColor:o("axisColor"),direction:e.direction??"context"}}function X(t,e){const o=t.a,n={type:o.type,priority:Number(o.priority??0),dxfId:null,operator:o.operator??null,formulas:p(t,"f").map(f=>f.t),text:P(o.text??null),rank:o.rank!==void 0?Number(o.rank):null,percent:u(o.percent),bottom:u(o.bottom),aboveAverage:o.aboveAverage===void 0?!0:u(o.aboveAverage),equalAverage:u(o.equalAverage),stdDev:o.stdDev!==void 0?Number(o.stdDev):0,stopIfTrue:u(o.stopIfTrue),timePeriod:o.timePeriod??null,x14:!0};o.id&&(n.id=o.id);const i=a(t,"dxf");i&&(n.dxf=I(i,e));const r=a(t,"colorScale");r&&(n.colorScale={cfvo:F(p(r,"cfvo")),colors:p(r,"color").map(f=>f.a)});const l=a(t,"dataBar");if(l){const f=q(l);n.dataBar={cfvo:f.cfvo.map(w),color:a(l,"fillColor")?.a??{rgb:"FF638EC6"},showValue:l.a.showValue===void 0?!0:u(l.a.showValue),ext:f}}const s=a(t,"iconSet");return s&&(n.iconSet={name:s.a.iconSet??"3TrafficLights1",cfvo:F(p(s,"cfvo")),reverse:u(s.a.reverse),showValue:s.a.showValue===void 0?!0:u(s.a.showValue),x14:!0},u(s.a.custom)&&(n.iconSet.custom=p(s,"cfIcon").map(f=>({iconSet:f.a.iconSet,iconId:Number(f.a.iconId??0)})))),n}function A(t){return/<ext\b[^>]*>\s*<(\w+:)?conditionalFormattings\b[\s\S]*?<\/(\w+:)?conditionalFormattings>\s*<\/ext>/.exec(t)}function nt(t,e,o){if(!e.includes("conditionalFormattings"))return;const n=A(e);if(n===null)return;let i;try{i=N(V.encode(`<r xmlns:x14="x" xmlns:xm="m" xmlns:xr="x">${n[0]}</r>`))}catch{return}const r=new Map;for(const s of t.cf)for(const f of s.rules)f.id&&r.set(f.id.toUpperCase(),f);const l=a(a(i,"ext"),"conditionalFormattings");for(const s of p(l,"conditionalFormatting")){const f=a(s,"sqref")?.t.trim()??"",c=[];for(const d of p(s,"cfRule")){const m=X(d,o),x=m.id?r.get(m.id.toUpperCase()):void 0;x!==void 0&&x.dataBar&&m.dataBar?(x.dataBar.ext=m.dataBar.ext,x.dataBar.showValue=x.dataBar.showValue&&m.dataBar.showValue):x===void 0&&c.push(m)}c.length>0&&f!==""&&t.cf.push({sqref:f,rules:c})}}function I(t,e){const o={},n=a(t,"font");if(n){const c=x=>{const g=a(n,x);return g!==void 0&&g.a.val!=="0"&&g.a.val!=="false"};a(n,"b")&&(o.bold=c("b")),a(n,"i")&&(o.italic=c("i")),a(n,"strike")&&(o.strike=c("strike"));const d=a(n,"u");d&&(o.underline=d.a.val==="none"?0:d.a.val==="double"||d.a.val==="doubleAccounting"?2:1);const m=e(a(n,"color"));m&&(o.color=m)}const i=a(t,"numFmt");i?.a.formatCode!==void 0&&(o.numFmt=i.a.formatCode);const r=a(t,"fill"),l=a(r,"patternFill");if(l){const c=l.a.patternType,d=a(l,"fgColor");o.pf={none:c==="none",auto:d?.a.auto==="1",fg:d&&d.a.auto!=="1"?e(d):null};const m=e(a(l,"bgColor")),x=e(a(l,"fgColor"));if(c===void 0||c==="solid"){const g=m??x;g&&(o.fill=g)}else c==="none"?o.noFill=!0:(o.pattern={type:c,fg:x??"#000000"},o.fill=m??"#FFFFFF")}const s=a(r,"gradientFill");if(s){const c=p(s,"stop").map(d=>({pos:Number(d.a.position??0),color:e(a(d,"color"))??"#FFFFFF"}));c.length>1&&(o.gradient={type:s.a.type==="path"?"path":"linear",degree:Number(s.a.degree??0),left:Number(s.a.left??0),right:Number(s.a.right??0),top:Number(s.a.top??0),bottom:Number(s.a.bottom??0),stops:c},o.fill=c[0].color)}const f=a(t,"border");if(f){const c=g=>{const b=a(f,g);return b&&b.a.style?{style:b.a.style,color:e(a(b,"color"))??"#000000"}:null},d={l:c("left"),r:c("right"),t:c("top"),b:c("bottom")},m=c("vertical"),x=c("horizontal");m&&(d.v=m),x&&(d.h=x),(d.l||d.r||d.t||d.b||m||x)&&(o.borders=d)}return o}const it=(t,e)=>p(a(t,"dxfs"),"dxf").map(o=>I(o,e)),v=t=>`FF${t.slice(1).toUpperCase()}`,U={General:0,0:1,"0.00":2,"#,##0":3,"#,##0.00":4,"0%":9,"0.00%":10,"0.00E+00":11,"# ?/?":12,"# ??/??":13,"mm-dd-yy":14,"d-mmm-yy":15,"d-mmm":16,"mmm-yy":17,"h:mm AM/PM":18,"h:mm:ss AM/PM":19,"h:mm":20,"h:mm:ss":21,"m/d/yy h:mm":22,"@":49};function _(t){const e=U[t];if(e!==void 0)return e;let o=0;for(let n=0;n<t.length;n++)o=(o*31+t.charCodeAt(n))%6e4;return 1e3+o}function z(t,e="dxf"){let o="";t.bold!==void 0&&(o+=t.bold?"<b/>":'<b val="0"/>'),t.italic!==void 0&&(o+=t.italic?"<i/>":'<i val="0"/>'),t.strike!==void 0&&(o+=t.strike?"<strike/>":'<strike val="0"/>'),t.underline?o+=t.underline===2?'<u val="double"/>':"<u/>":t.underline===0&&(o+='<u val="none"/>'),t.color&&(o+=`<color rgb="${v(t.color)}"/>`);const n=t.numFmt?`<numFmt numFmtId="${_(t.numFmt)}" formatCode="${$(t.numFmt)}"/>`:"";let i="";t.noFill?i='<fill><patternFill patternType="none"/></fill>':t.pattern?i=`<fill><patternFill patternType="${t.pattern.type}"><fgColor rgb="${v(t.pattern.fg??"#000000")}"/>${t.fill?`<bgColor rgb="${v(t.fill)}"/>`:""}</patternFill></fill>`:t.fill&&(i=`<fill><patternFill><bgColor rgb="${v(t.fill)}"/></patternFill></fill>`);let r="";if(t.borders){const l=(f,c)=>c?`<${f} style="${c.style}"><color rgb="${v(c.color??"#000000")}"/></${f}>`:"",s=l("left",t.borders.l)+l("right",t.borders.r)+l("top",t.borders.t)+l("bottom",t.borders.b)+l("vertical",t.borders.v)+l("horizontal",t.borders.h);s&&(r=`<border>${s}</border>`)}return`<${e}>${o?`<font>${o}</font>`:""}${n}${i}${r}</${e}>`}const B=t=>t.map(e=>`<cfvo type="${e.type}"${e.val!==null&&e.val!==void 0?` val="${$(e.val)}"`:""}${e.gte===!1?' gte="0"':""}/>`).join(""),h=t=>Object.entries(t).map(([e,o])=>`${e}="${$(o)}"`).join(" "),S=(t,e)=>e?`<x14:${t} ${h(e)}/>`:"";function y(t){return t.map(e=>{const o=e.gte===!1?' gte="0"':"";return e.val===null||e.val===void 0?`<x14:cfvo type="${e.type}"${o}/>`:`<x14:cfvo type="${e.type}"${o}><xm:f>${$(e.val)}</xm:f></x14:cfvo>`}).join("")}function C(t){return t.x14&&!t.dataBar?!0:!!t.iconSet&&(t.iconSet.x14||t.iconSet.custom!==void 0||D.has(t.iconSet.name))}function k(t){let e=`type="${t.type}" priority="${t.priority}"`;return t.stopIfTrue&&(e+=' stopIfTrue="1"'),t.operator&&(e+=` operator="${t.operator}"`),t.text!==null&&t.text!==void 0&&(e+=` text="${E(t.text)}"`),t.rank!==null&&t.rank!==void 0&&(e+=` rank="${t.rank}"`),t.percent&&(e+=' percent="1"'),t.bottom&&(e+=' bottom="1"'),t.type==="aboveAverage"&&(t.aboveAverage===!1&&(e+=' aboveAverage="0"'),t.equalAverage&&(e+=' equalAverage="1"'),t.stdDev&&(e+=` stdDev="${t.stdDev}"`)),t.timePeriod&&(e+=` timePeriod="${t.timePeriod}"`),e}function G(t){let e=k(t);t.dxfId!==null&&t.dxfId!==void 0&&(e=e.replace(/( priority="\d+")/,` dxfId="${t.dxfId}"$1`));let o=(t.formulas??[]).map(n=>`<formula>${$(n)}</formula>`).join("");if(t.colorScale&&(o+=`<colorScale>${B(t.colorScale.cfvo)}${t.colorScale.colors.map(n=>`<color ${h(n)}/>`).join("")}</colorScale>`),t.dataBar){const n=t.dataBar,i=n.ext,r=i?i.minLength===0&&i.maxLength===100?[10,90]:[i.minLength,i.maxLength]:[n.minLength??10,n.maxLength??90],l=`${r[0]!==10?` minLength="${r[0]}"`:""}${r[1]!==90?` maxLength="${r[1]}"`:""}${n.showValue===!1?' showValue="0"':""}`;o+=`<dataBar${l}>${B(i?i.cfvo.map(w):n.cfvo)}<color ${h(n.color)}/></dataBar>`,n.ext&&(o+=`<extLst><ext xmlns:x14="${L}" uri="${R}"><x14:id>${t.id}</x14:id></ext></extLst>`)}return t.iconSet&&(o+=`<iconSet iconSet="${t.iconSet.name}"${t.iconSet.reverse?' reverse="1"':""}${t.iconSet.showValue===!1?' showValue="0"':""}>${B(t.iconSet.cfvo)}</iconSet>`),`<cfRule ${e}>${o}</cfRule>`}function O(t){const e=t.ext;let o=` minLength="${e.minLength}" maxLength="${e.maxLength}"`;t.showValue===!1&&(o+=' showValue="0"'),e.gradient===!1&&(o+=' gradient="0"'),e.border&&(o+=' border="1"'),e.direction&&e.direction!=="context"&&(o+=` direction="${e.direction}"`),e.negFillSame&&(o+=' negativeBarColorSameAsPositive="1"'),e.negBorderSame===!1&&(o+=' negativeBarBorderColorSameAsPositive="0"'),e.axisPosition&&e.axisPosition!=="automatic"&&(o+=` axisPosition="${e.axisPosition}"`);const n=(e.border?S("borderColor",e.borderColor):"")+(e.negFillSame?"":S("negativeFillColor",e.negFill))+(e.border&&e.negBorderSame===!1?S("negativeBorderColor",e.negBorder):"")+(e.axisPosition==="none"?"":S("axisColor",e.axisColor));return`<x14:dataBar${o}>${y(e.cfvo)}${n}</x14:dataBar>`}function H(t){if(t.dataBar)return`<x14:cfRule type="dataBar" id="${t.id}">${O(t.dataBar)}</x14:cfRule>`;let e=(t.formulas??[]).map(o=>`<xm:f>${$(o)}</xm:f>`).join("");if(t.colorScale&&(e+=`<x14:colorScale>${y(t.colorScale.cfvo)}${t.colorScale.colors.map(o=>`<x14:color ${h(o)}/>`).join("")}</x14:colorScale>`),t.iconSet){const o=t.iconSet,n=o.custom!==void 0;e+=`<x14:iconSet iconSet="${o.name}"${o.showValue===!1?' showValue="0"':""}${o.reverse?' reverse="1"':""}${n?' custom="1"':""}>${y(o.cfvo)}${n?o.custom.map(i=>`<x14:cfIcon iconSet="${i.iconSet}" iconId="${i.iconId}"/>`).join(""):""}</x14:iconSet>`}return t.dxf&&(e+=z(t.dxf,"x14:dxf")),`<x14:cfRule ${k(t)} id="${t.id}">${e}</x14:cfRule>`}function J(t){let e="";for(const o of t){const n=o.rules.filter(i=>!C(i));n.length!==0&&(e+=`<conditionalFormatting${o.pivot?' pivot="1"':""} sqref="${$(o.sqref)}">${n.map(G).join("")}</conditionalFormatting>`)}return e}function K(t){let e="";for(const o of t){const n=o.rules.filter(i=>C(i)||i.dataBar?.ext);n.length!==0&&(e+=`<x14:conditionalFormatting xmlns:xm="${T}"${o.pivot?' pivot="1"':""}>${n.map(H).join("")}<xm:sqref>${$(o.sqref)}</xm:sqref></x14:conditionalFormatting>`)}return e?`<ext xmlns:x14="${L}" uri="${M}"><x14:conditionalFormattings>${e}</x14:conditionalFormattings></ext>`:""}function Q(t){for(const e of t)for(const o of e.rules)(C(o)||o.dataBar?.ext)&&!o.id&&(o.id=j())}function W(t){const e=/<\/extLst>\s*(?:<\/(?:\w+:)?worksheet>\s*)?$/.exec(t);return e?e.index:-1}function Y(t,e){const o=A(t);let n=o?t.slice(0,o.index)+t.slice(o.index+o[0].length):t;const i=K(e),r=W(n);if(!i)return r>=0?n.replace(/<extLst>\s*<\/extLst>(\s*(?:<\/(?:\w+:)?worksheet>\s*)?)$/,"$1"):n;if(r>=0)return n.slice(0,r)+i+n.slice(r);const l=n.lastIndexOf("</worksheet>"),s=`<extLst>${i}</extLst>`;return l>=0?n.slice(0,l)+s+n.slice(l):n+s}function at(t,e,o){const n=e??[];return Q(n),Y(o(t,"conditionalFormatting",J(n)),n)}const Z=t=>/^\s*[-+]?[\d.]+(?:[eE][-+]?\d+)?\s*$/.test(t);function rt(t,e){const o=i=>i.map(r=>typeof r.val=="string"&&!Z(r.val)?{...r,val:e(r.val)}:r),n={...t};return t.formulas&&(n.formulas=t.formulas.map(e)),t.colorScale&&(n.colorScale={...t.colorScale,cfvo:o(t.colorScale.cfvo)}),t.iconSet&&(n.iconSet={...t.iconSet,cfvo:o(t.iconSet.cfvo)}),t.dataBar&&(n.dataBar={...t.dataBar,cfvo:o(t.dataBar.cfvo)},t.dataBar.ext&&(n.dataBar.ext={...t.dataBar.ext,cfvo:o(t.dataBar.ext.cfvo)})),n}function st(t){return t.replace(/<conditionalFormatting\b[\s\S]*?<\/conditionalFormatting>/g,e=>" ".repeat(e.length))}export{D as X14_ICON_SETS,nt as applyCfExt,K as cfExtXml,J as cfMainXml,B as cfvoXml,h as colorAttrs,z as dxfToXml,C as extOnly,ot as extendRule,st as maskCfBlocks,it as parseDxfList,I as parseDxfNode,at as patchCf,Y as patchCfExt,W as sheetExtLstEnd,rt as shiftRuleFormulas};
|
|
1
|
+
import{child as a,children as p,parseTree as N,unescapeOoxml as E}from"../io/xml-scan.js";import{escapeMarkup as $,xmlAttr as P}from"../io/xml-escape.js";const V=new TextEncoder,u=t=>t==="1"||t==="true",L="http://schemas.microsoft.com/office/spreadsheetml/2009/9/main",T="http://schemas.microsoft.com/office/excel/2006/main",R="{B025F937-C7B1-47D3-B67F-A62EFF666E3E}",M="{78C0D931-6437-407d-A8EE-F0AAD7539E65}",D=new Set(["3Stars","3Triangles","5Boxes"]),j=()=>{const t=()=>Math.floor(Math.random()*65536).toString(16).padStart(4,"0");return`{${t()}${t()}-${t()}-4${t().slice(1)}-a${t().slice(1)}-${t()}${t()}${t()}}`.toUpperCase()};function nt(t,e){const o=a(e,"dataBar");o&&t.dataBar&&(o.a.minLength!==void 0&&(t.dataBar.minLength=Number(o.a.minLength)),o.a.maxLength!==void 0&&(t.dataBar.maxLength=Number(o.a.maxLength)));for(const n of p(a(e,"extLst"),"ext")){const i=a(n,"id");i&&(t.id=i.t.trim())}return t}const F=t=>t.map(e=>{const o=a(e,"f"),n={type:e.a.type,val:o?o.t:e.a.val??null};return e.a.gte!==void 0&&!u(e.a.gte)&&(n.gte=!1),n}),w=t=>{const e=t.type==="autoMin"?"min":t.type==="autoMax"?"max":t.type;return e==="min"||e==="max"?{type:e}:{type:e,val:t.val}};function q(t){const e=t.a,o=n=>a(t,n)?.a??null;return{cfvo:F(p(t,"cfvo")),minLength:e.minLength!==void 0?Number(e.minLength):10,maxLength:e.maxLength!==void 0?Number(e.maxLength):90,gradient:e.gradient===void 0?!0:u(e.gradient),border:u(e.border),borderColor:o("borderColor"),negFill:o("negativeFillColor"),negBorder:o("negativeBorderColor"),negFillSame:u(e.negativeBarColorSameAsPositive),negBorderSame:e.negativeBarBorderColorSameAsPositive===void 0?!0:u(e.negativeBarBorderColorSameAsPositive),axisPosition:e.axisPosition??"automatic",axisColor:o("axisColor"),direction:e.direction??"context"}}function X(t,e){const o=t.a,n={type:o.type,priority:Number(o.priority??0),dxfId:null,operator:o.operator??null,formulas:p(t,"f").map(l=>l.t),text:E(o.text??null),rank:o.rank!==void 0?Number(o.rank):null,percent:u(o.percent),bottom:u(o.bottom),aboveAverage:o.aboveAverage===void 0?!0:u(o.aboveAverage),equalAverage:u(o.equalAverage),stdDev:o.stdDev!==void 0?Number(o.stdDev):0,stopIfTrue:u(o.stopIfTrue),timePeriod:o.timePeriod??null,x14:!0};o.id&&(n.id=o.id);const i=a(t,"dxf");i&&(n.dxf=I(i,e));const c=a(t,"colorScale");c&&(n.colorScale={cfvo:F(p(c,"cfvo")),colors:p(c,"color").map(l=>l.a)});const f=a(t,"dataBar");if(f){const l=q(f);n.dataBar={cfvo:l.cfvo.map(w),color:a(f,"fillColor")?.a??{rgb:"FF638EC6"},showValue:f.a.showValue===void 0?!0:u(f.a.showValue),ext:l}}const s=a(t,"iconSet");return s&&(n.iconSet={name:s.a.iconSet??"3TrafficLights1",cfvo:F(p(s,"cfvo")),reverse:u(s.a.reverse),showValue:s.a.showValue===void 0?!0:u(s.a.showValue),x14:!0},u(s.a.custom)&&(n.iconSet.custom=p(s,"cfIcon").map(l=>({iconSet:l.a.iconSet,iconId:Number(l.a.iconId??0)})))),n}function A(t){return/<ext\b[^>]*>\s*<(\w+:)?conditionalFormattings\b[\s\S]*?<\/(\w+:)?conditionalFormattings>\s*<\/ext>/.exec(t)}function it(t,e,o){if(!e.includes("conditionalFormattings"))return;const n=A(e);if(n===null)return;let i;try{i=N(V.encode(`<r xmlns:x14="x" xmlns:xm="m" xmlns:xr="x">${n[0]}</r>`))}catch{return}const c=new Map;for(const s of t.cf)for(const l of s.rules)l.id&&c.set(l.id.toUpperCase(),l);const f=a(a(i,"ext"),"conditionalFormattings");for(const s of p(f,"conditionalFormatting")){const l=a(s,"sqref")?.t.trim()??"",r=[];for(const d of p(s,"cfRule")){const m=X(d,o),x=m.id?c.get(m.id.toUpperCase()):void 0;x!==void 0&&x.dataBar&&m.dataBar?(x.dataBar.ext=m.dataBar.ext,x.dataBar.showValue=x.dataBar.showValue&&m.dataBar.showValue):x===void 0&&r.push(m)}r.length>0&&l!==""&&t.cf.push({sqref:l,rules:r})}}function I(t,e){const o={},n=a(t,"font");if(n){const r=x=>{const g=a(n,x);return g!==void 0&&g.a.val!=="0"&&g.a.val!=="false"};a(n,"b")&&(o.bold=r("b")),a(n,"i")&&(o.italic=r("i")),a(n,"strike")&&(o.strike=r("strike"));const d=a(n,"u");d&&(o.underline=d.a.val==="none"?0:d.a.val==="double"||d.a.val==="doubleAccounting"?2:1);const m=e(a(n,"color"));m&&(o.color=m)}const i=a(t,"numFmt");i?.a.formatCode!==void 0&&(o.numFmt=i.a.formatCode);const c=a(t,"fill"),f=a(c,"patternFill");if(f){const r=f.a.patternType,d=a(f,"fgColor");o.pf={none:r==="none",auto:d?.a.auto==="1",fg:d&&d.a.auto!=="1"?e(d):null};const m=e(a(f,"bgColor")),x=e(a(f,"fgColor"));if(r===void 0||r==="solid"){const g=m??x;g&&(o.fill=g)}else r==="none"?o.noFill=!0:(o.pattern={type:r,fg:x??"#000000"},o.fill=m??"#FFFFFF")}const s=a(c,"gradientFill");if(s){const r=p(s,"stop").map(d=>({pos:Number(d.a.position??0),color:e(a(d,"color"))??"#FFFFFF"}));r.length>1&&(o.gradient={type:s.a.type==="path"?"path":"linear",degree:Number(s.a.degree??0),left:Number(s.a.left??0),right:Number(s.a.right??0),top:Number(s.a.top??0),bottom:Number(s.a.bottom??0),stops:r},o.fill=r[0].color)}const l=a(t,"border");if(l){const r=g=>{const b=a(l,g);return b&&b.a.style?{style:b.a.style,color:e(a(b,"color"))??"#000000"}:null},d={l:r("left"),r:r("right"),t:r("top"),b:r("bottom")},m=r("vertical"),x=r("horizontal");m&&(d.v=m),x&&(d.h=x),(d.l||d.r||d.t||d.b||m||x)&&(o.borders=d)}return o}const at=(t,e)=>p(a(t,"dxfs"),"dxf").map(o=>I(o,e)),v=t=>`FF${t.slice(1).toUpperCase()}`,U={General:0,0:1,"0.00":2,"#,##0":3,"#,##0.00":4,"0%":9,"0.00%":10,"0.00E+00":11,"# ?/?":12,"# ??/??":13,"mm-dd-yy":14,"d-mmm-yy":15,"d-mmm":16,"mmm-yy":17,"h:mm AM/PM":18,"h:mm:ss AM/PM":19,"h:mm":20,"h:mm:ss":21,"m/d/yy h:mm":22,"@":49};function _(t){const e=U[t];if(e!==void 0)return e;let o=0;for(let n=0;n<t.length;n++)o=(o*31+t.charCodeAt(n))%6e4;return 1e3+o}function z(t,e="dxf"){let o="";t.bold!==void 0&&(o+=t.bold?"<b/>":'<b val="0"/>'),t.italic!==void 0&&(o+=t.italic?"<i/>":'<i val="0"/>'),t.strike!==void 0&&(o+=t.strike?"<strike/>":'<strike val="0"/>'),t.underline?o+=t.underline===2?'<u val="double"/>':"<u/>":t.underline===0&&(o+='<u val="none"/>'),t.color&&(o+=`<color rgb="${v(t.color)}"/>`);const n=t.numFmt?`<numFmt numFmtId="${_(t.numFmt)}" formatCode="${$(t.numFmt)}"/>`:"";let i="";t.noFill?i='<fill><patternFill patternType="none"/></fill>':t.pattern?i=`<fill><patternFill patternType="${t.pattern.type}"><fgColor rgb="${v(t.pattern.fg??"#000000")}"/>${t.fill?`<bgColor rgb="${v(t.fill)}"/>`:""}</patternFill></fill>`:t.fill&&(i=`<fill><patternFill><bgColor rgb="${v(t.fill)}"/></patternFill></fill>`);let c="";if(t.borders){const f=(l,r)=>r?`<${l} style="${r.style}"><color rgb="${v(r.color??"#000000")}"/></${l}>`:"",s=f("left",t.borders.l)+f("right",t.borders.r)+f("top",t.borders.t)+f("bottom",t.borders.b)+f("vertical",t.borders.v)+f("horizontal",t.borders.h);s&&(c=`<border>${s}</border>`)}return`<${e}>${o?`<font>${o}</font>`:""}${n}${i}${c}</${e}>`}const B=t=>t.map(e=>`<cfvo type="${e.type}"${e.val!==null&&e.val!==void 0?` val="${$(e.val)}"`:""}${e.gte===!1?' gte="0"':""}/>`).join(""),h=t=>Object.entries(t).map(([e,o])=>`${e}="${$(o)}"`).join(" "),S=(t,e)=>e?`<x14:${t} ${h(e)}/>`:"";function y(t){return t.map(e=>{const o=e.gte===!1?' gte="0"':"";return e.val===null||e.val===void 0?`<x14:cfvo type="${e.type}"${o}/>`:`<x14:cfvo type="${e.type}"${o}><xm:f>${$(e.val)}</xm:f></x14:cfvo>`}).join("")}function C(t){return t.x14&&!t.dataBar?!0:!!t.iconSet&&(t.iconSet.x14||t.iconSet.custom!==void 0||D.has(t.iconSet.name))}function k(t){let e=`type="${t.type}" priority="${t.priority}"`;return t.stopIfTrue&&(e+=' stopIfTrue="1"'),t.operator&&(e+=` operator="${t.operator}"`),t.text!==null&&t.text!==void 0&&(e+=` text="${P(t.text)}"`),t.rank!==null&&t.rank!==void 0&&(e+=` rank="${t.rank}"`),t.percent&&(e+=' percent="1"'),t.bottom&&(e+=' bottom="1"'),t.type==="aboveAverage"&&(t.aboveAverage===!1&&(e+=' aboveAverage="0"'),t.equalAverage&&(e+=' equalAverage="1"'),t.stdDev&&(e+=` stdDev="${t.stdDev}"`)),t.timePeriod&&(e+=` timePeriod="${t.timePeriod}"`),e}function G(t){let e=k(t);t.dxfId!==null&&t.dxfId!==void 0&&(e=e.replace(/( priority="\d+")/,` dxfId="${t.dxfId}"$1`));let o=(t.formulas??[]).map(n=>`<formula>${$(n)}</formula>`).join("");if(t.colorScale&&(o+=`<colorScale>${B(t.colorScale.cfvo)}${t.colorScale.colors.map(n=>`<color ${h(n)}/>`).join("")}</colorScale>`),t.dataBar){const n=t.dataBar,i=n.ext,c=i?i.minLength===0&&i.maxLength===100?[10,90]:[i.minLength,i.maxLength]:[n.minLength??10,n.maxLength??90],f=`${c[0]!==10?` minLength="${c[0]}"`:""}${c[1]!==90?` maxLength="${c[1]}"`:""}${n.showValue===!1?' showValue="0"':""}`;o+=`<dataBar${f}>${B(i?i.cfvo.map(w):n.cfvo)}<color ${h(n.color)}/></dataBar>`,n.ext&&(o+=`<extLst><ext xmlns:x14="${L}" uri="${R}"><x14:id>${t.id}</x14:id></ext></extLst>`)}return t.iconSet&&(o+=`<iconSet iconSet="${t.iconSet.name}"${t.iconSet.reverse?' reverse="1"':""}${t.iconSet.showValue===!1?' showValue="0"':""}>${B(t.iconSet.cfvo)}</iconSet>`),`<cfRule ${e}>${o}</cfRule>`}function O(t){const e=t.ext;let o=` minLength="${e.minLength}" maxLength="${e.maxLength}"`;t.showValue===!1&&(o+=' showValue="0"'),e.gradient===!1&&(o+=' gradient="0"'),e.border&&(o+=' border="1"'),e.direction&&e.direction!=="context"&&(o+=` direction="${e.direction}"`),e.negFillSame&&(o+=' negativeBarColorSameAsPositive="1"'),e.negBorderSame===!1&&(o+=' negativeBarBorderColorSameAsPositive="0"'),e.axisPosition&&e.axisPosition!=="automatic"&&(o+=` axisPosition="${e.axisPosition}"`);const n=(e.border?S("borderColor",e.borderColor):"")+(e.negFillSame?"":S("negativeFillColor",e.negFill))+(e.border&&e.negBorderSame===!1?S("negativeBorderColor",e.negBorder):"")+(e.axisPosition==="none"?"":S("axisColor",e.axisColor));return`<x14:dataBar${o}>${y(e.cfvo)}${n}</x14:dataBar>`}function H(t){if(t.dataBar)return`<x14:cfRule type="dataBar" id="${t.id}">${O(t.dataBar)}</x14:cfRule>`;let e=(t.formulas??[]).map(o=>`<xm:f>${$(o)}</xm:f>`).join("");if(t.colorScale&&(e+=`<x14:colorScale>${y(t.colorScale.cfvo)}${t.colorScale.colors.map(o=>`<x14:color ${h(o)}/>`).join("")}</x14:colorScale>`),t.iconSet){const o=t.iconSet,n=o.custom!==void 0;e+=`<x14:iconSet iconSet="${o.name}"${o.showValue===!1?' showValue="0"':""}${o.reverse?' reverse="1"':""}${n?' custom="1"':""}>${y(o.cfvo)}${n?o.custom.map(i=>`<x14:cfIcon iconSet="${i.iconSet}" iconId="${i.iconId}"/>`).join(""):""}</x14:iconSet>`}return t.dxf&&(e+=z(t.dxf,"x14:dxf")),`<x14:cfRule ${k(t)} id="${t.id}">${e}</x14:cfRule>`}function J(t){let e="";for(const o of t){const n=o.rules.filter(i=>!C(i));n.length!==0&&(e+=`<conditionalFormatting${o.pivot?' pivot="1"':""} sqref="${$(o.sqref)}">${n.map(G).join("")}</conditionalFormatting>`)}return e}function K(t){let e="";for(const o of t){const n=o.rules.filter(i=>C(i)||i.dataBar?.ext);n.length!==0&&(e+=`<x14:conditionalFormatting xmlns:xm="${T}"${o.pivot?' pivot="1"':""}>${n.map(H).join("")}<xm:sqref>${$(o.sqref)}</xm:sqref></x14:conditionalFormatting>`)}return e?`<ext xmlns:x14="${L}" uri="${M}"><x14:conditionalFormattings>${e}</x14:conditionalFormattings></ext>`:""}function Q(t){for(const e of t)for(const o of e.rules)(C(o)||o.dataBar?.ext)&&!o.id&&(o.id=j())}function W(t){const e=/<\/extLst>\s*(?:<\/(?:\w+:)?worksheet>\s*)?$/.exec(t);return e?e.index:-1}function Y(t,e){const o=A(t);let n=o?t.slice(0,o.index)+t.slice(o.index+o[0].length):t;return Z(n,K(e))}function Z(t,e){const o=W(t);if(!e)return o>=0?t.replace(/<extLst>\s*<\/extLst>(\s*(?:<\/(?:\w+:)?worksheet>\s*)?)$/,"$1"):t;if(o>=0)return t.slice(0,o)+e+t.slice(o);const n=t.lastIndexOf("</worksheet>"),i=`<extLst>${e}</extLst>`;return n>=0?t.slice(0,n)+i+t.slice(n):t+i}function rt(t,e,o){const n=e??[];return Q(n),Y(o(t,"conditionalFormatting",J(n)),n)}const tt=t=>/^\s*[-+]?[\d.]+(?:[eE][-+]?\d+)?\s*$/.test(t);function st(t,e){const o=i=>i.map(c=>typeof c.val=="string"&&!tt(c.val)?{...c,val:e(c.val)}:c),n={...t};return t.formulas&&(n.formulas=t.formulas.map(e)),t.colorScale&&(n.colorScale={...t.colorScale,cfvo:o(t.colorScale.cfvo)}),t.iconSet&&(n.iconSet={...t.iconSet,cfvo:o(t.iconSet.cfvo)}),t.dataBar&&(n.dataBar={...t.dataBar,cfvo:o(t.dataBar.cfvo)},t.dataBar.ext&&(n.dataBar.ext={...t.dataBar.ext,cfvo:o(t.dataBar.ext.cfvo)})),n}function ct(t){return t.replace(/<(conditionalFormatting\b[^>]*>)([\s\S]*?)<\/conditionalFormatting>/g,(e,o)=>`<${o}`.padEnd(e.length))}export{D as X14_ICON_SETS,Z as appendSheetExt,it as applyCfExt,K as cfExtXml,J as cfMainXml,B as cfvoXml,h as colorAttrs,z as dxfToXml,C as extOnly,nt as extendRule,ct as maskCfBlocks,at as parseDxfList,I as parseDxfNode,rt as patchCf,Y as patchCfExt,W as sheetExtLstEnd,st as shiftRuleFormulas};
|
package/cells/docprops-xml.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{children as
|
|
2
|
-
`,
|
|
1
|
+
import{children as B,parseTree as I,unescapeOoxml as b}from"../io/xml-scan.js";import{xmlAttr as M,xmlText as $}from"../io/xml-escape.js";const g=`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
|
2
|
+
`,S="http://schemas.openxmlformats.org/package/2006/metadata/core-properties",D="http://purl.org/dc/elements/1.1/",O="http://purl.org/dc/terms/",E="http://www.w3.org/2001/XMLSchema-instance",V="http://schemas.openxmlformats.org/officeDocument/2006/extended-properties",y="http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes",F="http://schemas.openxmlformats.org/officeDocument/2006/custom-properties",L="{D5CDD505-2E9C-101B-9397-08002B2CF9AE}",m={core:{path:"docProps/core.xml",type:"application/vnd.openxmlformats-package.core-properties+xml",rel:"http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties"},app:{path:"docProps/app.xml",type:"application/vnd.openxmlformats-officedocument.extended-properties+xml",rel:"http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties"},custom:{path:"docProps/custom.xml",type:"application/vnd.openxmlformats-officedocument.custom-properties+xml",rel:"http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties"}},N={title:"dc:title",subject:"dc:subject",creator:"dc:creator",keywords:"cp:keywords",description:"dc:description",category:"cp:category",contentStatus:"cp:contentStatus",lastModifiedBy:"cp:lastModifiedBy",lastPrinted:"cp:lastPrinted",revision:"cp:revision"},_={created:"dcterms:created",modified:"dcterms:modified"},A={manager:"Manager",company:"Company",hyperlinkBase:"HyperlinkBase"},P=e=>e.slice(e.indexOf(":")+1);function h(e,t){const o=e?.c.find(s=>P(s.n)===t);return o?b(o.t):void 0}function q(e,t={}){const o={custom:[],sources:{core:e.core??null,app:e.app??null,custom:e.custom??null},paths:{core:m.core.path,app:m.app.path,custom:m.custom.path,...t},changed:!1},s=i=>{if(!i)return null;try{return I(new TextEncoder().encode(i))}catch{return null}},r=s(e.core);for(const i of[...Object.keys(N),...Object.keys(_)]){const l=h(r,i);l!==void 0&&(o[i]=l)}const c=s(e.app);for(const[i,l]of Object.entries(A)){const f=h(c,l);f!==void 0&&(o[i]=f)}const p=h(c,"Application");p!==void 0&&(o.application=p);const n=h(c,"AppVersion");n!==void 0&&(o.appVersion=n);const u=h(c,"TotalTime");u!==void 0&&(o.totalTime=Number(u)||0);const a=s(e.custom),d=e.custom?[...e.custom.matchAll(/<property\b[\s\S]*?<\/property>/g)].map(i=>i[0]):[];return B(a,"property").forEach((i,l)=>{const f=i.c[0];if(!f)return;const v=P(f.n),x=X[v],C=b(f.t);o.custom.push({name:b(i.a.name??""),type:x??"text",value:x?H(x,C):C,raw:d[l]??null,vt:v})}),o}const X={lpwstr:"text",lpstr:"text",bstr:"text",i1:"number",i2:"number",i4:"number",i8:"number",int:"number",ui1:"number",ui2:"number",ui4:"number",ui8:"number",uint:"number",r4:"number",r8:"number",decimal:"number",bool:"bool",filetime:"date",date:"date"};function H(e,t){return e==="number"?Number(t):e==="bool"?t==="true"||t==="1":t}function U(e){switch(e.type){case"number":{const t=Number(e.value)||0;return Number.isInteger(t)&&Math.abs(t)<2147483648?`<vt:i4>${t}</vt:i4>`:`<vt:r8>${t}</vt:r8>`}case"bool":return`<vt:bool>${e.value?"true":"false"}</vt:bool>`;case"date":return`<vt:filetime>${$(e.value)}</vt:filetime>`;default:return`<vt:lpwstr>${$(e.value)}</vt:lpwstr>`}}function w(e,t,o,s=""){const r=P(t),c=new RegExp(`<((?:[\\w.-]+:)?${r})\\b[^>]*?(?:/>|>[\\s\\S]*?</\\1\\s*>)`),p=o==null||o==="",n=c.exec(e);if(p)return n?e.slice(0,n.index)+e.slice(n.index+n[0].length):e;const u=R.exec(e),a=n&&T(n[1]),d=a&&new RegExp(`\\sxmlns:${a}\\s*=`).test(u[0])?n[1]:t.includes(":")||!T(u[1])?t:`${T(u[1])}:${t}`,i=`<${d}${s}>${$(o)}</${d}>`;if(n)return e.slice(0,n.index)+i+e.slice(n.index+n[0].length);const l=e.lastIndexOf("</");return e.slice(0,l)+i+e.slice(l)}const R=/<((?:[\w.-]+:)?(?:coreProperties|Properties))\b[^>]*>/,T=e=>e.includes(":")?e.slice(0,e.indexOf(":")):"";function j(e,t,o){return e.replace(R,(s,r)=>{const c=s.endsWith("/>")?`${s.slice(0,-2)}></${r}>`:s;return new RegExp(`\\sxmlns:${t}\\s*=`).test(s)?c:c.replace(r,()=>`${r} xmlns:${t}="${o}"`)})}function W(e){let t=e.sources?.core;t||(t=`${g}<cp:coreProperties xmlns:cp="${S}" xmlns:dc="${D}" xmlns:dcterms="${O}" xmlns:dcmitype="http://purl.org/dc/dcmitype/" xmlns:xsi="${E}"></cp:coreProperties>`);for(const[o,s]of[["cp",S],["dc",D],["dcterms",O],["xsi",E]])t=j(t,o,s);for(const[o,s]of Object.entries(N))t=w(t,s,e[o]);for(const[o,s]of Object.entries(_))t=w(t,s,e[o],' xsi:type="dcterms:W3CDTF"');return t}function Y(e){let t=e.sources?.app;t||(t=`${g}<Properties xmlns="${V}" xmlns:vt="${y}"><Application>8sheets</Application></Properties>`),t=j(t,"vt",y);for(const[o,s]of Object.entries(A))t=w(t,s,e[o]);return t}function G(e){const t=e.custom.map((o,s)=>{const r=s+2;return o.raw&&!o.edited?o.raw.replace(/\bpid="\d+"/,()=>`pid="${r}"`):`<property fmtid="${L}" pid="${r}" name="${M(o.name)}">${U(o)}</property>`});return`${g}<Properties xmlns="${F}" xmlns:vt="${y}">${t.join("")}</Properties>`}let k=()=>new Date;function z(e){k=e??(()=>new Date)}const J=()=>k();function ee(e){const t=e.docProps,o=e.source===null;if(!t&&!o)return null;const s=J().toISOString().replace(/\.\d+Z$/,"Z"),r=t??{custom:[],sources:{},paths:{},changed:!1};e.docProps=r,!r.created&&o&&(r.created=s),r.modified=s;const c=[],p=r.paths??{},n=(a,d)=>c.push({key:a,path:p[a]??m[a].path,type:m[a].type,rel:m[a].rel,xml:d});(o||r.changed||r.sources?.core)&&n("core",W(r)),(o||r.changed&&(r.sources?.app||r.manager||r.company||r.hyperlinkBase))&&n("app",Y(r)),r.custom.length>0&&(o||r.customChanged)&&n("custom",G(r));const u=r.customChanged===!0&&r.custom.length===0&&!!r.sources?.custom;return c.length||u?{parts:c,dropCustom:u,customPath:p.custom??m.custom.path}:null}function te(e,t,o=!0){const s=e.docProps;if(!(!s||!t)){for(const r of t.parts)s.sources[r.key]=r.xml;if(t.dropCustom&&(s.sources.custom=null),!!o){for(const r of s.custom)r.edited=!1;s.changed=!1,s.customChanged=!1}}}function oe(e,t){if(!t)return e;let o=e;t.dropCustom&&(o=o.replace(new RegExp(`<Override\\b[^>]*PartName="/${t.customPath.replace(/[.]/g,"\\.")}"[^>]*/>`),""));const s=t.parts.filter(r=>!o.includes(`PartName="/${r.path}"`)).map(r=>`<Override PartName="/${r.path}" ContentType="${r.type}"/>`).join("");return s?o.replace("</Types>",()=>`${s}</Types>`):o}function K(e){return e?e.parts.map(t=>`<Relationship Id="rIdProps_${t.key}" Type="${t.rel}" Target="${t.path}"/>`).join(""):""}async function re(e,t,o,s){if(!o)return;for(const n of o.parts)await e.addBytes(n.path,n.xml),s.add(n.path);if(o.dropCustom&&s.add(o.customPath),!t||!t.has("_rels/.rels"))return;let r=await t.text("_rels/.rels");const c=r;o.dropCustom&&(r=r.replace(/<Relationship\b[^>]*custom-properties[^>]*\/>/,""));const p=o.parts.filter(n=>!r.includes(`Type="${n.rel}"`));p.length&&(r=r.replace("</Relationships>",()=>`${K({parts:p})}</Relationships>`)),r!==c&&(await e.addBytes("_rels/.rels",r),s.add("_rels/.rels"))}function se(e){const t={};for(const o of e.matchAll(/<Relationship\b[^>]*\/>/g)){const s=/\bType="([^"]+)"/.exec(o[0])?.[1],r=/\bTarget="([^"]+)"/.exec(o[0])?.[1];if(!(!s||!r))for(const[c,p]of Object.entries(m))s===p.rel&&(t[c]=r.replace(/^\//,""))}return t}export{m as PARTS,te as docPropsCommitted,se as docPropsPaths,ee as docPropsPlan,K as docPropsRels,oe as docPropsTypes,q as parseDocProps,z as setSaveClock,re as writeDocProps};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{MAX_COLS as Q}from"../core/address.js";import{BOOL as O,ERR as $,ERRORS as U,KIND_MASK as w,NUM as h,STR as F}from"../core/sheet.js";import{FILL_MARK as T,formatGeneral as V,getFormatter as D,partsToSerial as _,serialToParts as A}from"../core/numfmt.js";import{cfEffectAt as b,iconAt as W}from"../core/cond-format.js";import{parseInput as Y}from"../core/input.js";import{asSpec as z,dxfFilterColor as P}from"./filter-file.js";import{cellRich as I}from"./rich-values.js";function E(r,t,e,n){switch(t){case h:return n.numFmt==="General"?V(e):D(n.numFmt).number(e,r.dateOffset);case F:{const a=r.strings.get(e);return n.numFmt==="General"||n.numFmt==="@"?a:D(n.numFmt).text(a)}case O:return e?"TRUE":"FALSE";case $:return U[e]??"#N/A";default:return""}}const k=new RegExp(`${T}.?${T}`,"g"),S=r=>(r.indexOf(T)>=0?r.replace(k," "):r).trim();function dt(r,t,e,n,a=!1){const s=t.kind(e,n)&w,u=t.value(e,n);if(s===0)return"";if(s===F)return`s${r.strings.get(u).toLowerCase()}`;if(s===O)return`${a?"b":"s"}${u?"true":"false"}`;if(s===$&&t.valueMeta!==null){const y=r.richImages?.get(t.valueMeta.get(e*Q+n));if(y!==void 0)return`p${y.id}`;const c=I(r,t,e,n);if(c)return`s${c.view.text.toLowerCase()}`}return s===h&&a?`n${u}`:s===h?`n${u}${S(E(r,s,u,r.styles.get(t.style(e,n)))).toLowerCase()}`:`${s}:${u}`}const G=new Map;function B(r){if(!r||r==="General")return!1;let t=G.get(r);if(t===void 0){const e=r.replace(/"[^"]*"/g,"").replace(/\\./g,"").replace(/\[[^\]]*\]/g,"").replace(/_./g,"").replace(/\*./g,"");t=/[ymdhs]/i.test(e)&&!/^[#0.,?/ %E+-]+$/.test(e),G.set(r,t)}return t}function q(r=new Date){return _(r.getFullYear(),r.getMonth()+1,r.getDate())}function d(r,t){const e=r*12+(t-1);return _(Math.floor(e/12),e%12+1,1)}function X(r,t=q()){const e=A(t),n=t-e.weekday,a=Math.floor((e.month-1)/3),s=u=>d(e.year,u*3+1);switch(r){case"tomorrow":return[t+1,t+2];case"today":return[t,t+1];case"yesterday":return[t-1,t];case"nextWeek":return[n+7,n+14];case"thisWeek":return[n,n+7];case"lastWeek":return[n-7,n];case"nextMonth":return[d(e.year,e.month+1),d(e.year,e.month+2)];case"thisMonth":return[d(e.year,e.month),d(e.year,e.month+1)];case"lastMonth":return[d(e.year,e.month-1),d(e.year,e.month)];case"nextQuarter":return[s(a+1),s(a+2)];case"thisQuarter":return[s(a),s(a+1)];case"lastQuarter":return[s(a-1),s(a)];case"nextYear":return[d(e.year+1,1),d(e.year+2,1)];case"thisYear":return[d(e.year,1),d(e.year+1,1)];case"lastYear":return[d(e.year-1,1),d(e.year,1)];case"yearToDate":return[d(e.year,1),t+1];default:return null}}function j(r){let t="";for(let e=0;e<r.length;e++){const n=r[e];n==="~"&&e+1<r.length&&"*?~".includes(r[e+1])?t+=`\\${r[++e]}`:n==="*"?t+="[\\s\\S]*":n==="?"?t+="[\\s\\S]":t+=n.replace(/[.+^${}()|[\]\\/-]/g,"\\$&")}return new RegExp(`^${t}$`,"i")}const H=r=>/(^|[^~])[*?]/.test(r);function J(r){const t=r.trim();if(t==="")return null;const e=Number(t);if(Number.isFinite(e))return e;const n=Y(t);return n.kind===h?n.value:null}const Z=new Intl.Collator("en",{sensitivity:"accent",numeric:!1});function tt(r){const{op:t,val:e}=r,n=J(e),a=e.trim().toLowerCase(),s=t==="equal"||t==="notEqual",u=s&&H(e)?j(e):null,y=e.replace(/~([*?~])/g,"$1").toLowerCase(),c=s&&e.trim()==="";return(o,i,l)=>{if(c)return o!==0;if(s){if(t==="notEqual"&&o===h&&n!==null&&u===null)return i!==n;const m=u!==null?o===F&&u.test(l):o!==0&&l.toLowerCase()===y;return t==="equal"?m:!m}if(o===0)return!1;if(n!==null){if(o!==h)return!1;switch(t){case"greaterThan":return i>n;case"greaterThanOrEqual":return i>=n;case"lessThan":return i<n;default:return i<=n}}if(o!==F)return!1;const f=Z.compare(l,a);switch(t){case"greaterThan":return f>0;case"greaterThanOrEqual":return f>=0;case"lessThan":return f<0;default:return f<=0}}}function et(r,t,e){return r.y!==t.year?!1:r.group==="year"?!0:r.m!==t.month?!1:r.group==="month"?!0:r.d!==t.day?!1:r.group==="day"?!0:r.h!==e.h?!1:r.group==="hour"?!0:r.i!==e.m?!1:r.group==="minute"?!0:r.s===e.s}function rt(r){const t=Math.round((r-Math.floor(r))*86400);return{h:Math.floor(t/3600)%24,m:Math.floor(t/60)%60,s:t%60}}function K(r,t,e){const n=[];for(let a=t.r0+1;a<=t.r1;a++){const s=r.kind(a,e)&w;s===h?n.push(r.value(a,e)):s===$&&(n.hasError=!0)}return n}function nt(r,t){const e=r.length;if(e===0)return null;const n=t.percent?Math.max(1,Math.floor(e*t.val/100)):Math.min(e,Math.max(1,Math.floor(t.val))),a=Float64Array.from(r).sort();return t.top?a[e-Math.min(n,e)]:a[Math.min(n,e)-1]}function ut(r,t,e,n,a=r.styles.get(t.style(e,n))){const s=b(t,e,n,r),u=s?.noFill?null:s?.fill??a.fill??null;return u?u.toLowerCase():null}function at(r,t,e,n,a=r.styles.get(t.style(e,n))){const s=b(t,e,n,r)?.color??a.color??null;return s?s.toLowerCase():null}const st=(r,t,e,n)=>W(t,e,n,r),ot=(r,t)=>P(r.dxfs?.[t.dxfId],t.cell);function lt(r,t,e,n,a,s=q()){const u=z(a),{styles:y}=r;switch(u.kind){case"values":{const c=new Set(u.values.map(m=>m.trim().toLowerCase())),{blank:o}=u,i=u.dates??[],l=new Map,f=new Map;return c.size===0&&i.length===0&&!o?()=>!0:m=>{const p=t.kind(m,n)&w;if(p===0)return o;const g=t.value(m,n);if(p===F){const M=t.style(m,n),R=g*65536+M;let v=l.get(R);if(v===void 0){const N=S(E(r,p,g,y.get(M))).toLowerCase();v=N===""?o:c.has(N),l.set(R,v)}return v}const x=y.get(t.style(m,n));if(p===h&&i.length>0&&B(x.numFmt)){const M=A(Math.floor(g)),R=rt(g);for(const v of i)if(et(v,M,R))return!0;return!1}let C=f.get(x);C===void 0&&(C=new Map,f.set(x,C));let L=C.get(g);if(L===void 0||p!==h){const M=p===$&&t.valueMeta!==null?I(r,t,m,n):null;L=c.has((M?M.view.text:S(E(r,p,g,x))).toLowerCase()),p===h&&C.set(g,L)}return L}}case"custom":{const c=u.rules.map(tt),{and:o}=u;return i=>{const l=t.kind(i,n)&w,f=l===0?0:t.value(i,n),m=l===$&&t.valueMeta!==null?I(r,t,i,n):null,p=l===0?"":m?m.view.text:S(E(r,l,f,y.get(t.style(i,n))));if(c.length===1)return c[0](l,f,p);const g=c[0](l,f,p),x=c[1](l,f,p);return o?g&&x:g||x}}case"top10":{const c=K(t,e,n);if(c.hasError)return()=>!0;const o=nt(c,u);return u.filterVal=o??void 0,o===null?()=>!0:i=>{if((t.kind(i,n)&w)!==h)return!1;const l=t.value(i,n);return u.top?l>=o:l<=o}}case"dynamic":{if(u.type==="aboveAverage"||u.type==="belowAverage"){const l=K(t,e,n);let f=0;for(const g of l)f+=g;const m=l.length&&!l.hasError?f/l.length:0;u.val=m;const p=u.type==="aboveAverage";return g=>{if((t.kind(g,n)&w)!==h)return!1;const x=t.value(g,n);return p?x>m:x<m}}const c=/^Q([1-4])$/.exec(u.type),o=/^M(1[0-2]|[1-9])$/.exec(u.type);if(c||o){const l=c?(Number(c[1])-1)*3+1:Number(o[1]),f=c?l+2:l;return m=>{if((t.kind(m,n)&w)!==h)return!1;const p=A(Math.floor(t.value(m,n))).month;return p>=l&&p<=f}}const i=X(u.type,s);return i===null?()=>!0:([u.val,u.maxVal]=i,l=>{if((t.kind(l,n)&w)!==h)return!1;const f=t.value(l,n);return f>=i[0]&&f<i[1]})}case"color":{const c=ot(r,u),{cell:o}=u;return i=>(o?ut(r,t,i,n):at(r,t,i,n))===c.color}case"icon":return c=>{const o=st(r,t,c,n);return u.iconId===void 0?o===null:o!==null&&o.iconSet===u.iconSet&&o.iconId===u.iconId};default:return null}}function yt(r,t,e,n=q()){const a=Math.max(0,e.r1-e.r0),s=new Uint8Array(a).fill(1);for(const[u,y]of e.columns){const c=lt(r,t,e,u,y,n);if(c!==null)for(let o=0;o<a;o++)s[o]===1&&!c(e.r0+1+o)&&(s[o]=0)}return s}function xt(r,t){const e=Math.max(0,t.r1-t.r0);let n=0;if(r.filteredRows)if(r.filteredRows.size<=e)for(const a of r.filteredRows)a>t.r0&&a<=t.r1&&n++;else for(let a=t.r0+1;a<=t.r1;a++)r.filteredRows.has(a)&&n++;return{shown:e-n,total:e}}export{ut as cellFillColor,at as cellFontColor,st as cellIcon,E as cellText,S as cleanText,lt as compileColumn,dt as duplicateKey,X as dynamicRange,yt as evaluateFilter,xt as filterCounts,B as isDateFormat,q as todaySerial,nt as top10Threshold};
|
package/cells/filter-file.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{child as p,children as g,parseTree as V,unescapeOoxml as y}from"../io/xml-scan.js";import{escapeMarkup as F,xmlAttr as v}from"../io/xml-escape.js";import{parseRangeRef as C,rangeRef as I,sheetPrefix as j}from"../core/address.js";const q=new TextEncoder,$=e=>e==="1"||e==="true",b=e=>e==="0"||e==="false",x=e=>e===void 0||e===""?void 0:Number(e),Y=["equal","notEqual","greaterThan","greaterThanOrEqual","lessThan","lessThanOrEqual"];function D(e){if(e instanceof Set){const t=[];let n=!1;for(const r of e)r===""?n=!0:t.push(r);return{kind:"values",values:t,blank:n,dates:[]}}return e}function k(e){return{group:e.dateTimeGrouping??"year",y:x(e.year),m:x(e.month),d:x(e.day),h:x(e.hour),i:x(e.minute),s:x(e.second)}}const N=e=>e.slice(e.indexOf(":")+1);function P(e,t){for(const n of e.c){if(N(n.n)===t)return n;const r=P(n,t);if(r)return r}return null}function W(e,t){const n=p(e,"filters");if(n)return{kind:"values",values:g(n,"filter").map(u=>y(u.a.val??"")),blank:$(n.a.blank),dates:g(n,"dateGroupItem").map(u=>k(u.a)),calendarType:n.a.calendarType};const r=p(e,"customFilters");if(r)return{kind:"custom",and:$(r.a.and),rules:g(r,"customFilter").map(u=>({op:u.a.operator??"equal",val:y(u.a.val??"")}))};const o=p(e,"top10");if(o)return{kind:"top10",top:!b(o.a.top),percent:$(o.a.percent),val:Number(o.a.val??10),filterVal:x(o.a.filterVal)};const i=p(e,"dynamicFilter");if(i)return{kind:"dynamic",type:i.a.type??"null",val:x(i.a.val),maxVal:x(i.a.maxVal)};const l=p(e,"colorFilter");if(l)return{kind:"color",cell:!b(l.a.cellColor),dxfId:x(l.a.dxfId)};const a=p(e,"iconFilter");if(a)return{kind:"icon",iconSet:a.a.iconSet??"3Arrows",iconId:x(a.a.iconId)};const s=p(e,"extLst");if(s){const u=P(s,"filters");if(u)return{kind:"values",values:u.c.filter(f=>N(f.n)==="filter").map(f=>y(f.a.val??"")),blank:$(u.a.blank),dates:u.c.filter(f=>N(f.n)==="dateGroupItem").map(f=>k(f.a))}}return e.c.length>0?{kind:"raw",xml:t}:null}const S=(e,t,n=0)=>{const r=e.indexOf(`<${t}`,n);if(r<0)return null;const o=e.charCodeAt(r+t.length+1);if(o!==32&&o!==47&&o!==62&&o!==10&&o!==13&&o!==9)return S(e,t,r+1);const i=e.indexOf(">",r);if(i<0)return null;if(e[i-1]==="/")return{at:r,end:i+1,text:e.slice(r,i+1)};const l=e.indexOf(`</${t}>`,i);if(l<0)return null;const a=l+t.length+3;return{at:r,end:a,text:e.slice(r,a)}},G='xmlns:xr="x" xmlns:xr3="x" xmlns:x14="x" xmlns:xlrd2="x" xmlns:mc="x" xmlns:xm="x" xmlns:r="x" xmlns:x="x" xmlns:xr2="x" xmlns:xr6="x" xmlns:xr10="x"',T=e=>V(q.encode(`<root ${G}>${e}</root>`)).c[0];function B(e){const t=C(e.a.ref??"");return t?{...t,byColumns:$(e.a.columnSort),caseSensitive:$(e.a.caseSensitive),conditions:g(e,"sortCondition").map(n=>({...C(n.a.ref??"")??t,desc:$(n.a.descending),sortBy:n.a.sortBy??"value",customList:y(n.a.customList),dxfId:x(n.a.dxfId),iconSet:n.a.iconSet,iconId:x(n.a.iconId)}))}:null}function L(e){const t=T(e),n=C(t?.a.ref??"");if(!n)return null;const r=new Map;let o=null,i=0;for(const a of g(t,"filterColumn")){const s=S(e,"filterColumn",i);i=s?s.end:i;const u=n.c0+Number(a.a.colId??0),f=W(a,s?.text??"");f&&r.set(u,f),($(a.a.hiddenButton)||b(a.a.showButton))&&(o??=new Map,o.set(u,{hidden:$(a.a.hiddenButton),noShow:b(a.a.showButton)}))}const l=p(t,"sortState");return{...n,columns:r,buttons:o,sortState:l?B(l):null}}function A(e){const t=T(e);return t?B(t):null}function ee(e){const t={autoFilter:null,sortState:null};if(!e)return t;try{const n=S(e,"autoFilter");n&&(t.autoFilter=L(n.text));const r=n?n.end:0,o=S(e,"sortState",r),i=e.indexOf("<mergeCells");o&&(i<0||o.at<i)&&(t.sortState=A(o.text))}catch{}return t}function w(e){return String(e)}function X(e){const t=[];return e.y!==void 0&&t.push(`year="${e.y}"`),e.m!==void 0&&t.push(`month="${e.m}"`),e.d!==void 0&&t.push(`day="${e.d}"`),e.h!==void 0&&t.push(`hour="${e.h}"`),e.i!==void 0&&t.push(`minute="${e.i}"`),e.s!==void 0&&t.push(`second="${e.s}"`),t.push(`dateTimeGrouping="${e.group}"`),`<dateGroupItem ${t.join(" ")}/>`}function z(e){switch(e.kind){case"values":{const t=e.values.map(r=>`<filter val="${v(r)}"/>`).join("")+(e.dates??[]).map(X).join(""),n=`${e.blank?' blank="1"':""}${e.calendarType?` calendarType="${F(e.calendarType)}"`:""}`;return t?`<filters${n}>${t}</filters>`:`<filters${n}/>`}case"custom":return`<customFilters${e.and?' and="1"':""}>${e.rules.map(t=>`<customFilter${t.op&&t.op!=="equal"?` operator="${t.op}"`:""} val="${v(t.val)}"/>`).join("")}</customFilters>`;case"top10":return`<top10${e.top?"":' top="0"'}${e.percent?' percent="1"':""} val="${w(e.val)}"${e.filterVal!==void 0?` filterVal="${w(e.filterVal)}"`:""}/>`;case"dynamic":return`<dynamicFilter type="${F(e.type)}"${e.val!==void 0?` val="${w(e.val)}"`:""}${e.maxVal!==void 0?` maxVal="${w(e.maxVal)}"`:""}/>`;case"color":return`<colorFilter${e.dxfId!==void 0?` dxfId="${e.dxfId}"`:""}${e.cell?"":' cellColor="0"'}/>`;case"icon":return`<iconFilter iconSet="${F(e.iconSet)}"${e.iconId!==void 0?` iconId="${e.iconId}"`:""}/>`;default:return""}}function U(e,t,n){if(t?.kind==="raw")return t.xml.replace(/\bcolId="\d+"/,`colId="${e}"`);const r=`${n?.hidden?' hiddenButton="1"':""}${n?.noShow?' showButton="0"':""}`,o=t?z(D(t)):"";return o?`<filterColumn colId="${e}"${r}>${o}</filterColumn>`:`<filterColumn colId="${e}"${r}/>`}function E(e){if(!e||e.conditions.length===0)return"";const t=e.conditions.map(n=>{const r=[`ref="${I(n)}"`];return n.desc&&r.push('descending="1"'),n.sortBy&&n.sortBy!=="value"&&r.push(`sortBy="${n.sortBy}"`),n.customList&&r.push(`customList="${v(n.customList)}"`),n.dxfId!==void 0&&r.push(`dxfId="${n.dxfId}"`),n.iconSet&&r.push(`iconSet="${F(n.iconSet)}"`),n.iconId!==void 0&&r.push(`iconId="${n.iconId}"`),`<sortCondition ${r.join(" ")}/>`}).join("");return`<sortState ref="${I(e)}"${e.byColumns?' columnSort="1"':""}${e.caseSensitive?' caseSensitive="1"':""}>${t}</sortState>`}function Z(e,t=!0){const n=new Set(e.columns?.keys()??[]);if(e.buttons)for(const l of e.buttons.keys())n.add(l);const r=[...n].sort((l,a)=>l-a).map(l=>U(l-e.c0,e.columns?.get(l)??null,e.buttons?.get(l))).join(""),o=t?E(e.sortState):"",i=I(e);return r||o?`<autoFilter ref="${i}">${r}${o}</autoFilter>`:`<autoFilter ref="${i}"/>`}function te(e){return`${e.autoFilter?Z(e.autoFilter):""}${E(e.sortState)}`}function ne(e){try{const t=new TextDecoder().decode(e),n=S(t,"autoFilter");if(!n)return null;const r=L(n.text);if(!r)return null;const o=S(t,"sortState",n.end);return o&&(r.sortState=A(o.text)),r}catch{return null}}function O(e,t){if(t.columns.size===0)return;const n=e.rows.hiddenSizes;if(n)for(const r of n.keys())r>t.r0&&r<=t.r1&&(e.filteredRows??=new Set,e.filteredRows.add(r))}function re(e,t){t&&(t.sortState&&(e.sortState=t.sortState),t.autoFilter&&(e.autoFilter=t.autoFilter,O(e,t.autoFilter)))}function oe(e,t){const n={r0:e.r0,c0:e.c0,r1:e.r1-e.totalsRows,c1:e.c1},r=e.fileFilter,o={...n,columns:r?.columns??new Map,buttons:r?.buttons??null,sortState:r?.sortState??null};return t&&O(t,o),o}function le(e){const t=o=>{let i=0;if(o)for(const l of o.values()){const a=l.indexOf('outlineLevel="');a>=0&&(i=Math.max(i,l.charCodeAt(a+14)-48))}return i},n=e.autoFilter??(e.advancedFilter?.inPlace?e.advancedFilter:null);let r=!1;if(n&&e.filteredRows){for(const o of e.filteredRows)if(o>n.r0&&o<=n.r1){r=!0;break}}return{filterMode:r,summaryBelow:e.summaryAbove!==!0,summaryRight:e.summaryLeft!==!0,applyStyles:e.outlineAutoStyles===!0,standardWidth:e.standardWidthChanged?e.cols.defaultSize:null,levelRow:t(e.rowExtras),levelCol:t(e.colExtras)}}function h(e,t,n){const r=new RegExp(`\\s${t}="[^"]*"`),o=e.replace(r,"");return n===null?o:o.replace(/\s*(\/?)>$/,` ${t}="${n}"$1>`)}function ie(e,t){if(!t)return e;let n=e;const r=/<sheetPr\b[^>]*?(\/?)>/.exec(n),o=t.filterMode||!t.summaryBelow||!t.summaryRight||t.applyStyles;if(r||o){let i=r?r[0]:"<sheetPr/>";i=h(i,"filterMode",t.filterMode?"1":null);let l="",a=n;if(r)if(r[1]==="/")a=n.slice(0,r.index)+n.slice(r.index+r[0].length);else{const m=n.indexOf("</sheetPr>",r.index);l=n.slice(r.index+r[0].length,m),a=n.slice(0,r.index)+n.slice(m+10)}const s=/<outlinePr\b[^>]*\/>/.exec(l);let u=s?s[0]:"<outlinePr/>";if(u=h(u,"summaryBelow",t.summaryBelow?null:"0"),u=h(u,"summaryRight",t.summaryRight?null:"0"),u=h(u,"applyStyles",t.applyStyles?"1":null),s&&(l=l.replace(s[0],"")),u!=="<outlinePr/>"){const m=l.indexOf("<pageSetUpPr");l=m>=0?`${l.slice(0,m)}${u}${l.slice(m)}`:`${l}${u}`}const f=r?r.index:(()=>{const m=/<worksheet\b[^>]*>/.exec(a);return m?m.index+m[0].length:0})(),d=/<sheetPr\b([^>]*?)\/?>/.exec(i)[1],c=l||d.trim()?l?`<sheetPr${d}>${l}</sheetPr>`:`<sheetPr${d}/>`:"";n=a.slice(0,f)+c+a.slice(f)}return n=n.replace(/<sheetFormatPr\b[^>]*\/>/,i=>{let l=h(i,"outlineLevelRow",t.levelRow>0?String(t.levelRow):null);return l=h(l,"outlineLevelCol",t.levelCol>0?String(t.levelCol):null),t.standardWidth&&(l=h(l,"defaultColWidth",String(Math.trunc(t.standardWidth/6*256)/256))),l}),n}function ae(e){const t=[];return e.forEach((n,r)=>{const o=n.autoFilter?null:n.advancedFilter,i=n.autoFilter??o;if(!i)return;const l=(a,s)=>`${j((a??n).name)}$${M(s.c0)}$${s.r0+1}:$${M(s.c1)}$${s.r1+1}`;t.push({localSheetId:r,text:l(o?.listSheet,i)}),o?.criteria&&t.push({name:"_xlnm.Criteria",localSheetId:r,text:l(o.criteriaSheet,o.criteria),visible:!0}),o?.extract&&t.push({name:"_xlnm.Extract",localSheetId:r,text:l(n,o.extract),visible:!0})}),t}function ue(e,t){const n=r=>{const o=/^(?:'((?:[^']|'')*)'|([^'!]+))!\$?([A-Z]+)\$?(\d+)(?::\$?([A-Z]+)\$?(\d+))?$/.exec(r??"");if(!o)return null;const i=a=>[...a].reduce((s,u)=>s*26+u.charCodeAt(0)-64,0)-1,l=e.sheets.find(a=>a.name===(o[1]?.replace(/''/g,"'")??o[2]));return l?{sheet:l,range:{r0:Number(o[4])-1,c0:i(o[3]),r1:Number(o[6]??o[4])-1,c1:i(o[5]??o[3])}}:null};e.sheets.forEach((r,o)=>{if(r.autoFilter)return;const i=(t??[]).filter(d=>d.localSheetId===o),l=n(i.find(d=>d.name==="_xlnm._FilterDatabase")?.text);if(!l)return;const a=n(i.find(d=>d.name==="_xlnm.Criteria")?.text),s=n(i.find(d=>d.name==="_xlnm.Extract")?.text),u=r.rows.hiddenSizes;let f=!1;if(l.sheet===r&&u)for(const d of u.keys())d>l.range.r0&&d<=l.range.r1&&((r.filteredRows??=new Set).add(d),f=!0);r.advancedFilter={...l.range,listSheet:l.sheet,criteria:a?.range??null,criteriaSheet:a?.sheet??null,extract:s?.range??null,unique:!1,inPlace:f}})}function M(e){let t="";for(let n=e+1;n>0;n=Math.floor((n-1)/26))t=String.fromCharCode(65+(n-1)%26)+t;return t}function se(e,t,n=[]){if(!t)return e;const r=/<definedName\b[^>]*name="_xlnm\._FilterDatabase"[^>]*>[\s\S]*?<\/definedName>/g,o=new Set(t.map(c=>c.localSheetId));let i=e.replace(r,c=>{const m=Number(/\blocalSheetId="(\d+)"/.exec(c)?.[1]??-1);return!o.has(m)&&n[m]?.sourceIndex===m?c:""});const l=new Set(t.filter(c=>c.name).map(c=>`${c.name}|${c.localSheetId}`));i=i.replace(/<definedName\b[^>]*name="(_xlnm\.(?:Criteria|Extract))"[^>]*>[\s\S]*?<\/definedName>/g,(c,m)=>{const _=/\blocalSheetId="(\d+)"/.exec(c)?.[1]??"-1";return l.has(`${m}|${_}`)?"":c});const a=t.map(c=>`<definedName name="${c.name??"_xlnm._FilterDatabase"}" localSheetId="${c.localSheetId}"${c.visible?"":' hidden="1"'}>${F(c.text)}</definedName>`).join(""),s=/<definedNames\b[^>]*>([\s\S]*?)<\/definedNames>/.exec(i);if(s){const c=a+s[1];return i.slice(0,s.index)+(c.trim()?`<definedNames>${c}</definedNames>`:"")+i.slice(s.index+s[0].length)}if(!a)return i;const u=/<\/sheets>/.exec(i);if(!u)return i;let f=u.index+u[0].length;const d=/<\/externalReferences>/.exec(i);return d&&(f=Math.max(f,d.index+d[0].length)),`${i.slice(0,f)}<definedNames>${a}</definedNames>${i.slice(f)}`}function ce(e,t){if(!e)return{color:null,auto:!0};if(t){const r=e.pf;if(r){if(r.none)return{color:null,none:!0};if(r.auto)return{color:null,auto:!0};if(r.fg)return{color:r.fg.toLowerCase()}}return e.fill?{color:e.fill.toLowerCase()}:{color:null,none:!0}}const n=e.pf;return n?.fg?{color:n.fg.toLowerCase()}:e.color?{color:e.color.toLowerCase()}:{color:null,auto:!0}}const R=e=>`FF${e.slice(1).toUpperCase()}`;function H(e,t,n=!1){return n&&!t?{color:e??void 0,pf:null,raw:`<dxf><font><color ${e===null?'auto="1"':`rgb="${R(e)}"`}/></font></dxf>`}:t?e===null?{pf:{none:!0},raw:'<dxf><fill><patternFill patternType="none"><fgColor indexed="64"/><bgColor indexed="65"/></patternFill></fill></dxf>'}:{pf:{fg:e},raw:`<dxf><fill><patternFill patternType="solid"><fgColor rgb="${R(e)}"/><bgColor rgb="FF000000"/></patternFill></fill></dxf>`}:e===null?{pf:{auto:!0},raw:'<dxf><fill><patternFill patternType="solid"><fgColor auto="1"/><bgColor indexed="65"/></patternFill></fill></dxf>'}:{pf:{fg:e},raw:`<dxf><fill><patternFill patternType="solid"><fgColor rgb="${R(e)}"/><bgColor rgb="FF000000"/></patternFill></fill></dxf>`}}function fe(e,t,n,r=!1){const o=H(t,n,r);e.dxfs??=[];const i=e.dxfs.findIndex(l=>l.raw===o.raw);return i>=0?i:(e.dxfs.push(o),e.dxfs.length-1)}export{Y as OPERATORS,ue as adoptAdvancedFilter,re as applySheetFilter,D as asSpec,Z as autoFilterXml,fe as colorDxfId,ce as dxfFilterColor,ae as filterNameEntries,H as makeColorDxf,L as parseAutoFilter,A as parseSortState,se as patchFilterNames,ie as patchSheetProps,ee as readSheetFilter,ne as readTableFilter,te as sheetFilterXml,le as sheetProps,E as sortStateXml,oe as tableFilterFromFile};
|
|
1
|
+
import{child as $,children as y,parseTree as V,unescapeOoxml as F}from"../io/xml-scan.js";import{escapeMarkup as S,xmlAttr as w}from"../io/xml-escape.js";import{parseRangeRef as C,rangeRef as I,sheetPrefix as j}from"../core/address.js";const q=new TextEncoder,p=e=>e==="1"||e==="true",b=e=>e==="0"||e==="false",x=e=>e===void 0||e===""?void 0:Number(e),Y=["equal","notEqual","greaterThan","greaterThanOrEqual","lessThan","lessThanOrEqual"];function D(e){if(e instanceof Set){const t=[];let n=!1;for(const r of e)r===""?n=!0:t.push(r);return{kind:"values",values:t,blank:n,dates:[]}}return e}function k(e){return{group:e.dateTimeGrouping??"year",y:x(e.year),m:x(e.month),d:x(e.day),h:x(e.hour),i:x(e.minute),s:x(e.second)}}const N=e=>e.slice(e.indexOf(":")+1);function P(e,t){for(const n of e.c){if(N(n.n)===t)return n;const r=P(n,t);if(r)return r}return null}function W(e,t){const n=$(e,"filters");if(n)return{kind:"values",values:y(n,"filter").map(s=>F(s.a.val??"")),blank:p(n.a.blank),dates:y(n,"dateGroupItem").map(s=>k(s.a)),calendarType:n.a.calendarType};const r=$(e,"customFilters");if(r)return{kind:"custom",and:p(r.a.and),rules:y(r,"customFilter").map(s=>({op:s.a.operator??"equal",val:F(s.a.val??"")}))};const o=$(e,"top10");if(o)return{kind:"top10",top:!b(o.a.top),percent:p(o.a.percent),val:Number(o.a.val??10),filterVal:x(o.a.filterVal)};const l=$(e,"dynamicFilter");if(l)return{kind:"dynamic",type:l.a.type??"null",val:x(l.a.val),maxVal:x(l.a.maxVal)};const i=$(e,"colorFilter");if(i)return{kind:"color",cell:!b(i.a.cellColor),dxfId:x(i.a.dxfId)};const a=$(e,"iconFilter");if(a)return{kind:"icon",iconSet:a.a.iconSet??"3Arrows",iconId:x(a.a.iconId)};const u=$(e,"extLst");if(u){const s=P(u,"filters");if(s)return{kind:"values",values:s.c.filter(f=>N(f.n)==="filter").map(f=>F(f.a.val??"")),blank:p(s.a.blank),dates:s.c.filter(f=>N(f.n)==="dateGroupItem").map(f=>k(f.a))}}return e.c.length>0?{kind:"raw",xml:t}:null}const g=(e,t,n=0)=>{const r=e.indexOf(`<${t}`,n);if(r<0)return null;const o=e.charCodeAt(r+t.length+1);if(o!==32&&o!==47&&o!==62&&o!==10&&o!==13&&o!==9)return g(e,t,r+1);const l=e.indexOf(">",r);if(l<0)return null;if(e[l-1]==="/")return{at:r,end:l+1,text:e.slice(r,l+1)};const i=e.indexOf(`</${t}>`,l);if(i<0)return null;const a=i+t.length+3;return{at:r,end:a,text:e.slice(r,a)}},G='xmlns:xr="x" xmlns:xr3="x" xmlns:x14="x" xmlns:xlrd2="x" xmlns:mc="x" xmlns:xm="x" xmlns:r="x" xmlns:x="x" xmlns:xr2="x" xmlns:xr6="x" xmlns:xr10="x"',T=e=>V(q.encode(`<root ${G}>${e}</root>`)).c[0];function B(e){const t=C(e.a.ref??"");return t?{...t,byColumns:p(e.a.columnSort),caseSensitive:p(e.a.caseSensitive),conditions:y(e,"sortCondition").map(n=>({...C(n.a.ref??"")??t,desc:p(n.a.descending),sortBy:n.a.sortBy??"value",customList:F(n.a.customList),dxfId:x(n.a.dxfId),iconSet:n.a.iconSet,iconId:x(n.a.iconId)}))}:null}function L(e){const t=T(e),n=C(t?.a.ref??"");if(!n)return null;const r=new Map;let o=null,l=0;for(const a of y(t,"filterColumn")){const u=g(e,"filterColumn",l);l=u?u.end:l;const s=n.c0+Number(a.a.colId??0),f=W(a,u?.text??"");f&&r.set(s,f),(p(a.a.hiddenButton)||b(a.a.showButton))&&(o??=new Map,o.set(s,{hidden:p(a.a.hiddenButton),noShow:b(a.a.showButton)}))}const i=$(t,"sortState");return{...n,columns:r,buttons:o,sortState:i?B(i):null,...t.a.uid?{uid:t.a.uid}:{}}}function A(e){const t=T(e);return t?B(t):null}function ee(e){const t={autoFilter:null,sortState:null};if(!e)return t;try{const n=g(e,"autoFilter");n&&(t.autoFilter=L(n.text));const r=n?n.end:0,o=g(e,"sortState",r),l=e.indexOf("<mergeCells");o&&(l<0||o.at<l)&&(t.sortState=A(o.text))}catch{}return t}function v(e){return String(e)}function X(e){const t=[];return e.y!==void 0&&t.push(`year="${e.y}"`),e.m!==void 0&&t.push(`month="${e.m}"`),e.d!==void 0&&t.push(`day="${e.d}"`),e.h!==void 0&&t.push(`hour="${e.h}"`),e.i!==void 0&&t.push(`minute="${e.i}"`),e.s!==void 0&&t.push(`second="${e.s}"`),t.push(`dateTimeGrouping="${e.group}"`),`<dateGroupItem ${t.join(" ")}/>`}function z(e){const t=D(e);switch(t.kind){case"values":{const n=t.values.map(o=>`<filter val="${w(o)}"/>`).join("")+(t.dates??[]).map(X).join(""),r=`${t.blank?' blank="1"':""}${t.calendarType?` calendarType="${S(t.calendarType)}"`:""}`;return n?`<filters${r}>${n}</filters>`:`<filters${r}/>`}case"custom":return`<customFilters${t.and?' and="1"':""}>${t.rules.map(n=>`<customFilter${n.op&&n.op!=="equal"?` operator="${n.op}"`:""} val="${w(n.val)}"/>`).join("")}</customFilters>`;case"top10":return`<top10${t.top?"":' top="0"'}${t.percent?' percent="1"':""} val="${v(t.val)}"${t.filterVal!==void 0?` filterVal="${v(t.filterVal)}"`:""}/>`;case"dynamic":return`<dynamicFilter type="${S(t.type)}"${t.val!==void 0?` val="${v(t.val)}"`:""}${t.maxVal!==void 0?` maxVal="${v(t.maxVal)}"`:""}/>`;case"color":return`<colorFilter${t.dxfId!==void 0?` dxfId="${t.dxfId}"`:""}${t.cell?"":' cellColor="0"'}/>`;case"icon":return`<iconFilter iconSet="${S(t.iconSet)}"${t.iconId!==void 0?` iconId="${t.iconId}"`:""}/>`;default:return""}}function U(e,t,n){if(t?.kind==="raw")return t.xml.replace(/\bcolId="\d+"/,`colId="${e}"`);const r=`${n?.hidden?' hiddenButton="1"':""}${n?.noShow?' showButton="0"':""}`,o=t?z(t):"";return o?`<filterColumn colId="${e}"${r}>${o}</filterColumn>`:`<filterColumn colId="${e}"${r}/>`}function E(e){if(!e||e.conditions.length===0)return"";const t=e.conditions.map(n=>{const r=[`ref="${I(n)}"`];return n.desc&&r.push('descending="1"'),n.sortBy&&n.sortBy!=="value"&&r.push(`sortBy="${n.sortBy}"`),n.customList&&r.push(`customList="${w(n.customList)}"`),n.dxfId!==void 0&&r.push(`dxfId="${n.dxfId}"`),n.iconSet&&r.push(`iconSet="${S(n.iconSet)}"`),n.iconId!==void 0&&r.push(`iconId="${n.iconId}"`),`<sortCondition ${r.join(" ")}/>`}).join("");return`<sortState ref="${I(e)}"${e.byColumns?' columnSort="1"':""}${e.caseSensitive?' caseSensitive="1"':""}>${t}</sortState>`}function Z(e,t=!0){const n=new Set(e.columns?.keys()??[]);if(e.buttons)for(const a of e.buttons.keys())n.add(a);const r=[...n].sort((a,u)=>a-u).map(a=>U(a-e.c0,e.columns?.get(a)??null,e.buttons?.get(a))).join(""),o=t?E(e.sortState):"",l=e.uid?` xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:xr="http://schemas.microsoft.com/office/spreadsheetml/2014/revision" mc:Ignorable="xr" xr:uid="${S(e.uid)}"`:"",i=`<autoFilter ref="${I(e)}"${l}`;return r||o?`${i}>${r}${o}</autoFilter>`:`${i}/>`}function te(e){return`${e.autoFilter?Z(e.autoFilter):""}${E(e.sortState)}`}function ne(e){try{const t=new TextDecoder().decode(e),n=g(t,"autoFilter");if(!n)return null;const r=L(n.text);if(!r)return null;const o=g(t,"sortState",n.end);return o&&(r.sortState=A(o.text)),r}catch{return null}}function O(e,t){if(t.columns.size===0)return;const n=e.rows.hiddenSizes;if(n)for(const r of n.keys())r>t.r0&&r<=t.r1&&(e.filteredRows??=new Set,e.filteredRows.add(r))}function re(e,t){t&&(t.sortState&&(e.sortState=t.sortState),t.autoFilter&&(e.autoFilter=t.autoFilter,O(e,t.autoFilter)))}function oe(e,t){const n={r0:e.r0,c0:e.c0,r1:e.r1-e.totalsRows,c1:e.c1},r=e.fileFilter,o={...n,columns:r?.columns??new Map,buttons:r?.buttons??null,sortState:r?.sortState??null};return t&&O(t,o),o}function le(e){const t=o=>{let l=0;if(o)for(const i of o.values()){const a=i.indexOf('outlineLevel="');a>=0&&(l=Math.max(l,i.charCodeAt(a+14)-48))}return l},n=e.autoFilter??(e.advancedFilter?.inPlace?e.advancedFilter:null);let r=!1;if(n&&e.filteredRows){for(const o of e.filteredRows)if(o>n.r0&&o<=n.r1){r=!0;break}}return{filterMode:r,summaryBelow:e.summaryAbove!==!0,summaryRight:e.summaryLeft!==!0,applyStyles:e.outlineAutoStyles===!0,standardWidth:e.standardWidthChanged?e.cols.defaultSize:null,levelRow:t(e.rowExtras),levelCol:t(e.colExtras)}}function h(e,t,n){const r=new RegExp(`\\s${t}="[^"]*"`),o=e.replace(r,"");return n===null?o:o.replace(/\s*(\/?)>$/,` ${t}="${n}"$1>`)}function ie(e,t){if(!t)return e;let n=e;const r=/<sheetPr\b[^>]*?(\/?)>/.exec(n),o=t.filterMode||!t.summaryBelow||!t.summaryRight||t.applyStyles;if(r||o){let l=r?r[0]:"<sheetPr/>";l=h(l,"filterMode",t.filterMode?"1":null);let i="",a=n;if(r)if(r[1]==="/")a=n.slice(0,r.index)+n.slice(r.index+r[0].length);else{const m=n.indexOf("</sheetPr>",r.index);i=n.slice(r.index+r[0].length,m),a=n.slice(0,r.index)+n.slice(m+10)}const u=/<outlinePr\b[^>]*\/>/.exec(i);let s=u?u[0]:"<outlinePr/>";if(s=h(s,"summaryBelow",t.summaryBelow?null:"0"),s=h(s,"summaryRight",t.summaryRight?null:"0"),s=h(s,"applyStyles",t.applyStyles?"1":null),u&&(i=i.replace(u[0],"")),s!=="<outlinePr/>"){const m=i.indexOf("<pageSetUpPr");i=m>=0?`${i.slice(0,m)}${s}${i.slice(m)}`:`${i}${s}`}const f=r?r.index:(()=>{const m=/<worksheet\b[^>]*>/.exec(a);return m?m.index+m[0].length:0})(),d=/<sheetPr\b([^>]*?)\/?>/.exec(l)[1],c=i||d.trim()?i?`<sheetPr${d}>${i}</sheetPr>`:`<sheetPr${d}/>`:"";n=a.slice(0,f)+c+a.slice(f)}return n=n.replace(/<sheetFormatPr\b[^>]*\/>/,l=>{let i=h(l,"outlineLevelRow",t.levelRow>0?String(t.levelRow):null);return i=h(i,"outlineLevelCol",t.levelCol>0?String(t.levelCol):null),t.standardWidth&&(i=h(i,"defaultColWidth",String(Math.trunc(t.standardWidth/6*256)/256))),i}),n}function ae(e){const t=[];return e.forEach((n,r)=>{const o=n.autoFilter?null:n.advancedFilter,l=n.autoFilter??o;if(!l)return;const i=(a,u)=>`${j((a??n).name)}$${M(u.c0)}$${u.r0+1}:$${M(u.c1)}$${u.r1+1}`;t.push({localSheetId:r,text:i(o?.listSheet,l)}),o?.criteria&&t.push({name:"_xlnm.Criteria",localSheetId:r,text:i(o.criteriaSheet,o.criteria),visible:!0}),o?.extract&&t.push({name:"_xlnm.Extract",localSheetId:r,text:i(n,o.extract),visible:!0})}),t}function se(e,t){const n=r=>{const o=/^(?:'((?:[^']|'')*)'|([^'!]+))!\$?([A-Z]+)\$?(\d+)(?::\$?([A-Z]+)\$?(\d+))?$/.exec(r??"");if(!o)return null;const l=a=>[...a].reduce((u,s)=>u*26+s.charCodeAt(0)-64,0)-1,i=e.sheets.find(a=>a.name===(o[1]?.replace(/''/g,"'")??o[2]));return i?{sheet:i,range:{r0:Number(o[4])-1,c0:l(o[3]),r1:Number(o[6]??o[4])-1,c1:l(o[5]??o[3])}}:null};e.sheets.forEach((r,o)=>{if(r.autoFilter)return;const l=(t??[]).filter(d=>d.localSheetId===o),i=n(l.find(d=>d.name==="_xlnm._FilterDatabase")?.text);if(!i)return;const a=n(l.find(d=>d.name==="_xlnm.Criteria")?.text),u=n(l.find(d=>d.name==="_xlnm.Extract")?.text),s=r.rows.hiddenSizes;let f=!1;if(i.sheet===r&&s)for(const d of s.keys())d>i.range.r0&&d<=i.range.r1&&((r.filteredRows??=new Set).add(d),f=!0);r.advancedFilter={...i.range,listSheet:i.sheet,criteria:a?.range??null,criteriaSheet:a?.sheet??null,extract:u?.range??null,unique:!1,inPlace:f}})}function M(e){let t="";for(let n=e+1;n>0;n=Math.floor((n-1)/26))t=String.fromCharCode(65+(n-1)%26)+t;return t}function ue(e,t,n=[]){if(!t)return e;const r=/<definedName\b[^>]*name="_xlnm\._FilterDatabase"[^>]*>[\s\S]*?<\/definedName>/g,o=new Set(t.map(c=>c.localSheetId));let l=e.replace(r,c=>{const m=Number(/\blocalSheetId="(\d+)"/.exec(c)?.[1]??-1);return!o.has(m)&&n[m]?.sourceIndex>=0?c:""});const i=new Set(t.filter(c=>c.name).map(c=>`${c.name}|${c.localSheetId}`));l=l.replace(/<definedName\b[^>]*name="(_xlnm\.(?:Criteria|Extract))"[^>]*>[\s\S]*?<\/definedName>/g,(c,m)=>{const _=/\blocalSheetId="(\d+)"/.exec(c)?.[1]??"-1";return i.has(`${m}|${_}`)?"":c});const a=t.map(c=>`<definedName name="${c.name??"_xlnm._FilterDatabase"}" localSheetId="${c.localSheetId}"${c.visible?"":' hidden="1"'}>${S(c.text)}</definedName>`).join(""),u=/<definedNames\b[^>]*>([\s\S]*?)<\/definedNames>/.exec(l);if(u){const c=a+u[1];return l.slice(0,u.index)+(c.trim()?`<definedNames>${c}</definedNames>`:"")+l.slice(u.index+u[0].length)}if(!a)return l;const s=/<\/sheets>/.exec(l);if(!s)return l;let f=s.index+s[0].length;const d=/<\/externalReferences>/.exec(l);return d&&(f=Math.max(f,d.index+d[0].length)),`${l.slice(0,f)}<definedNames>${a}</definedNames>${l.slice(f)}`}function ce(e,t){if(!e)return{color:null,auto:!0};if(t){const r=e.pf;if(r){if(r.none)return{color:null,none:!0};if(r.auto)return{color:null,auto:!0};if(r.fg)return{color:r.fg.toLowerCase()}}return e.fill?{color:e.fill.toLowerCase()}:{color:null,none:!0}}const n=e.pf;return n?.fg?{color:n.fg.toLowerCase()}:e.color?{color:e.color.toLowerCase()}:{color:null,auto:!0}}const R=e=>`FF${e.slice(1).toUpperCase()}`;function H(e,t,n=!1){return n&&!t?{color:e??void 0,pf:null,raw:`<dxf><font><color ${e===null?'auto="1"':`rgb="${R(e)}"`}/></font></dxf>`}:t?e===null?{pf:{none:!0},raw:'<dxf><fill><patternFill patternType="none"><fgColor indexed="64"/><bgColor indexed="65"/></patternFill></fill></dxf>'}:{pf:{fg:e},raw:`<dxf><fill><patternFill patternType="solid"><fgColor rgb="${R(e)}"/><bgColor rgb="FF000000"/></patternFill></fill></dxf>`}:e===null?{pf:{auto:!0},raw:'<dxf><fill><patternFill patternType="solid"><fgColor auto="1"/><bgColor indexed="65"/></patternFill></fill></dxf>'}:{pf:{fg:e},raw:`<dxf><fill><patternFill patternType="solid"><fgColor rgb="${R(e)}"/><bgColor rgb="FF000000"/></patternFill></fill></dxf>`}}function fe(e,t,n,r=!1){const o=H(t,n,r);e.dxfs??=[];const l=e.dxfs.findIndex(i=>i.raw===o.raw);return l>=0?l:(e.dxfs.push(o),e.dxfs.length-1)}export{Y as OPERATORS,se as adoptAdvancedFilter,re as applySheetFilter,D as asSpec,Z as autoFilterXml,fe as colorDxfId,z as columnBodyXml,ce as dxfFilterColor,ae as filterNameEntries,H as makeColorDxf,L as parseAutoFilter,W as parseColumnBody,A as parseSortState,ue as patchFilterNames,ie as patchSheetProps,ee as readSheetFilter,ne as readTableFilter,te as sheetFilterXml,le as sheetProps,E as sortStateXml,oe as tableFilterFromFile};
|
package/cells/find-engine.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{formulaEntryLimit as
|
|
2
|
-
`);return{...t,text:s}}function z(e,t,n){if(!e.comments)return[];const s=[];for(const[o
|
|
1
|
+
import{cellEditable as J}from"../core/protection.js";import{formulaEntryLimit as W}from"../calc/parser.js";import{CHUNK_BITS as M,CHUNK_MASK as I,EMPTY as D,FORMULA as T,KIND_MASK as G,SPILL as X,STR as Y}from"../core/sheet.js";const H=/[.+^${}()|[\]\\]/g;function P(e){if(!/[*?~]/.test(e))return null;let t="";for(let n=0;n<e.length;n++){const s=e[n];s==="~"&&n+1<e.length&&"*?~".includes(e[n+1])?t+=e[++n].replace(/[*?]/,"\\$&"):s==="*"?t+="[\\s\\S]*":s==="?"?t+="[\\s\\S]":t+=s.replace(H,"\\$&")}return t}const U=(e,t,n,s)=>new RegExp(n?`^(?:${e})$`:e,`${s}${n?"":"m"}u${t?"":"i"}`);function ft(e){try{return U(e,!0,!1,""),null}catch(t){return t.message}}function v(e,{matchCase:t=!1,whole:n=!1,regex:s=!1}={}){if(s){const r=U(e,t,n,"");return c=>r.test(c)}const i=P(e);if(i===null&&!n){if(t)return c=>c.includes(e);const r=e.toLowerCase();return c=>c.toLowerCase().includes(r)}if(i===null){if(t)return c=>c===e;const r=e.toLowerCase();return c=>c.toLowerCase()===r}const o=new RegExp(n?`^(?:${i})$`:i,t?"":"i");return r=>o.test(r)}function q(e,t,{matchCase:n=!1,whole:s=!1,regex:i=!1}={}){if(i){const c=U(e,n,s,"g");return f=>f.replace(c,t)}const o=P(e)??e.replace(H,"\\$&").replace(/[*?]/g,"\\$&"),r=new RegExp(s?`^(?:${o})$`:o,n?"g":"gi");return c=>c.replace(r,f=>f===""?"":t)}const Q=(e,t)=>e===t||e&&t&&typeof e=="object"&&JSON.stringify(e)===JSON.stringify(t);function V(e,t,n){const{styles:s,strings:i}=e,{what:o,look:r,format:c}=t,f=o===""?null:v(o,t),d=new Uint8Array(i.size+1),l=new Map,m=u=>{let h=l.get(u);if(h===void 0){const g=s.get(u);h=Object.keys(c).every(x=>Q(g[x]??null,c[x]??null)),l.set(u,h)}return h};return(u,h,g,x,a)=>{if(r==="values"&&(u.rows.isHidden(h)||u.cols.isHidden(g)||u.filteredRows?.has(h))||c!==null&&!m(u.style(h,g)))return!1;if(f===null)return!0;const y=x&G,S=u.protection&&x&T&&s.get(u.style(h,g)).hiddenFormula;if(r==="formulas"&&x&T&&!S)return f(e.editText(u,h,g));if(y===D)return!1;if(y===Y){if(a>=d.length)return f(i.get(a));let w=d[a];return w===0&&(w=f(i.get(a))?1:2,d[a]=w),w===1}const p=r==="formulas"&&!S?e.editText(u,h,g):n(y,a,s.get(u.style(h,g)));return f(p)}}const F=12,K=()=>new Promise(e=>setTimeout(e,0));class _{constructor(t){this.ctrl=t,this.start=performance.now()}async pause(){return performance.now()-this.start<F?!this.ctrl.cancelled:(this.ctrl.onProgress?.(),await K(),this.start=performance.now(),!this.ctrl.cancelled)}}const A=(e,t,n)=>e?n*1048576+t:t*16384+n;function Z(e){const t=[];for(let n=0;n<=e.maxCol;n++)e.columns[n]!==void 0&&t.push(n);return t}async function j(e,{byCols:t,dir:n,from:s,to:i,withEmpty:o},r,c){const f=Z(e);n<0&&f.reverse();const d=s===null?-n*(1/0):s,l=i===null?n*(1/0):i,m=n>0?a=>a>=d&&a<=l:a=>a<=d&&a>=l,u=o===!0;if(t){for(const a of f){const y=e.columns[a],S=n>0?0:y.length-1,p=n>0?y.length:-1;for(let w=S;w!==p;w+=n){const L=y[w];if(L===void 0)continue;const $=w<<M,{kinds:R,values:E,styles:O}=L;for(let k=n>0?0:I;k>=0&&k<=I;k+=n){const C=R[k];if(C===0&&!(u&&O!==null&&O[k]!==0))continue;const N=$+k;if(m(A(!0,N,a))&&r(N,a,C,E[k]))return!0}if(!await c.pause())return!1}}return!1}const h=e.maxRow>>>M,g=n>0?0:h,x=n>0?h+1:-1;for(let a=g;a!==x;a+=n){const y=[];for(const p of f){const w=e.columns[p][a];w!==void 0&&y.push(p,w)}if(y.length===0)continue;const S=a<<M;for(let p=n>0?0:I;p>=0&&p<=I;p+=n){const w=S+p;for(let L=0;L<y.length;L+=2){const $=y[L+1],R=$.kinds[p];if(R===0&&!(u&&$.styles!==null&&$.styles[p]!==0))continue;const E=y[L];if(m(A(!1,w,E))&&r(w,E,R,$.values[p]))return!0}}if(!await c.pause())return!1}return!1}function b(e,t){if(!t.author?.startsWith("tc="))return t;const n=t.author.slice(3),s=(e.threads??[]).filter(i=>i.id===n||i.parentId===n).map(i=>i.text).join(`
|
|
2
|
+
`);return{...t,text:s}}function z(e,t,n){if(!e.comments)return[];const s=[];for(const[i,o]of e.comments){const r=Math.floor(i/16384);s.push({row:r,col:i-r*16384,note:b(e,o)})}return s.sort((i,o)=>n*(A(t,i.row,i.col)-A(t,o.row,o.col))),s}function tt(e,t,n){const s=e.sheets.filter(r=>!r.hidden);if(t.within!=="workbook")return[e.sheet];const i=s.indexOf(e.sheet),o=[];for(let r=0;r<s.length;r++)o.push(s[(i+n*r+s.length*2)%s.length]);return o}const et=(e,t,n)=>e.some(s=>t>=s.r0&&t<=s.r1&&n>=s.c0&&n<=s.c1);function B(e,t,n){const s=V(e,t,n);if(!t.ranges)return s;const i=t.sheet??e.sheet;return(o,r,c,f,d)=>(o!==i||et(t.ranges,r,c))&&s(o,r,c,f,d)}async function at(e,t,n,s,i,o={}){const r=t.byColumns===!0,c=new _(o),f=tt(e,t,s),d=A(r,n.row,n.col);if(t.look==="notes")return nt(e,t,f,d,r,s);const l=B(e,t,i),m=t.what===""&&t.format!==null;let u=null;const h=async(g,x,a,y)=>(await j(g,{byCols:r,dir:s,from:x,to:a,withEmpty:m},(S,p,w,L)=>y&&A(r,S,p)===d||!l(g,S,p,w,L)?!1:(u={sheet:g,row:S,col:p},!0),c),u!==null||o.cancelled===!0);if(await h(f[0],d,null,!0))return u;for(let g=1;g<f.length;g++)if(await h(f[g],null,null,!1))return u;return await h(f[0],null,d,!1),u}function nt(e,t,n,s,i,o){const r=v(t.what,t),c=l=>r(l.note.text??""),f=z(n[0],i,o),d=o>0?l=>l>s:l=>l<s;for(const l of f)if(d(A(i,l.row,l.col))&&c(l))return{sheet:n[0],row:l.row,col:l.col};for(let l=1;l<n.length;l++)for(const m of z(n[l],i,o))if(c(m))return{sheet:n[l],row:m.row,col:m.col};for(const l of f)if(!d(A(i,l.row,l.col))&&c(l))return{sheet:n[0],row:l.row,col:l.col};return null}class st{constructor(t){this.cap=t,this.count=0,this.overflow=!1,this.size=Math.min(t,1024),this.rows=new Uint32Array(this.size),this.cols=new Uint16Array(this.size),this.sheets=new Uint16Array(this.size),this.sheetList=[]}push(t,n,s){if(this.count===this.cap)return this.overflow=!0,!1;if(this.count===this.size){this.size=Math.min(this.cap,this.size*2);const r=(c,f)=>{const d=new c(this.size);return d.set(f),d};this.rows=r(Uint32Array,this.rows),this.cols=r(Uint16Array,this.cols),this.sheets=r(Uint16Array,this.sheets)}let i=this.sheetList.indexOf(t);i<0&&(i=this.sheetList.length,this.sheetList.push(t));const o=this.count++;return this.rows[o]=n,this.cols[o]=s,this.sheets[o]=i,!0}}async function rt(e,t,n,s={},i=1e5){const o=new st(i),r=t.byColumns===!0,c=new _(s),f=t.sheet?[t.sheet]:t.within==="workbook"?e.sheets.filter(m=>!m.hidden):[e.sheet];if(t.look==="notes"){const m=v(t.what,t);for(const u of f)for(const h of z(u,r,1))m(h.note.text??"")&&o.push(u,h.row,h.col);return o}const d=B(e,t,n),l=t.what===""&&t.format!==null;for(const m of f)if(await j(m,{byCols:r,dir:1,from:null,to:null,withEmpty:l},(h,g,x,a)=>d(m,h,g,x,a)?!o.push(m,h,g):!1,c)||s.cancelled)break;return o}function it(e,t,n,s,i,o,r=null){const{sheet:c}=t;let f=!1;if(i!==null){const d=c.formula(n,s);if(d&&d.t==="array")return!1;const l=c.kind(n,s);if(l&X&&!(l&T))return!1;const m=e.editText(c,n,s),u=i(m);if(u!==m&&u.startsWith("=")&&u.length>1&&!ot(e,u.slice(1)))return r!==null&&r.invalid++,!1;u!==m&&(e.setInput(t,n,s,u),f=!0)}return o&&(f||t.saveCell(n,s),c.setStyle(n,s,e.styles.derive(c.style(n,s),o)),f=!0),f}async function ht(e,t,n,s,i,o={}){const r=await rt(e,{...t,look:"formulas"},i,o,4294967295);if(o.cancelled)return{count:0,sheets:0,cancelled:!0};const c=t.what===""?null:q(t.what,n??"",t);let f=0,d=0;const l={locked:0,invalid:0},m=[];for(let u=0;u<r.sheetList.length;u++){const h=r.sheetList[u],g=[];let x=0,a=0;for(;a<r.count;){const y=performance.now(),S=e.runSlice(h,"replace",p=>{for(let w=0;a<r.count&&!(w%1024===1023&&performance.now()-y>F);a++,w++){if(r.sheets[a]!==u)continue;const L=r.rows[a],$=r.cols[a];if(h.protection&&!J(e,h,L,$)){l.locked++;continue}it(e,p,L,$,c,s,l)&&x++}});if(S!==null&&g.push(S),o.onProgress?.(),a<r.count&&await K(),o.cancelled)return e.rollbackSlices([...m,...g]),{count:0,sheets:0,cancelled:!0}}m.push(...g),x>0&&(f+=x,d++)}return e.pushFolded(m,"replace",e.sheet),{count:f,sheets:d,...l}}function ot(e,t){if(!e.engine)return!W(t);try{return e.engine.validate(t),!0}catch{return!1}}export{st as FoundList,rt as findAll,at as findNext,v as makeMatcher,q as makeReplacer,V as makeTest,ft as regexProblem,ht as replaceAll,it as replaceInCell};
|
package/cells/find.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{overlayRoot as S}from"../api/overlay.js";import{el as l,openFormatCells as T}from"../ui/dialogs.js";import{cellRef as _,MAX_COLS as L,MAX_ROWS as B}from"../core/address.js";import{KIND_MASK as E}from"../core/sheet.js";import{formatCount as g}from"../core/numfmt.js";import{findAll as $,findNext as b,makeReplacer as W,makeTest as O,replaceAll as N,replaceInCell as H}from"./find-engine.js";import{ensureBookCss as D}from"./book-css.js";import{svgNode as P}from"./format-tabs.js";import{t as a,tc as F}from"../i18n/index.js";const m=20,j=["fontName","fontSize","bold","italic","underline","strike","color","fill","pattern","borders","numFmt","hAlign","vAlign","wrap","indent","rotation","shrink","unlocked","hiddenFormula"];let p=null,v=null;const w=[];function R(c){const t=l("span",{class:"bk-fmt-chip",textContent:c?a("Preview*"):a("No Format Set")});return y(t,c),t}function y(c,t){c.textContent=t?a("Preview*"):a("No Format Set"),c.style.background=t?.fill??"",c.style.color=t?.color??"",c.style.fontWeight=t?.bold?"700":"",c.style.fontStyle=t?.italic?"italic":"",c.style.textDecoration=t?.underline?"underline":""}function I(c){const t={};for(const e of j)c[e]!==void 0&&c[e]!==null&&c[e]!==!1&&c[e]!==0&&c[e]!=="General"&&(t[e]=c[e]);return t}class V{constructor(t){this.app=t,this.findFormat=null,this.replaceFormat=null,this.ctrl=null,this.results=null,this.order=null,this.activeRow=-1,this.sort={key:null,dir:1},this._build()}_build(){D();const t=(i,d)=>{const u=l("select",{class:"dlg-input","aria-label":a(i)});for(const[f,k]of d)u.append(l("option",{value:k,textContent:a(f)}));return u},e=(i,d,u=!1)=>l("button",{class:`dlg-btn${u?" primary":""}`,type:"button",textContent:a(i),on:{click:d}}),s=l("button",{type:"button",class:"bk-find-history",title:a("Recent searches"),"aria-label":a("Recent searches"),on:{click:i=>this.app.ribbon.openMenu(i.currentTarget,{items:w.length?w.map(d=>[d,()=>{this.what.value=d,this.what.focus()},{raw:!0}]):[["No recent searches",()=>{}]]})}},P('<svg width="9" height="6" viewBox="0 0 9 6" fill="none" stroke="currentColor" stroke-width="1.3" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M1 1l3.5 3.5L8 1"/></svg>'));this.what=l("input",{class:"dlg-input","aria-label":a("Find what"),spellcheck:!1}),this.repl=l("input",{class:"dlg-input","aria-label":a("Replace with"),spellcheck:!1}),this.within=t("Within",[["Sheet","sheet"],["Workbook","workbook"]]),this.searchBy=t("Search",[["By Rows","rows"],["By Columns","cols"]]),this.look=t("Look in",[["Formulas","formulas"],["Values","values"],["Notes","notes"]]),this.matchCase=l("input",{type:"checkbox","aria-label":a("Match case")}),this.whole=l("input",{type:"checkbox","aria-label":a("Match entire cell contents")}),this.status=l("div",{class:"dlg-status",role:"status"}),this.progress=l("div",{class:"bk-progress",hidden:!0},l("div")),this.findChip=R(null),this.replaceChip=R(null);const o=i=>e("Format…",d=>this._formatMenu(i,d.currentTarget)),r=(...i)=>l("span",{class:"dlg-row bk-find-fmt",hidden:!0},...i);this.fmtFind=r(this.findChip,o("find")),this.fmtReplace=r(this.replaceChip,o("replace")),this.replaceRow=[l("span",{textContent:a("Replace with:")}),l("div",{class:"dlg-row"},this.repl,this.fmtReplace)],this.modeFind=l("button",{type:"button",role:"tab",class:"dlg-tab",textContent:a("Find"),on:{click:()=>this.setMode(!1)}}),this.modeReplace=l("button",{type:"button",role:"tab",class:"dlg-tab",textContent:a("Replace"),on:{click:()=>this.setMode(!0)}}),this.opts=l("div",{class:"bk-find-opts",hidden:!0},l("span",{textContent:a("Within:")}),this.within,l("label",{class:"dlg-row dlg-check"},this.matchCase,` ${a("Match case")}`),l("span",{textContent:a("Search:")}),this.searchBy,l("label",{class:"dlg-row dlg-check"},this.whole,` ${a("Match entire cell contents")}`),l("span",{textContent:a("Look in:")}),this.look,l("span")),this.btnReplaceAll=e("Replace All",()=>this.doReplaceAll()),this.btnReplace=e("Replace",()=>this.doReplace()),this.resultsHost=l("div",{class:"bk-results",hidden:!0});const n=l("h2",{class:"bk-panel-title",textContent:a("Find & Replace")});this.node=l("div",{class:"bk-panel xl-dlg",role:"dialog","aria-label":a("Find & Replace")},n,l("div",{class:"xl-tabbed"},l("div",{class:"dlg-tabs",role:"tablist"},this.modeFind,this.modeReplace),l("div",{class:"xl-box bk-find-box"},l("div",{class:"bk-find-grid"},l("span",{textContent:a("Find what:")}),l("div",{class:"dlg-row"},l("span",{class:"bk-find-field"},this.what,s),this.fmtFind),...this.replaceRow),this.opts,this.progress,this.resultsHost,l("div",{class:"bk-find-low"},this.status,e("Options",()=>this.toggleOptions())))),l("div",{class:"bk-find-foot"},this.btnReplaceAll,this.btnReplace,e("Find All",()=>this.doFindAll()),e(F("find","Previous"),()=>this.doFind(-1)),e(F("find","Next"),()=>this.doFind(1),!0),e("Close",()=>this.close()))),this.node.addEventListener("keydown",i=>{i.stopPropagation(),i.key==="Escape"?(i.preventDefault(),this.ctrl?this.cancel():this.close()):i.key==="Enter"&&i.target.tagName!=="BUTTON"&&(i.preventDefault(),this.doFind(i.shiftKey?-1:1))}),n.addEventListener("pointerdown",i=>{i.preventDefault(),n.setPointerCapture(i.pointerId);const d=this.node.getBoundingClientRect(),u=i.clientX-d.left,f=i.clientY-d.top,k=x=>{this.node.style.left=`${Math.max(0,Math.min(window.innerWidth-80,x.clientX-u))}px`,this.node.style.top=`${Math.max(0,Math.min(window.innerHeight-40,x.clientY-f))}px`},C=()=>{n.removeEventListener("pointermove",k),n.removeEventListener("pointerup",C)};n.addEventListener("pointermove",k),n.addEventListener("pointerup",C)}),this.node.style.right="24px",this.node.style.top="120px",S().append(this.node);const h=this.node.getBoundingClientRect();this.node.style.left=`${h.left}px`,this.node.style.right="auto"}toggleOptions(){const t=this.opts.hidden||!!(this.findFormat||this.replaceFormat);this.opts.hidden=!t,this.fmtFind.hidden=!t,this.fmtReplace.hidden=!t}setMode(t){this.withReplace=t,this.modeFind.setAttribute("aria-selected",String(!t)),this.modeReplace.setAttribute("aria-selected",String(t));for(const e of this.replaceRow)e.hidden=!t;this.btnReplaceAll.hidden=!t,this.btnReplace.hidden=!t,t&&(this.look.value="formulas"),this.look.querySelector('option[value="values"]').disabled=t,this.look.querySelector('option[value="notes"]').disabled=t}focus(){this.what.focus(),this.what.select()}close(){this.cancel(),(this.what.value!==""||this.findFormat)&&(v=this._options(!1)),this.node.remove(),p=null,this.app.controller.pickCell=null,this.app.controller.focusGrid()}cancel(){this.ctrl&&(this.ctrl.cancelled=!0)}_formatMenu(t,e){const{app:s}=this,o=r=>{t==="find"?(this.findFormat=r,y(this.findChip,r)):(this.replaceFormat=r,y(this.replaceChip,r))};s.ribbon.openMenu(e,{items:[["Format…",()=>T(s,"Number",{onPick:r=>o(Object.keys(r).length?r:null)})],["Choose Format from Cell…",()=>{this.status.textContent=a("Click the cell whose format you want."),s.controller.pickCell=(r,n)=>{const{book:h}=s;o(I(h.styles.get(h.sheet.style(r,n)))),this.status.textContent=""}}],["Clear Format",()=>o(null)]]})}_options(t=!0){const{app:e}=this,s=e.grid.selection,o=s.ranges.length===1&&s.ranges[0].r0===s.ranges[0].r1&&s.ranges[0].c0===s.ranges[0].c1,r=e.book.sheet.mergeAt(s.row,s.col),n=o||r&&s.ranges.length===1;return{what:this.what.value,matchCase:this.matchCase.checked,whole:this.whole.checked,look:this.look.value,format:this.findFormat,byColumns:this.searchBy.value==="cols",within:this.within.value,ranges:t&&!n?s.ranges:null}}_display(){const{grid:t}=this.app;return(e,s,o)=>t.displayText(e,s,o)}_ready(t){if(t.what===""&&t.format===null)return this.status.textContent=a("Enter what to find, or choose a format."),this.what.focus(),!1;if(t.what!==""){const e=w.indexOf(t.what);e>=0&&w.splice(e,1),w.unshift(t.what),w.length=Math.min(w.length,12)}return!0}_begin(){this.cancel();const t={cancelled:!1};this.ctrl=t;const e=this.progress,s=performance.now();return t.onProgress=()=>{if(performance.now()-s>150){e.hidden=!1;const o=e.firstChild;o.style.width=`${((performance.now()-s)/40%100).toFixed(0)}%`,this.status.textContent=a("Searching… Press Esc to stop.")}},t}_end(t){this.ctrl===t&&(this.ctrl=null),this.progress.hidden=!0}_jump(t){const{app:e}=this,{book:s}=e;t.sheet!==s.sheet&&(s.selectedSheets&&!s.selectedSheets.has(t.sheet)&&(s.selectedSheets=null),e.switchSheet(s.sheets.indexOf(t.sheet)));const o=e.grid.selection;o.ranges.some(n=>(n.r0!==n.r1||n.c0!==n.c1)&&t.row>=n.r0&&t.row<=n.r1&&t.col>=n.c0&&t.col<=n.c1)?(e.grid.setSelection({ranges:o.ranges,row:t.row,col:t.col}),e.grid.ensureVisible(t.row,t.col)):e.controller.moveTo(t.row,t.col)}async doFind(t){const e=this._options();if(!this._ready(e))return null;const s=this._begin(),o=performance.now(),r=this.app.grid.selection,n=await b(this.app.book,e,{row:r.row,col:r.col},t,this._display(),s);return this._end(s),s.cancelled?(this.status.textContent=a("Stopped."),null):(this.lastMs=performance.now()-o,n?(this._jump(n),this.status.textContent=`${n.sheet===this.app.book.sheet?"":`${n.sheet.name}!`}${_(n.row,n.col)}`,n):(this.status.textContent=a("We couldn't find what you were looking for."),null))}async doFindAll(){const t=this._options();if(!this._ready(t))return;const e=this._begin(),s=performance.now(),o=await $(this.app.book,t,this._display(),e);if(this._end(e),e.cancelled){this.status.textContent=a("Stopped.");return}this.lastMs=performance.now()-s,this.results=o,this.order=new Uint32Array(o.count);for(let n=0;n<o.count;n++)this.order[n]=n;this.sort={key:null,dir:1},this.activeRow=-1;const r=g(o.count);this.status.textContent=o.overflow?a("The first {shown} cells found. There are more.",{shown:r}):a("{shown} cells found.",{count:o.count,shown:r}),this._renderResults()}_cellValue(t){const{book:e,grid:s}=this.app,{results:o}=this,r=o.sheetList[o.sheets[t]],n=o.rows[t],h=o.cols[t];if(this.look.value==="notes")return r.comments?.get(n*L+h)?.text??"";const i=r.kind(n,h)&E;return s.displayText(i,r.value(n,h),e.styles.get(r.style(n,h))).replace(/\u0001.?\u0001/g," ")}_cellFormula(t){const{book:e}=this.app,{results:s}=this,o=e.editText(s.sheetList[s.sheets[t]],s.rows[t],s.cols[t]);return o[0]==="="||o.startsWith("{=")?o:""}_sortBy(t){const{results:e}=this;if(!e)return;const s=this.sort.key===t?-this.sort.dir:1;this.sort={key:t,dir:s};const o={sheet:i=>e.sheetList[e.sheets[i]].name,cell:i=>e.cols[i]*B+e.rows[i],value:i=>this._cellValue(i),formula:i=>this._cellFormula(i)}[t],r=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"}),n=new Array(e.count);for(let i=0;i<e.count;i++)n[i]=o(i);const h=Array.from(this.order);h.sort((i,d)=>s*(typeof n[i]=="number"?n[i]-n[d]:r.compare(n[i],n[d]))),this.order=Uint32Array.from(h),this._renderResults()}_renderResults(){const{results:t}=this,e=(h,i)=>l("button",{type:"button",textContent:`${a(h)}${this.sort.key===i?this.sort.dir>0?" ▴":" ▾":""}`,on:{click:()=>this._sortBy(i)}}),s=l("div",{class:"bk-results-body",tabIndex:0}),o=l("div",{style:`height:${t.count*m}px`}),r=l("div");s.append(o,r);const n=()=>{const h=Math.floor(s.scrollTop/m),i=Math.min(t.count,h+Math.ceil(s.clientHeight/m)+2),d=[];for(let u=h;u<i;u++){const f=this.order[u],k=l("div",{class:`bk-results-row${u===this.activeRow?" active":""}`,style:`top:${u*m}px`,on:{click:()=>this._pick(u)}},l("span",{textContent:t.sheetList[t.sheets[f]].name}),l("span",{textContent:_(t.rows[f],t.cols[f])}),l("span",{textContent:this._cellValue(f)}),l("span",{textContent:this._cellFormula(f)}));d.push(k)}r.replaceChildren(...d)};this.drawResults=n,s.addEventListener("scroll",n,{passive:!0}),s.addEventListener("keydown",h=>{h.key!=="ArrowDown"&&h.key!=="ArrowUp"||(h.preventDefault(),this._pick(Math.max(0,Math.min(t.count-1,this.activeRow+(h.key==="ArrowDown"?1:-1)))))}),this.resultsHost.replaceChildren(l("div",{class:"bk-results-head"},e("Sheet","sheet"),e("Cell","cell"),e("Value","value"),e("Formula","formula")),s),this.resultsHost.hidden=t.count===0,n(),this.resultsBody=s}_pick(t){const{results:e}=this,s=this.order[t];this.activeRow=t,this._jump({sheet:e.sheetList[e.sheets[s]],row:e.rows[s],col:e.cols[s]});const o=this.resultsBody;t*m<o.scrollTop?o.scrollTop=t*m:(t+1)*m>o.scrollTop+o.clientHeight&&(o.scrollTop=(t+1)*m-o.clientHeight),this.drawResults()}async doReplace(){const t=this._options(!1);if(!this._ready(t))return;const{app:e}=this,{book:s}=e,{sheet:o}=s,{row:r,col:n}=e.grid.selection;if(await b(s,{...t,within:"sheet",look:"formulas"},{row:r,col:n},1,this._display(),{})!==null&&this._matchesHere(t,r,n))if(o.protection&&s.styles.get(o.style(r,n)).unlocked!==!0)this.status.textContent=a("This cell is locked.");else{const d=t.what===""?null:W(t.what,this.repl.value,t),u={invalid:0};if(s.transact("replace",f=>{H(s,f,r,n,d,this.replaceFormat,u)}),e.grid.invalidate(),u.invalid>0){this.status.textContent=a("There's a problem with this formula after the replacement, so the cell was left as it was.");return}}await this.doFind(1)}_matchesHere(t,e,s){const{book:o}=this.app,{sheet:r}=o;return O(o,{...t,look:"formulas"},this._display())(r,e,s,r.kind(e,s),r.value(e,s))}async doReplaceAll(){const t=this._options();if(!this._ready(t))return;const e=this._begin(),s=performance.now(),o=await N(this.app.book,t,this.repl.value,this.replaceFormat,this._display(),e);if(this._end(e),this.lastMs=performance.now()-s,o.cancelled){this.status.textContent=a("Stopped; nothing was replaced.");return}const r={count:o.count,shown:g(o.count),sheets:o.sheets},n=[o.count===0&&o.locked===0&&o.invalid===0?a("We couldn't find anything to replace."):o.sheets>1?a("All done. We made {shown} replacements on {sheets} sheets.",r):a("All done. We made {shown} replacements.",r)];o.locked>0&&n.push(a("{shown} locked cells on protected sheets were left as they were.",{count:o.locked,shown:g(o.locked)})),o.invalid>0&&n.push(a("{shown} cells were left as they were, as the replacement would break their formulas.",{count:o.invalid,shown:g(o.invalid)})),this.status.textContent=n.join(" "),this.app.grid.invalidate(),this.app.afterCommand(),this.what.focus()}}function tt(c,t){if(!p&&v){const e=c.grid.selection;return b(c.book,v,{row:e.row,col:e.col},t,(s,o,r)=>c.grid.displayText(s,o,r),{}).then(s=>s?(s.sheet&&s.sheet!==c.book.sheet&&c.switchSheet(c.book.sheets.indexOf(s.sheet)),c.controller.moveTo(s.row,s.col),s):(c.shell?.setStatus(a("We couldn't find what you were looking for.")),null))}return p?(M(c),p.doFind(t)):(U(c),null)}const A=new WeakSet;function M(c){p.app=c,!A.has(c)&&(A.add(c),c.signal?.addEventListener("abort",()=>{p?.app===c&&(p.cancel(),p.node.remove(),p=null)},{once:!0}))}function U(c,t=!1){p??=new V(c),M(c),p.setMode(t),p.focus();const e=p;return setTimeout(()=>{p===e&&document.activeElement!==e.what&&!e.node.contains(document.activeElement)&&e.focus()},0),p}export{tt as findAgain,U as openFind};
|
|
1
|
+
import{cellEditable as T}from"../core/protection.js";import{overlayRoot as L}from"../api/overlay.js";import{el as l,openFormatCells as B}from"../ui/dialogs.js";import{cellRef as _,MAX_COLS as E,MAX_ROWS as $}from"../core/address.js";import{KIND_MASK as W}from"../core/sheet.js";import{formatCount as k}from"../core/numfmt.js";import{findAll as O,findNext as v,makeReplacer as N,makeTest as H,regexProblem as F,replaceAll as P,replaceInCell as D}from"./find-engine.js";import{ensureBookCss as j}from"./book-css.js";import{svgNode as I}from"./format-tabs.js";import{t as r,tc as R}from"../i18n/index.js";const m=20,V=["fontName","fontSize","bold","italic","underline","strike","color","fill","pattern","borders","numFmt","hAlign","vAlign","wrap","indent","rotation","shrink","unlocked","hiddenFormula"];let p=null,b=null;const w=[];function M(c){const t=l("span",{class:"bk-fmt-chip",textContent:c?r("Preview*"):r("No Format Set")});return y(t,c),t}function y(c,t){c.textContent=t?r("Preview*"):r("No Format Set"),c.style.background=t?.fill??"",c.style.color=t?.color??"",c.style.fontWeight=t?.bold?"700":"",c.style.fontStyle=t?.italic?"italic":"",c.style.textDecoration=t?.underline?"underline":""}function U(c){const t={};for(const e of V)c[e]!==void 0&&c[e]!==null&&c[e]!==!1&&c[e]!==0&&c[e]!=="General"&&(t[e]=c[e]);return t}class X{constructor(t){this.app=t,this.findFormat=null,this.replaceFormat=null,this.ctrl=null,this.results=null,this.order=null,this.activeRow=-1,this.sort={key:null,dir:1},this._build()}_build(){j();const t=(i,d)=>{const u=l("select",{class:"dlg-input","aria-label":r(i)});for(const[f,g]of d)u.append(l("option",{value:g,textContent:r(f)}));return u},e=(i,d,u=!1)=>l("button",{class:`dlg-btn${u?" primary":""}`,type:"button",textContent:r(i),on:{click:d}}),o=l("button",{type:"button",class:"bk-find-history",title:r("Recent searches"),"aria-label":r("Recent searches"),on:{click:i=>this.app.ribbon.openMenu(i.currentTarget,{items:w.length?w.map(d=>[d,()=>{this.what.value=d,this.what.focus()},{raw:!0}]):[["No recent searches",()=>{}]]})}},I('<svg width="9" height="6" viewBox="0 0 9 6" fill="none" stroke="currentColor" stroke-width="1.3" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M1 1l3.5 3.5L8 1"/></svg>'));this.what=l("input",{class:"dlg-input","aria-label":r("Find what"),spellcheck:!1}),this.repl=l("input",{class:"dlg-input","aria-label":r("Replace with"),spellcheck:!1}),this.within=t("Within",[["Sheet","sheet"],["Workbook","workbook"]]),this.searchBy=t("Search",[["By Rows","rows"],["By Columns","cols"]]),this.look=t("Look in",[["Formulas","formulas"],["Values","values"],["Notes","notes"]]),this.matchCase=l("input",{type:"checkbox","aria-label":r("Match case")}),this.whole=l("input",{type:"checkbox","aria-label":r("Match entire cell contents")}),this.regex=l("input",{type:"checkbox","aria-label":r("Match using regular expressions")}),this.status=l("div",{class:"dlg-status",role:"status"}),this.progress=l("div",{class:"bk-progress",hidden:!0},l("div")),this.findChip=M(null),this.replaceChip=M(null);const s=i=>e("Format…",d=>this._formatMenu(i,d.currentTarget)),a=(...i)=>l("span",{class:"dlg-row bk-find-fmt",hidden:!0},...i);this.fmtFind=a(this.findChip,s("find")),this.fmtReplace=a(this.replaceChip,s("replace")),this.replaceRow=[l("span",{textContent:r("Replace with:")}),l("div",{class:"dlg-row"},this.repl,this.fmtReplace)],this.modeFind=l("button",{type:"button",role:"tab",class:"dlg-tab",textContent:r("Find"),on:{click:()=>this.setMode(!1)}}),this.modeReplace=l("button",{type:"button",role:"tab",class:"dlg-tab",textContent:r("Replace"),on:{click:()=>this.setMode(!0)}}),this.opts=l("div",{class:"bk-find-opts",hidden:!0},l("span",{textContent:r("Within:")}),this.within,l("label",{class:"dlg-row dlg-check"},this.matchCase,` ${r("Match case")}`),l("span",{textContent:r("Search:")}),this.searchBy,l("label",{class:"dlg-row dlg-check"},this.whole,` ${r("Match entire cell contents")}`),l("span",{textContent:r("Look in:")}),this.look,l("label",{class:"dlg-row dlg-check"},this.regex,` ${r("Match using regular expressions")}`)),this.btnReplaceAll=e("Replace All",()=>this.doReplaceAll()),this.btnReplace=e("Replace",()=>this.doReplace()),this.resultsHost=l("div",{class:"bk-results",hidden:!0});const n=l("h2",{class:"bk-panel-title",textContent:r("Find & Replace")});this.node=l("div",{class:"bk-panel xl-dlg",role:"dialog","aria-label":r("Find & Replace")},n,l("div",{class:"xl-tabbed"},l("div",{class:"dlg-tabs",role:"tablist"},this.modeFind,this.modeReplace),l("div",{class:"xl-box bk-find-box"},l("div",{class:"bk-find-grid"},l("span",{textContent:r("Find what:")}),l("div",{class:"dlg-row"},l("span",{class:"bk-find-field"},this.what,o),this.fmtFind),...this.replaceRow),this.opts,this.progress,this.resultsHost,l("div",{class:"bk-find-low"},this.status,e("Options",()=>this.toggleOptions())))),l("div",{class:"bk-find-foot"},this.btnReplaceAll,this.btnReplace,e("Find All",()=>this.doFindAll()),e(R("find","Previous"),()=>this.doFind(-1)),e(R("find","Next"),()=>this.doFind(1),!0),e("Close",()=>this.close()))),this.node.addEventListener("keydown",i=>{i.stopPropagation(),i.key==="Escape"?(i.preventDefault(),this.ctrl?this.cancel():this.close()):i.key==="Enter"&&i.target.tagName!=="BUTTON"&&(i.preventDefault(),this.doFind(i.shiftKey?-1:1))}),n.addEventListener("pointerdown",i=>{i.preventDefault(),n.setPointerCapture(i.pointerId);const d=this.node.getBoundingClientRect(),u=i.clientX-d.left,f=i.clientY-d.top,g=C=>{this.node.style.left=`${Math.max(0,Math.min(window.innerWidth-80,C.clientX-u))}px`,this.node.style.top=`${Math.max(0,Math.min(window.innerHeight-40,C.clientY-f))}px`},x=()=>{n.removeEventListener("pointermove",g),n.removeEventListener("pointerup",x)};n.addEventListener("pointermove",g),n.addEventListener("pointerup",x)}),this.node.style.right="24px",this.node.style.top="120px",L().append(this.node);const h=this.node.getBoundingClientRect();this.node.style.left=`${h.left}px`,this.node.style.right="auto"}toggleOptions(){const t=this.opts.hidden||!!(this.findFormat||this.replaceFormat);this.opts.hidden=!t,this.fmtFind.hidden=!t,this.fmtReplace.hidden=!t}setMode(t){this.withReplace=t,this.modeFind.setAttribute("aria-selected",String(!t)),this.modeReplace.setAttribute("aria-selected",String(t));for(const e of this.replaceRow)e.hidden=!t;this.btnReplaceAll.hidden=!t,this.btnReplace.hidden=!t,t&&(this.look.value="formulas"),this.look.querySelector('option[value="values"]').disabled=t,this.look.querySelector('option[value="notes"]').disabled=t}focus(){this.what.focus(),this.what.select()}close(){this.cancel(),(this.what.value!==""||this.findFormat)&&(b=this._options(!1)),this.node.remove(),p=null,this.app.controller.pickCell=null,this.app.controller.focusGrid()}cancel(){this.ctrl&&(this.ctrl.cancelled=!0)}_formatMenu(t,e){const{app:o}=this,s=a=>{t==="find"?(this.findFormat=a,y(this.findChip,a)):(this.replaceFormat=a,y(this.replaceChip,a))};o.ribbon.openMenu(e,{items:[["Format…",()=>B(o,"Number",{onPick:a=>s(Object.keys(a).length?a:null)})],["Choose Format from Cell…",()=>{this.status.textContent=r("Click the cell whose format you want."),o.controller.pickCell=(a,n)=>{const{book:h}=o;s(U(h.styles.get(h.sheet.style(a,n)))),this.status.textContent=""}}],["Clear Format",()=>s(null)]]})}_options(t=!0){const{app:e}=this,o=e.grid.selection,s=o.ranges.length===1&&o.ranges[0].r0===o.ranges[0].r1&&o.ranges[0].c0===o.ranges[0].c1,a=e.book.sheet.mergeAt(o.row,o.col),n=s||a&&o.ranges.length===1;return{what:this.what.value,matchCase:this.matchCase.checked,whole:this.whole.checked,regex:this.regex.checked,look:this.look.value,format:this.findFormat,byColumns:this.searchBy.value==="cols",within:this.within.value,ranges:t&&!n?o.ranges:null}}_display(){const{grid:t}=this.app;return(e,o,s)=>t.displayText(e,o,s)}_ready(t){if(t.what===""&&t.format===null)return this.status.textContent=r("Enter what to find, or choose a format."),this.what.focus(),!1;const e=t.regex?F(t.what):null;if(e!==null)return this.status.textContent=r("This regular expression isn't valid: {problem}",{problem:e}),this.what.focus(),!1;if(t.what!==""){const o=w.indexOf(t.what);o>=0&&w.splice(o,1),w.unshift(t.what),w.length=Math.min(w.length,12)}return!0}_begin(){this.cancel();const t={cancelled:!1};this.ctrl=t;const e=this.progress,o=performance.now();return t.onProgress=()=>{if(performance.now()-o>150){e.hidden=!1;const s=e.firstChild;s.style.width=`${((performance.now()-o)/40%100).toFixed(0)}%`,this.status.textContent=r("Searching… Press Esc to stop.")}},t}_end(t){this.ctrl===t&&(this.ctrl=null),this.progress.hidden=!0}_jump(t){const{app:e}=this,{book:o}=e;t.sheet!==o.sheet&&(o.selectedSheets&&!o.selectedSheets.has(t.sheet)&&(o.selectedSheets=null),e.switchSheet(o.sheets.indexOf(t.sheet)));const s=e.grid.selection;s.ranges.some(n=>(n.r0!==n.r1||n.c0!==n.c1)&&t.row>=n.r0&&t.row<=n.r1&&t.col>=n.c0&&t.col<=n.c1)?(e.grid.setSelection({ranges:s.ranges,row:t.row,col:t.col}),e.grid.ensureVisible(t.row,t.col)):e.controller.moveTo(t.row,t.col)}async doFind(t){const e=this._options();if(!this._ready(e))return null;const o=this._begin(),s=performance.now(),a=this.app.grid.selection,n=await v(this.app.book,e,{row:a.row,col:a.col},t,this._display(),o);return this._end(o),o.cancelled?(this.status.textContent=r("Stopped."),null):(this.lastMs=performance.now()-s,n?(this._jump(n),this.status.textContent=`${n.sheet===this.app.book.sheet?"":`${n.sheet.name}!`}${_(n.row,n.col)}`,n):(this.status.textContent=r("We couldn't find what you were looking for."),null))}async doFindAll(){const t=this._options();if(!this._ready(t))return;const e=this._begin(),o=performance.now(),s=await O(this.app.book,t,this._display(),e);if(this._end(e),e.cancelled){this.status.textContent=r("Stopped.");return}this.lastMs=performance.now()-o,this.results=s,this.order=new Uint32Array(s.count);for(let n=0;n<s.count;n++)this.order[n]=n;this.sort={key:null,dir:1},this.activeRow=-1;const a=k(s.count);this.status.textContent=s.overflow?r("The first {shown} cells found. There are more.",{shown:a}):r("{shown} cells found.",{count:s.count,shown:a}),this._renderResults()}_cellValue(t){const{book:e,grid:o}=this.app,{results:s}=this,a=s.sheetList[s.sheets[t]],n=s.rows[t],h=s.cols[t];if(this.look.value==="notes")return a.comments?.get(n*E+h)?.text??"";const i=a.kind(n,h)&W;return o.displayText(i,a.value(n,h),e.styles.get(a.style(n,h))).replace(/\u0001.?\u0001/g," ")}_cellFormula(t){const{book:e}=this.app,{results:o}=this,s=e.editText(o.sheetList[o.sheets[t]],o.rows[t],o.cols[t]);return s[0]==="="||s.startsWith("{=")?s:""}_sortBy(t){const{results:e}=this;if(!e)return;const o=this.sort.key===t?-this.sort.dir:1;this.sort={key:t,dir:o};const s={sheet:i=>e.sheetList[e.sheets[i]].name,cell:i=>e.cols[i]*$+e.rows[i],value:i=>this._cellValue(i),formula:i=>this._cellFormula(i)}[t],a=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"}),n=new Array(e.count);for(let i=0;i<e.count;i++)n[i]=s(i);const h=Array.from(this.order);h.sort((i,d)=>o*(typeof n[i]=="number"?n[i]-n[d]:a.compare(n[i],n[d]))),this.order=Uint32Array.from(h),this._renderResults()}_renderResults(){const{results:t}=this,e=(h,i)=>l("button",{type:"button",textContent:`${r(h)}${this.sort.key===i?this.sort.dir>0?" ▴":" ▾":""}`,on:{click:()=>this._sortBy(i)}}),o=l("div",{class:"bk-results-body",tabIndex:0}),s=l("div",{style:`height:${t.count*m}px`}),a=l("div");o.append(s,a);const n=()=>{const h=Math.floor(o.scrollTop/m),i=Math.min(t.count,h+Math.ceil(o.clientHeight/m)+2),d=[];for(let u=h;u<i;u++){const f=this.order[u],g=l("div",{class:`bk-results-row${u===this.activeRow?" active":""}`,style:`top:${u*m}px`,on:{click:()=>this._pick(u)}},l("span",{textContent:t.sheetList[t.sheets[f]].name}),l("span",{textContent:_(t.rows[f],t.cols[f])}),l("span",{textContent:this._cellValue(f)}),l("span",{textContent:this._cellFormula(f)}));d.push(g)}a.replaceChildren(...d)};this.drawResults=n,o.addEventListener("scroll",n,{passive:!0}),o.addEventListener("keydown",h=>{h.key!=="ArrowDown"&&h.key!=="ArrowUp"||(h.preventDefault(),this._pick(Math.max(0,Math.min(t.count-1,this.activeRow+(h.key==="ArrowDown"?1:-1)))))}),this.resultsHost.replaceChildren(l("div",{class:"bk-results-head"},e("Sheet","sheet"),e("Cell","cell"),e("Value","value"),e("Formula","formula")),o),this.resultsHost.hidden=t.count===0,n(),this.resultsBody=o}_pick(t){const{results:e}=this,o=this.order[t];this.activeRow=t,this._jump({sheet:e.sheetList[e.sheets[o]],row:e.rows[o],col:e.cols[o]});const s=this.resultsBody;t*m<s.scrollTop?s.scrollTop=t*m:(t+1)*m>s.scrollTop+s.clientHeight&&(s.scrollTop=(t+1)*m-s.clientHeight),this.drawResults()}async doReplace(){const t=this._options(!1);if(!this._ready(t))return;const{app:e}=this,{book:o}=e,{sheet:s}=o,{row:a,col:n}=e.grid.selection;if(await v(o,{...t,within:"sheet",look:"formulas"},{row:a,col:n},1,this._display(),{})!==null&&this._matchesHere(t,a,n))if(s.protection&&!T(o,s,a,n))this.status.textContent=r("This cell is locked.");else{const d=t.what===""?null:N(t.what,this.repl.value,t),u={invalid:0};if(o.transact("replace",f=>{D(o,f,a,n,d,this.replaceFormat,u)}),e.grid.invalidate(),u.invalid>0){this.status.textContent=r("There's a problem with this formula after the replacement, so the cell was left as it was.");return}}await this.doFind(1)}_matchesHere(t,e,o){const{book:s}=this.app,{sheet:a}=s;return H(s,{...t,look:"formulas"},this._display())(a,e,o,a.kind(e,o),a.value(e,o))}async doReplaceAll(){const t=this._options();if(!this._ready(t))return;const e=this._begin(),o=performance.now(),s=await P(this.app.book,t,this.repl.value,this.replaceFormat,this._display(),e);if(this._end(e),this.lastMs=performance.now()-o,s.cancelled){this.status.textContent=r("Stopped; nothing was replaced.");return}const a={count:s.count,shown:k(s.count),sheets:s.sheets},n=[s.count===0&&s.locked===0&&s.invalid===0?r("We couldn't find anything to replace."):s.sheets>1?r("All done. We made {shown} replacements on {sheets} sheets.",a):r("All done. We made {shown} replacements.",a)];s.locked>0&&n.push(r("{shown} locked cells on protected sheets were left as they were.",{count:s.locked,shown:k(s.locked)})),s.invalid>0&&n.push(r("{shown} cells were left as they were, as the replacement would break their formulas.",{count:s.invalid,shown:k(s.invalid)})),this.status.textContent=n.join(" "),this.app.grid.invalidate(),this.app.afterCommand(),this.what.focus()}}function ot(c,t){if(!p&&b){const e=b.regex?F(b.what):null;if(e!==null)return c.shell?.setStatus(r("This regular expression isn't valid: {problem}",{problem:e})),null;const o=c.grid.selection;return v(c.book,b,{row:o.row,col:o.col},t,(s,a,n)=>c.grid.displayText(s,a,n),{}).then(s=>s?(s.sheet&&s.sheet!==c.book.sheet&&c.switchSheet(c.book.sheets.indexOf(s.sheet)),c.controller.moveTo(s.row,s.col),s):(c.shell?.setStatus(r("We couldn't find what you were looking for.")),null))}return p?(A(c),p.doFind(t)):(K(c),null)}const S=new WeakSet;function A(c){p.app=c,!S.has(c)&&(S.add(c),c.signal?.addEventListener("abort",()=>{p?.app===c&&(p.cancel(),p.node.remove(),p=null)},{once:!0}))}function K(c,t=!1){p??=new X(c),A(c),p.setMode(t),p.focus();const e=p;return setTimeout(()=>{p===e&&document.activeElement!==e.what&&!e.node.contains(document.activeElement)&&e.focus()},0),p}export{ot as findAgain,K as openFind};
|
package/cells/goto.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{el as h,openModal as D}from"../ui/dialogs.js";import{ensureBookCss as L}from"./book-css.js";import{BOOL as U,CHUNK_BITS as v,CHUNK_MASK as $,ERR as q,FORMULA as T,KIND_MASK as N,NUM as H,STR as V}from"../core/sheet.js";import{MAX_COLS as y,MAX_ROWS as j,parseRangeRef as G}from"../core/address.js";import{goToText as X,locationText as z,namedPlaces as P}from"./name-box.js";import{inRanges as S}from"./selection-modes.js";import{t as M,tc as A}from"../i18n/index.js";const O=32768;class C{constructor(){this.ranges=[],this.open=new Map,this.col=-1}add(a,s,e){const n=s*j+e,i=this.open.get(n);if(i&&i.c1===a-1){i.c1=a;return}const t={r0:s,c0:a,r1:e,c1:a};this.open.set(n,t),this.ranges.push(t)}get tooMany(){return this.ranges.length>O}}function Z(r){const{grid:a,book:s}=r,{sheet:e}=s,{ranges:n}=a.selection,i=t=>({r0:t.r0,c0:t.c0,r1:Math.min(t.r1,e.maxRow),c1:Math.min(t.c1,e.maxCol)});if(_(r)){const{r0:t,c0:c}=W(e);return[{r0:t,c0:c,r1:Math.max(t,e.maxRow),c1:Math.max(c,e.maxCol)}]}return n.map(i).filter(t=>t.r0<=t.r1&&t.c0<=t.c1)}function _(r){const{ranges:a}=r.grid.selection;if(a.length!==1)return!1;const s=a[0];if(s.r0===s.r1&&s.c0===s.c1)return!0;const e=r.book.sheet.mergeAt(s.r0,s.c0);return e!=null&&e.r0===s.r0&&e.c0===s.c0&&e.r1===s.r1&&e.c1===s.c1}function W(r){let a=1/0,s=1/0;for(const e of r.rowStyles?.keys()??[])e<a&&(a=e),s=0;for(const e of r.colStyles?.keys()??[])e<s&&(s=e),a=0;for(let e=0;e<=r.maxCol;e++){const n=r.columns[e];if(n!==void 0)for(let i=0;i<n.length&&i<<v<a;i++){const t=n[i];if(t===void 0)continue;const c=i<<v;for(let o=0;o<t.kinds.length&&c+o<a;o++)if(!(t.kinds[o]===0&&(t.styles===null||t.styles[o]===0))){a=c+o,e<s&&(s=e);break}if(s===e)break}}return{r0:a===1/0?0:a,c0:s===1/0?0:s}}function I(r,a,s){const e=new C;for(const n of a)for(let i=n.c0;i<=n.c1;i++){const t=r.columns[i];if(t===void 0)continue;let c=-1;for(let o=n.r0>>>v;o<=n.r1>>>v;o++){const l=t[o],f=o<<v;if(l===void 0){c>=0&&(e.add(i,c,f-1),c=-1);continue}const m=Math.max(n.r0-f,0),u=Math.min(n.r1-f,$);for(let d=m;d<=u;d++){const g=l.kinds[d];g!==0&&s(g,f+d,i,l.values[d])?c<0&&(c=f+d):c>=0&&(e.add(i,c,f+d-1),c=-1)}}c>=0&&e.add(i,c,n.r1)}return e}const K=(r,a)=>{const s=r&N;return s===H&&a.numbers||s===V&&a.text||s===U&&a.logicals||s===q&&a.errors};function J(r,a){const s=new C;for(const e of a)for(let n=e.c0;n<=e.c1&&!s.tooMany;n++){const i=r.columns[n];if(i===void 0){s.add(n,e.r0,e.r1);continue}let t=-1;for(let c=e.r0;c<=e.r1;c++){const o=i[c>>>v];if(o===void 0){t<0&&(t=c);const l=c|$;c=Math.min(l,e.r1);continue}o.kinds[c&$]===0?t<0&&(t=c):t>=0&&(s.add(n,t,c-1),t=-1)}t>=0&&s.add(n,t,e.r1)}return s}const B=(r,a,s)=>{const e=r.rAbs0?r.r0:a+r.r0,n=r.rAbs1?r.r1:a+r.r1,i=r.cAbs0?r.c0:s+r.c0,t=r.cAbs1?r.c1:s+r.c1;return{r0:Math.min(e,n),c0:Math.min(i,t),r1:Math.max(e,n),c1:Math.max(i,t)}};function E(r,a,s,e){return a.formula(s,e)?.tpl??null}function Q(r,a,s,e){const n=new Set,i=[];let t=[];for(const c of s)for(const[o]of a.formulas){const l=Math.floor(o/y),f=o-l*y;l>=c.r0&&l<=c.r1&&f>=c.c0&&f<=c.c1&&t.push([l,f])}for(let c=0;t.length>0&&c<64;c++){const o=[];for(const[l,f]of t){const m=E(r,a,l,f);if(m)for(const u of m.refs){if(u.sheet)continue;const d=B(u,l,f),g=`${d.r0},${d.c0},${d.r1},${d.c1}`;if(!n.has(g)&&(n.add(g),i.push({r0:d.r0,c0:d.c0,r1:Math.min(d.r1,j-1),c1:Math.min(d.c1,y-1)}),!!e))for(const[b]of a.formulas){const p=Math.floor(b/y),k=b-p*y;p>=d.r0&&p<=d.r1&&k>=d.c0&&k<=d.c1&&o.push([p,k])}}}if(!e)break;t=o}return i}function Y(r,a,s,e){const n=new Set;let i=s;for(let o=0;i.length>0&&o<64;o++){const l=[];for(const[f]of a.formulas){if(n.has(f))continue;const m=Math.floor(f/y),u=f-m*y,d=E(r,a,m,u);if(d)for(const g of d.refs){if(g.sheet)continue;const b=B(g,m,u);if(i.some(p=>b.r0<=p.r1&&b.r1>=p.r0&&b.c0<=p.c1&&b.c1>=p.c0)){n.add(f),l.push({r0:m,c0:u,r1:m,c1:u});break}}}if(!e)break;i=l}const t=new Map;for(const o of n){const l=Math.floor(o/y),f=o-l*y;t.has(f)||t.set(f,[]),t.get(f).push(l)}const c=new C;for(const o of[...t.keys()].sort((l,f)=>l-f)){const l=t.get(o).sort((m,u)=>m-u);let f=l[0];for(let m=1;m<=l.length;m++)l[m]!==l[m-1]+1&&(c.add(o,f,l[m-1]),f=l[m])}return c.ranges}function R(r,a,s,e,n,i){const t=a.kind(s,e);return t&T?`f${r.editText(a,s,e).replace(/\$?[A-Z]{1,3}\$?\d+/g,o=>{const l=/^(\$?)([A-Z]+)(\$?)(\d+)$/.exec(o),f=l[2].split("").reduce((m,u)=>m*26+u.charCodeAt(0)-64,0)-1;return`${l[1]?`$${l[2]}`:`C[${f-e+i}]`}${l[3]?`$${l[4]}`:`R[${Number(l[4])-1-s+n}]`}`})}`:`${t&N}:${a.value(s,e)}`}function ee(r,a,s,e){const n=new C;for(const i of s)for(let t=i.c0;t<=i.c1;t++){if(t===e)continue;let c=-1;for(let o=i.r0;o<=i.r1;o++){const l=R(r,a,o,t,o,e)!==R(r,a,o,e,o,e);l&&c<0?c=o:!l&&c>=0&&(n.add(t,c,o-1),c=-1)}c>=0&&n.add(t,c,i.r1)}return n}function te(r,a,s,e){const n=new C;for(const i of s)for(let t=i.c0;t<=i.c1;t++){const c=R(r,a,e,t,e,t);let o=-1;for(let l=i.r0;l<=i.r1;l++){const f=l!==e&&R(r,a,l,t,e,t)!==c;f&&o<0?o=l:!f&&o>=0&&(n.add(t,o,l-1),o=-1)}o>=0&&n.add(t,o,i.r1)}return n}function ne(r,a){const s=(n,i,t)=>{const c=[];let o=-1;for(let l=i;l<=t;l++){const f=n.sizeOf(l)>0;f&&o<0?o=l:!f&&o>=0&&(c.push([o,l-1]),o=-1)}return o>=0&&c.push([o,t]),c},e=[];for(const n of a){const i=s(r.rows,n.r0,Math.min(n.r1,Math.max(r.maxRow,n.r0))),t=s(r.cols,n.c0,Math.min(n.c1,Math.max(r.maxCol,n.c0)));for(const[c,o]of i)for(const[l,f]of t)e.push({r0:c,c0:l,r1:o,c1:f})}return e}const F=r=>(r??"").split(/\s+/).map(G).filter(Boolean);function oe(r,{same:a},s,e){const n=[];for(const i of r.cf??[]){const t=F(i.sqref);(!a||S(t,s,e))&&n.push(...t)}return n}function se(r,{same:a},s,e){const n=[];for(const i of r.validations??[]){const t=F(i.sqref);(!a||S(t,s,e))&&n.push(...t)}return n}function ce(r){const{book:a,grid:s}=r,{sheet:e}=a,{row:n,col:i}=s.selection,t=(o,l)=>{const f=e.formula(o,l);return f&&f.t==="array"&&f.ref?G(f.ref):null};let c=t(n,i);if(!c&&a.engine?.spillMaster){const o=a.engine.spillMaster(e,n,i);o&&(c=t(o.row,o.col)??null)}return c}function re(r,a,s={}){const{book:e,grid:n,controller:i,shell:t}=r,{sheet:c}=e,{row:o,col:l}=n.selection,f=Z(r),m={numbers:s.numbers!==!1,text:s.text!==!1,logicals:s.logicals!==!1,errors:s.errors!==!1};let u=[];switch(a){case"notes":{const b=new C,p=_(r),k=[...c.comments?.keys()??[]].map(x=>[x%y,Math.floor(x/y)]).filter(([x,w])=>p||S(n.selection.ranges,w,x)).sort((x,w)=>x[0]-w[0]||x[1]-w[1]);for(const[x,w]of k)b.add(x,w,w);u=b.ranges;break}case"constants":u=I(c,f,b=>!(b&T)&&K(b,m)).ranges;break;case"formulas":u=I(c,f,b=>b&T&&K(b,m)).ranges;break;case"blanks":u=J(c,f).ranges;break;case"region":{u=[r.commands._currentRegion(o,l)??{r0:o,c0:l,r1:o,c1:l}];break}case"array":{const b=ce(r);u=b?[b]:[];break}case"objects":{const p=(r.objects?._state?.(c)?.objects??[]).filter(k=>!k.hidden&&k.kind!=="foreign");if(p.length>0){r.objects.select(p[0]);for(const k of p.slice(1))r.objects.select(k,{add:!0});t.setStatus(M("{count} objects selected.",{count:p.length}))}else t.setStatus(M("There are no objects on this sheet."));return}case"rowDiff":u=ee(e,c,f,l).ranges;break;case"colDiff":u=te(e,c,f,o).ranges;break;case"precedents":case"precedentsAll":u=Q(e,c,n.selection.ranges,a==="precedentsAll");break;case"dependents":case"dependentsAll":u=Y(e,c,n.selection.ranges,a==="dependentsAll");break;case"lastCell":u=[{r0:Math.max(c.maxRow,0),c0:Math.max(c.maxCol,0),r1:Math.max(c.maxRow,0),c1:Math.max(c.maxCol,0)}];break;case"visible":u=ne(c,n.selection.ranges.length===1&&n.selection.ranges[0].r0===n.selection.ranges[0].r1&&n.selection.ranges[0].c0===n.selection.ranges[0].c1?f:n.selection.ranges);break;case"cf":u=oe(c,s,o,l);break;case"validation":u=se(c,s,o,l);break;default:return}if(u.length===0){t.setStatus(M("No cells were found."));return}if(u.length>O){t.setStatus(M("That selection is too large: more than {count} separate areas.",{count:O.toLocaleString("en-US")}));return}const d=u[0],g=S(u,o,l);n.setSelection({ranges:u,row:g?o:d.r0,col:g?l:d.c0}),i.extent={row:d.r1,col:d.c1},g||n.ensureVisible(d.r0,d.c0)}function le(r){L();const a="bk-special";let s="notes";const e=(p,k,x=!1)=>{const w=h("input",{type:"radio",name:a,value:p,checked:x,on:{change:()=>{s=p,g()}}});return h("label",{class:"dlg-row dlg-check"},w,` ${A("special",k)}`)},n={numbers:h("input",{type:"checkbox",checked:!0}),text:h("input",{type:"checkbox",checked:!0}),logicals:h("input",{type:"checkbox",checked:!0}),errors:h("input",{type:"checkbox",checked:!0})},i=h("input",{type:"radio",name:"bk-depth",checked:!0}),t=h("input",{type:"radio",name:"bk-depth"}),c=h("input",{type:"radio",name:"bk-same",checked:!0}),o=h("input",{type:"radio",name:"bk-same"}),l=(p,k)=>h("label",{class:"dlg-row dlg-check"},p,` ${A("special",k)}`),f=h("div",{class:"bk-special-opts"},l(n.numbers,"Numbers"),l(n.text,"Text"),l(n.logicals,"Logicals"),l(n.errors,"Errors")),m=h("div",{class:"bk-special-opts"},l(i,"Direct only"),l(t,"All levels")),u=h("div",{class:"bk-special-opts"},l(c,"All"),l(o,"Same")),d=h("p",{class:"bk-special-none",textContent:M("There are no options for this selection.")}),g=()=>{f.hidden=s!=="constants"&&s!=="formulas",m.hidden=s!=="precedents"&&s!=="dependents",u.hidden=s!=="cf"&&s!=="validation",d.hidden=!(f.hidden&&m.hidden&&u.hidden)},b=h("div",{class:"bk-special"},h("div",{class:"xl-head dlg-label",textContent:A("special","Select")}),h("div",{class:"bk-grid2"},h("div",{},e("notes","Notes",!0),e("constants","Constants"),e("formulas","Formulas"),e("blanks","Blanks"),e("region","Current region"),e("array","Current array"),e("rowDiff","Row differences"),e("colDiff","Column differences")),h("div",{},e("precedents","Precedents"),e("dependents","Dependents"),e("lastCell","Last cell"),e("visible","Visible cells only"),e("objects","Objects"),e("cf","Conditional formats"),e("validation","Data validation"))),h("hr",{class:"xl-rule"}),h("div",{class:"xl-head dlg-label",textContent:M("Options")}),h("div",{class:"bk-special-low"},f,m,u,d));g(),D(r,A("dlg","Go To Special"),b,[{label:"Cancel"},{label:"OK",primary:!0,action:()=>{let p=s;(p==="precedents"||p==="dependents")&&t.checked&&(p+="All"),re(r,p,{numbers:n.numbers.checked,text:n.text.checked,logicals:n.logicals.checked,errors:n.errors.checked,same:o.checked})}}],{width:334,className:"xl-dlg"})}function pe(r){const{book:a,grid:s}=r,e=a.gotoHistory??=[],n=h("select",{class:"dlg-list bk-goto-list",size:8,"aria-label":M("Go to")});for(const o of P(a))n.append(h("option",{value:o.label,textContent:o.label}));for(const o of e.slice().reverse())n.append(h("option",{value:o,textContent:o}));const i=h("input",{class:"dlg-input","aria-label":M("Reference"),spellcheck:!1,value:e[e.length-1]??""});n.addEventListener("change",()=>{i.value=n.value}),n.addEventListener("dblclick",()=>{t()&&c.close()});const t=()=>{const o=z(a,s.selection);return X(r,i.value)?(e[e.length-1]!==o&&e.push(o),e.length>32&&e.shift(),!0):(i.select(),!1)};L();const c=D(r,A("dlg","Go To"),h("div",{class:"dlg-col"},h("div",{class:"dlg-label",textContent:M("Go to:")}),n,h("label",{class:"bk-above"},h("span",{textContent:M("Reference:")}),i)),[{label:"Special…",left:!0,action:()=>{queueMicrotask(()=>le(r))}},{label:"Cancel"},{label:"OK",primary:!0,action:()=>t()}],{width:326,className:"xl-dlg"});i.focus(),i.select()}export{le as goToSpecial,pe as openGoTo,re as selectSpecial};
|
|
1
|
+
import{el as h,openModal as D,showMessage as U}from"../ui/dialogs.js";import{ensureBookCss as L}from"./book-css.js";import{BOOL as q,CHUNK_BITS as v,CHUNK_MASK as $,ERR as V,FORMULA as T,KIND_MASK as N,NUM as H,STR as X}from"../core/sheet.js";import{allValidations as z,hostFormats as P}from"../core/host-rules.js";import{MAX_COLS as y,MAX_ROWS as j,parseRangeRef as G}from"../core/address.js";import{goToText as Z,locationText as W,namedPlaces as J}from"./name-box.js";import{inRanges as S}from"./selection-modes.js";import{t as w,tc as A}from"../i18n/index.js";const O=32768;class C{constructor(){this.ranges=[],this.open=new Map,this.col=-1}add(a,s,e){const n=s*j+e,i=this.open.get(n);if(i&&i.c1===a-1){i.c1=a;return}const t={r0:s,c0:a,r1:e,c1:a};this.open.set(n,t),this.ranges.push(t)}get tooMany(){return this.ranges.length>O}}function Q(r){const{grid:a,book:s}=r,{sheet:e}=s,{ranges:n}=a.selection,i=t=>({r0:t.r0,c0:t.c0,r1:Math.min(t.r1,e.maxRow),c1:Math.min(t.c1,e.maxCol)});if(_(r)){const{r0:t,c0:c}=Y(e);return[{r0:t,c0:c,r1:Math.max(t,e.maxRow),c1:Math.max(c,e.maxCol)}]}return n.map(i).filter(t=>t.r0<=t.r1&&t.c0<=t.c1)}function _(r){const{ranges:a}=r.grid.selection;if(a.length!==1)return!1;const s=a[0];if(s.r0===s.r1&&s.c0===s.c1)return!0;const e=r.book.sheet.mergeAt(s.r0,s.c0);return e!=null&&e.r0===s.r0&&e.c0===s.c0&&e.r1===s.r1&&e.c1===s.c1}function Y(r){let a=1/0,s=1/0;for(const e of r.rowStyles?.keys()??[])e<a&&(a=e),s=0;for(const e of r.colStyles?.keys()??[])e<s&&(s=e),a=0;for(let e=0;e<=r.maxCol;e++){const n=r.columns[e];if(n!==void 0)for(let i=0;i<n.length&&i<<v<a;i++){const t=n[i];if(t===void 0)continue;const c=i<<v;for(let o=0;o<t.kinds.length&&c+o<a;o++)if(!(t.kinds[o]===0&&(t.styles===null||t.styles[o]===0))){a=c+o,e<s&&(s=e);break}if(s===e)break}}return{r0:a===1/0?0:a,c0:s===1/0?0:s}}function I(r,a,s){const e=new C;for(const n of a)for(let i=n.c0;i<=n.c1;i++){const t=r.columns[i];if(t===void 0)continue;let c=-1;for(let o=n.r0>>>v;o<=n.r1>>>v;o++){const l=t[o],f=o<<v;if(l===void 0){c>=0&&(e.add(i,c,f-1),c=-1);continue}const m=Math.max(n.r0-f,0),u=Math.min(n.r1-f,$);for(let d=m;d<=u;d++){const p=l.kinds[d];p!==0&&s(p,f+d,i,l.values[d])?c<0&&(c=f+d):c>=0&&(e.add(i,c,f+d-1),c=-1)}}c>=0&&e.add(i,c,n.r1)}return e}const K=(r,a)=>{const s=r&N;return s===H&&a.numbers||s===X&&a.text||s===q&&a.logicals||s===V&&a.errors};function ee(r,a){const s=new C;for(const e of a)for(let n=e.c0;n<=e.c1&&!s.tooMany;n++){const i=r.columns[n];if(i===void 0){s.add(n,e.r0,e.r1);continue}let t=-1;for(let c=e.r0;c<=e.r1;c++){const o=i[c>>>v];if(o===void 0){t<0&&(t=c);const l=c|$;c=Math.min(l,e.r1);continue}o.kinds[c&$]===0?t<0&&(t=c):t>=0&&(s.add(n,t,c-1),t=-1)}t>=0&&s.add(n,t,e.r1)}return s}const B=(r,a,s)=>{const e=r.rAbs0?r.r0:a+r.r0,n=r.rAbs1?r.r1:a+r.r1,i=r.cAbs0?r.c0:s+r.c0,t=r.cAbs1?r.c1:s+r.c1;return{r0:Math.min(e,n),c0:Math.min(i,t),r1:Math.max(e,n),c1:Math.max(i,t)}};function E(r,a,s,e){return a.formula(s,e)?.tpl??null}function te(r,a,s,e){const n=new Set,i=[];let t=[];for(const c of s)for(const[o]of a.formulas){const l=Math.floor(o/y),f=o-l*y;l>=c.r0&&l<=c.r1&&f>=c.c0&&f<=c.c1&&t.push([l,f])}for(let c=0;t.length>0&&c<64;c++){const o=[];for(const[l,f]of t){const m=E(r,a,l,f);if(m)for(const u of m.refs){if(u.sheet)continue;const d=B(u,l,f),p=`${d.r0},${d.c0},${d.r1},${d.c1}`;if(!n.has(p)&&(n.add(p),i.push({r0:d.r0,c0:d.c0,r1:Math.min(d.r1,j-1),c1:Math.min(d.c1,y-1)}),!!e))for(const[b]of a.formulas){const g=Math.floor(b/y),k=b-g*y;g>=d.r0&&g<=d.r1&&k>=d.c0&&k<=d.c1&&o.push([g,k])}}}if(!e)break;t=o}return i}function ne(r,a,s,e){const n=new Set;let i=s;for(let o=0;i.length>0&&o<64;o++){const l=[];for(const[f]of a.formulas){if(n.has(f))continue;const m=Math.floor(f/y),u=f-m*y,d=E(r,a,m,u);if(d)for(const p of d.refs){if(p.sheet)continue;const b=B(p,m,u);if(i.some(g=>b.r0<=g.r1&&b.r1>=g.r0&&b.c0<=g.c1&&b.c1>=g.c0)){n.add(f),l.push({r0:m,c0:u,r1:m,c1:u});break}}}if(!e)break;i=l}const t=new Map;for(const o of n){const l=Math.floor(o/y),f=o-l*y;t.has(f)||t.set(f,[]),t.get(f).push(l)}const c=new C;for(const o of[...t.keys()].sort((l,f)=>l-f)){const l=t.get(o).sort((m,u)=>m-u);let f=l[0];for(let m=1;m<=l.length;m++)l[m]!==l[m-1]+1&&(c.add(o,f,l[m-1]),f=l[m])}return c.ranges}function R(r,a,s,e,n,i){const t=a.kind(s,e);return t&T?`f${r.editText(a,s,e).replace(/\$?[A-Z]{1,3}\$?\d+/g,o=>{const l=/^(\$?)([A-Z]+)(\$?)(\d+)$/.exec(o),f=l[2].split("").reduce((m,u)=>m*26+u.charCodeAt(0)-64,0)-1;return`${l[1]?`$${l[2]}`:`C[${f-e+i}]`}${l[3]?`$${l[4]}`:`R[${Number(l[4])-1-s+n}]`}`})}`:`${t&N}:${a.value(s,e)}`}function oe(r,a,s,e){const n=new C;for(const i of s)for(let t=i.c0;t<=i.c1;t++){if(t===e)continue;let c=-1;for(let o=i.r0;o<=i.r1;o++){const l=R(r,a,o,t,o,e)!==R(r,a,o,e,o,e);l&&c<0?c=o:!l&&c>=0&&(n.add(t,c,o-1),c=-1)}c>=0&&n.add(t,c,i.r1)}return n}function se(r,a,s,e){const n=new C;for(const i of s)for(let t=i.c0;t<=i.c1;t++){const c=R(r,a,e,t,e,t);let o=-1;for(let l=i.r0;l<=i.r1;l++){const f=l!==e&&R(r,a,l,t,e,t)!==c;f&&o<0?o=l:!f&&o>=0&&(n.add(t,o,l-1),o=-1)}o>=0&&n.add(t,o,i.r1)}return n}function ce(r,a){const s=(n,i,t)=>{const c=[];let o=-1;for(let l=i;l<=t;l++){const f=n.sizeOf(l)>0;f&&o<0?o=l:!f&&o>=0&&(c.push([o,l-1]),o=-1)}return o>=0&&c.push([o,t]),c},e=[];for(const n of a){const i=s(r.rows,n.r0,Math.min(n.r1,Math.max(r.maxRow,n.r0))),t=s(r.cols,n.c0,Math.min(n.c1,Math.max(r.maxCol,n.c0)));for(const[c,o]of i)for(const[l,f]of t)e.push({r0:c,c0:l,r1:o,c1:f})}return e}const F=r=>(r??"").split(/\s+/).map(G).filter(Boolean);function re(r,{same:a},s,e){const n=[];for(const i of[...r.cf??[],...P(r)]){const t=F(i.sqref);(!a||S(t,s,e))&&n.push(...t)}return n}function le(r,{same:a},s,e){const n=[];for(const i of z(r)){const t=F(i.sqref);(!a||S(t,s,e))&&n.push(...t)}return n}function ae(r){const{book:a,grid:s}=r,{sheet:e}=a,{row:n,col:i}=s.selection,t=(o,l)=>{const f=e.formula(o,l);return f&&f.t==="array"&&f.ref?G(f.ref):null};let c=t(n,i);if(!c&&a.engine?.spillMaster){const o=a.engine.spillMaster(e,n,i);o&&(c=t(o.row,o.col)??null)}return c}function ie(r,a,s={}){const{book:e,grid:n,controller:i,shell:t}=r,{sheet:c}=e,{row:o,col:l}=n.selection,f=Q(r),m={numbers:s.numbers!==!1,text:s.text!==!1,logicals:s.logicals!==!1,errors:s.errors!==!1};let u=[];switch(a){case"notes":{const b=new C,g=_(r),k=[...c.comments?.keys()??[]].map(x=>[x%y,Math.floor(x/y)]).filter(([x,M])=>g||S(n.selection.ranges,M,x)).sort((x,M)=>x[0]-M[0]||x[1]-M[1]);for(const[x,M]of k)b.add(x,M,M);u=b.ranges;break}case"constants":u=I(c,f,b=>!(b&T)&&K(b,m)).ranges;break;case"formulas":u=I(c,f,b=>b&T&&K(b,m)).ranges;break;case"blanks":u=ee(c,f).ranges;break;case"region":{u=[r.commands._currentRegion(o,l)??{r0:o,c0:l,r1:o,c1:l}];break}case"array":{const b=ae(r);u=b?[b]:[];break}case"objects":{const g=(r.objects?._state?.(c)?.objects??[]).filter(k=>!k.hidden&&k.kind!=="foreign");if(g.length>0){r.objects.select(g[0]);for(const k of g.slice(1))r.objects.select(k,{add:!0});t.setStatus(w("{count} objects selected.",{count:g.length}))}else t.setStatus(w("There are no objects on this sheet."));return}case"rowDiff":u=oe(e,c,f,l).ranges;break;case"colDiff":u=se(e,c,f,o).ranges;break;case"precedents":case"precedentsAll":u=te(e,c,n.selection.ranges,a==="precedentsAll");break;case"dependents":case"dependentsAll":u=ne(e,c,n.selection.ranges,a==="dependentsAll");break;case"lastCell":u=[{r0:Math.max(c.maxRow,0),c0:Math.max(c.maxCol,0),r1:Math.max(c.maxRow,0),c1:Math.max(c.maxCol,0)}];break;case"visible":u=ce(c,n.selection.ranges.length===1&&n.selection.ranges[0].r0===n.selection.ranges[0].r1&&n.selection.ranges[0].c0===n.selection.ranges[0].c1?f:n.selection.ranges);break;case"cf":u=re(c,s,o,l);break;case"validation":u=le(c,s,o,l);break;default:return}if(u.length===0){U(r,"8sheets","No cells were found.");return}if(u.length>O){t.setStatus(w("That selection is too large: more than {count} separate areas.",{count:O.toLocaleString("en-US")}));return}const d=u[0],p=S(u,o,l);n.setSelection({ranges:u,row:p?o:d.r0,col:p?l:d.c0}),i.extent={row:d.r1,col:d.c1},p||n.ensureVisible(d.r0,d.c0)}function fe(r){L();const a="bk-special";let s="notes";const e=(g,k,x=!1)=>{const M=h("input",{type:"radio",name:a,value:g,checked:x,on:{change:()=>{s=g,p()}}});return h("label",{class:"dlg-row dlg-check"},M,` ${A("special",k)}`)},n={numbers:h("input",{type:"checkbox",checked:!0}),text:h("input",{type:"checkbox",checked:!0}),logicals:h("input",{type:"checkbox",checked:!0}),errors:h("input",{type:"checkbox",checked:!0})},i=h("input",{type:"radio",name:"bk-depth",checked:!0}),t=h("input",{type:"radio",name:"bk-depth"}),c=h("input",{type:"radio",name:"bk-same",checked:!0}),o=h("input",{type:"radio",name:"bk-same"}),l=(g,k)=>h("label",{class:"dlg-row dlg-check"},g,` ${A("special",k)}`),f=h("div",{class:"bk-special-opts"},l(n.numbers,"Numbers"),l(n.text,"Text"),l(n.logicals,"Logicals"),l(n.errors,"Errors")),m=h("div",{class:"bk-special-opts"},l(i,"Direct only"),l(t,"All levels")),u=h("div",{class:"bk-special-opts"},l(c,"All"),l(o,"Same")),d=h("p",{class:"bk-special-none",textContent:w("There are no options for this selection.")}),p=()=>{f.hidden=s!=="constants"&&s!=="formulas",m.hidden=s!=="precedents"&&s!=="dependents",u.hidden=s!=="cf"&&s!=="validation",d.hidden=!(f.hidden&&m.hidden&&u.hidden)},b=h("div",{class:"bk-special"},h("div",{class:"xl-head dlg-label",textContent:A("special","Select")}),h("div",{class:"bk-grid2"},h("div",{},e("notes","Notes",!0),e("constants","Constants"),e("formulas","Formulas"),e("blanks","Blanks"),e("region","Current region"),e("array","Current array"),e("rowDiff","Row differences"),e("colDiff","Column differences")),h("div",{},e("precedents","Precedents"),e("dependents","Dependents"),e("lastCell","Last cell"),e("visible","Visible cells only"),e("objects","Objects"),e("cf","Conditional formats"),e("validation","Data validation"))),h("hr",{class:"xl-rule"}),h("div",{class:"xl-head dlg-label",textContent:w("Options")}),h("div",{class:"bk-special-low"},f,m,u,d));p(),D(r,A("dlg","Go To Special"),b,[{label:"Cancel"},{label:"OK",primary:!0,action:()=>{let g=s;(g==="precedents"||g==="dependents")&&t.checked&&(g+="All"),ie(r,g,{numbers:n.numbers.checked,text:n.text.checked,logicals:n.logicals.checked,errors:n.errors.checked,same:o.checked})}}],{width:334,className:"xl-dlg"})}function xe(r){const{book:a,grid:s}=r,e=a.gotoHistory??=[],n=h("select",{class:"dlg-list bk-goto-list",size:8,"aria-label":w("Go to")});for(const o of J(a))n.append(h("option",{value:o.label,textContent:o.label}));for(const o of e.slice().reverse())n.append(h("option",{value:o,textContent:o}));const i=h("input",{class:"dlg-input","aria-label":w("Reference"),spellcheck:!1,value:e[e.length-1]??""});n.addEventListener("change",()=>{i.value=n.value}),n.addEventListener("dblclick",()=>{t()&&c.close()});const t=()=>{const o=W(a,s.selection);return Z(r,i.value)?(e[e.length-1]!==o&&e.push(o),e.length>32&&e.shift(),!0):(i.select(),!1)};L();const c=D(r,A("dlg","Go To"),h("div",{class:"dlg-col"},h("div",{class:"dlg-label",textContent:w("Go to:")}),n,h("label",{class:"bk-above"},h("span",{textContent:w("Reference:")}),i)),[{label:"Special…",left:!0,action:()=>{queueMicrotask(()=>fe(r))}},{label:"Cancel"},{label:"OK",primary:!0,action:()=>t()}],{width:326,className:"xl-dlg"});i.focus(),i.select()}export{fe as goToSpecial,xe as openGoTo,ie as selectSpecial};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{parseRangeRef as o,rangeRef as l}from"../core/address.js";import{FORMULA as p}from"../core/sheet.js";const L="#0563C1",k="#954F72",m=(s,t,e)=>(s.ref??"").split(/\s+/).map(o).some(n=>n&&t>=n.r0&&t<=n.r1&&e>=n.c0&&e<=n.c1),A=(s,t,e)=>s.hyperlinks?.find(n=>m(n,t,e))??null;function O(s,t,e){const n=[];for(const i of s??[]){const c=(i.ref??"").split(/\s+/).filter(Boolean).map(o);if(!c.some(r=>r&&t>=r.r0&&t<=r.r1&&e>=r.c0&&e<=r.c1)){n.push(i);continue}const f=c.flatMap(r=>!r||t<r.r0||t>r.r1||e<r.c0||e>r.c1?r?[r]:[]:[{r0:r.r0,c0:r.c0,r1:t-1,c1:r.c1},{r0:t+1,c0:r.c0,r1:r.r1,c1:r.c1},{r0:t,c0:r.c0,r1:t,c1:e-1},{r0:t,c0:e+1,r1:t,c1:r.c1}].filter(a=>a.r0<=a.r1&&a.c0<=a.c1));for(const r of f)n.push({...i,ref:l(r)})}return n}const d=s=>/^[^\s@:]+@[^\s@:/]+\.[^\s@:/]+$/.test(s),u=s=>{const t=s.trim();return/^sjs:\/\//i.test(t)?{location:t.replace(/^sjs:\/\//i,"")}:/^[a-z][a-z0-9+.-]*:/i.test(t)?{target:t}:/^www\./i.test(t)?{target:`http://${t}`}:d(t)?{target:`mailto:${t}`}:/^(?:'[^']+'|[^!\s]+)!/.test(t)||o(t)?{location:t}:{target:t}};function $(s,t,e,n){if(!(t.kind(e,n)&p))return null;const i=s.editText(t,e,n),c=/^=\s*HYPERLINK\(\s*(?:"((?:[^"]|"")*)"|(\$?[A-Za-z]{1,3}\$?\d+))\s*[,)]/i.exec(i);if(!c)return null;if(c[1]!==void 0)return u(c[1].replace(/""/g,'"').replace(/^#/,""));const f=o(c[2]);if(!f)return null;const r=s.editText(t,f.r0,f.c0);return r?u(r.replace(/^#/,"")):null}export{L as LINK_COLOR,k as VISITED_COLOR,$ as formulaLink,d as isEmailAddress,A as linkAt,O as linksWithoutCell,u as normalizeAddress};
|