@m3ui-vue/m3ui-vue 1.7.0 → 1.8.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/dist/API.md +578 -3
- package/dist/{MColorPickerModal-BKM1CHxr.js → MColorPickerModal-H8nuX0Wu.js} +3 -4
- package/dist/{MColorPickerModal-BKM1CHxr.js.map → MColorPickerModal-H8nuX0Wu.js.map} +1 -1
- package/dist/MDialog-B42Mhn8W.js +331 -0
- package/dist/MDialog-B42Mhn8W.js.map +1 -0
- package/dist/{MListItem-BU5KDRCB.js → MListItem-DiOAxaN7.js} +102 -102
- package/dist/{MListItem-BU5KDRCB.js.map → MListItem-DiOAxaN7.js.map} +1 -1
- package/dist/{MLoadingIndicator-RykOo5tf.js → MLoadingIndicator-CuTZYFFj.js} +2 -2
- package/dist/{MLoadingIndicator-RykOo5tf.js.map → MLoadingIndicator-CuTZYFFj.js.map} +1 -1
- package/dist/{MSeekBar-B_Y3MpVz.js → MSeekBar-BCDQTx2t.js} +2 -2
- package/dist/{MSeekBar-B_Y3MpVz.js.map → MSeekBar-BCDQTx2t.js.map} +1 -1
- package/dist/{MSegmentedButton-CiOOY1-N.js → MSegmentedButton-BXzRsg1S.js} +2 -2
- package/dist/{MSegmentedButton-CiOOY1-N.js.map → MSegmentedButton-BXzRsg1S.js.map} +1 -1
- package/dist/MSignaturePad-BTqGaPXA.js +313 -0
- package/dist/MSignaturePad-BTqGaPXA.js.map +1 -0
- package/dist/{MSlider-BCeVIxcq.js → MSlider-D_O8J9YH.js} +3 -3
- package/dist/{MSlider-BCeVIxcq.js.map → MSlider-D_O8J9YH.js.map} +1 -1
- package/dist/{MSpinner-Cs03qoqE.js → MSpinner-UCdtSOHP.js} +2 -2
- package/dist/{MSpinner-Cs03qoqE.js.map → MSpinner-UCdtSOHP.js.map} +1 -1
- package/dist/{MTextField-NaFbMkjv.js → MTextField-CYk9yFvi.js} +3 -3
- package/dist/{MTextField-NaFbMkjv.js.map → MTextField-CYk9yFvi.js.map} +1 -1
- package/dist/{_useFieldValidation-Bz34IAQY.js → _useFieldValidation-B0B44M_t.js} +2 -2
- package/dist/{_useFieldValidation-Bz34IAQY.js.map → _useFieldValidation-B0B44M_t.js.map} +1 -1
- package/dist/api.json +1 -1
- package/dist/code-editor.js +2 -2
- package/dist/components/MFormBuilder.vue.d.ts +22 -0
- package/dist/components/MFormRenderer.vue.d.ts +151 -0
- package/dist/components/MMapRoute.vue.d.ts +13 -5
- package/dist/components/MPdfSigner.vue.d.ts +499 -0
- package/dist/components/MPdfViewer.vue.d.ts +12 -0
- package/dist/components/MPosKeypad.vue.d.ts +1 -1
- package/dist/components/MSpreadsheet.vue.d.ts +137 -0
- package/dist/components/MStack.vue.d.ts +1 -1
- package/dist/composables/pdfSign.d.ts +52 -0
- package/dist/composables/spreadsheetFormula.d.ts +55 -0
- package/dist/composables/useLocale.d.ts +154 -0
- package/dist/draw.js +2 -2
- package/dist/flow.js +1 -1
- package/dist/gantt.js +2 -2
- package/dist/index.d.ts +7 -0
- package/dist/locales/index.js +539 -0
- package/dist/locales/index.js.map +1 -1
- package/dist/m3ui-vue.css +1 -1
- package/dist/m3ui.js +16988 -15064
- package/dist/m3ui.js.map +1 -1
- package/dist/map.js +601 -585
- package/dist/map.js.map +1 -1
- package/dist/media.js +4 -4
- package/dist/pdf.d.ts +3 -0
- package/dist/pdf.js +1228 -687
- package/dist/pdf.js.map +1 -1
- package/dist/rich-text-editor.js +12 -13
- package/dist/rich-text-editor.js.map +1 -1
- package/dist/styles.css +1 -1
- package/dist/{useLocale-Dh1xZZ8i.js → useLocale-DL96OFgr.js} +78 -1
- package/dist/useLocale-DL96OFgr.js.map +1 -0
- package/package.json +5 -1
- package/src/__tests__/MFormRenderer.test.ts +157 -0
- package/src/__tests__/MMapRoute.test.ts +34 -0
- package/src/__tests__/MPdfSigner.test.ts +175 -0
- package/src/__tests__/MSpreadsheet.test.ts +223 -0
- package/src/__tests__/spreadsheetFormula.test.ts +77 -0
- package/src/__tests__/ssr.test.ts +3 -0
- package/src/components/MFormBuilder.vue +417 -0
- package/src/components/MFormRenderer.vue +324 -0
- package/src/components/MMapRoute.vue +64 -11
- package/src/components/MPdfSigner.vue +433 -0
- package/src/components/MPdfViewer.vue +12 -0
- package/src/components/MSpreadsheet.vue +992 -0
- package/src/composables/pdfSign.ts +141 -0
- package/src/composables/spreadsheetFormula.ts +459 -0
- package/src/composables/useLocale.ts +231 -0
- package/src/index.ts +7 -0
- package/src/locales/de.ts +77 -0
- package/src/locales/es.ts +77 -0
- package/src/locales/fr.ts +77 -0
- package/src/locales/ja.ts +77 -0
- package/src/locales/ko.ts +77 -0
- package/src/locales/pt.ts +77 -0
- package/src/locales/zh.ts +77 -0
- package/src/pdf.ts +3 -0
- package/dist/MButton-CN3wYwIG.js +0 -171
- package/dist/MButton-CN3wYwIG.js.map +0 -1
- package/dist/MDialog-1LAk9WAO.js +0 -167
- package/dist/MDialog-1LAk9WAO.js.map +0 -1
- package/dist/MProgressBar-BWly1UKN.js +0 -179
- package/dist/MProgressBar-BWly1UKN.js.map +0 -1
- package/dist/useLocale-Dh1xZZ8i.js.map +0 -1
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
// Writing filled signature fields into a PDF (MPdfSigner). Uses pdf-lib, an optional peer dependency loaded only
|
|
2
|
+
// when a document is saved
|
|
3
|
+
|
|
4
|
+
/** A field placed on a page to sign or fill */
|
|
5
|
+
export interface PdfSignField {
|
|
6
|
+
id: string
|
|
7
|
+
type: 'signature' | 'initials' | 'name' | 'date' | 'text' | 'checkbox'
|
|
8
|
+
/** 1-based page */
|
|
9
|
+
page: number
|
|
10
|
+
/** Where it is, as fractions (0–1) of the page as shown (its own rotation included): left, top, width, height */
|
|
11
|
+
x: number
|
|
12
|
+
y: number
|
|
13
|
+
width: number
|
|
14
|
+
height: number
|
|
15
|
+
/** What it asks for (shown in the empty field, and to screen readers) */
|
|
16
|
+
label?: string
|
|
17
|
+
/** Must be filled before the document is complete. Default true for signature fields */
|
|
18
|
+
required?: boolean
|
|
19
|
+
/** Who fills it, for documents several people sign; `signer` on MPdfSigner picks whose fields are active */
|
|
20
|
+
signer?: string
|
|
21
|
+
/** What it holds: a PNG data URL for a signature or initials, text otherwise, `'true'` for a ticked checkbox */
|
|
22
|
+
value?: string
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Whether a field needs filling and is empty */
|
|
26
|
+
export const fieldMissing = (f: PdfSignField) => (f.required ?? (f.type === 'signature' || f.type === 'initials')) && !f.value
|
|
27
|
+
|
|
28
|
+
type Rect = { x: number; y: number; width: number; height: number }
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* A rectangle on the page as shown (top-left origin, y down, in points) to PDF user space (bottom-left origin):
|
|
32
|
+
* where to anchor something drawn upright on screen, and the rotation to draw it with, for a page with its own
|
|
33
|
+
* `/Rotate` and a crop box. `box` is the crop box, `rotate` the page's rotation in degrees
|
|
34
|
+
*/
|
|
35
|
+
export function shownToUser(r: Rect, box: Rect, rotate: number): { x: number; y: number; rotate: number } {
|
|
36
|
+
const rot = ((rotate % 360) + 360) % 360
|
|
37
|
+
// The shown rectangle's bottom-left corner, mapped back into the unrotated page
|
|
38
|
+
const sx = r.x
|
|
39
|
+
const sy = r.y + r.height
|
|
40
|
+
let ux: number
|
|
41
|
+
let uy: number
|
|
42
|
+
if (rot === 90) { ux = sy; uy = sx }
|
|
43
|
+
else if (rot === 180) { ux = box.width - sx; uy = sy }
|
|
44
|
+
else if (rot === 270) { ux = box.width - sy; uy = box.height - sx }
|
|
45
|
+
else { ux = sx; uy = box.height - sy }
|
|
46
|
+
return { x: box.x + ux, y: box.y + uy, rotate: rot }
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Draws a field's value into a PNG (text in the page's font stack; any script works, unlike PDF standard fonts) */
|
|
50
|
+
async function fieldImage(f: PdfSignField, wPt: number, hPt: number, font: string): Promise<Uint8Array | null> {
|
|
51
|
+
if (!f.value) return null
|
|
52
|
+
if ((f.type === 'signature' || f.type === 'initials') && f.value.startsWith('data:image/png')) return dataUrlBytes(f.value)
|
|
53
|
+
const ratio = 4 // px per point: sharp when printed
|
|
54
|
+
const canvas = document.createElement('canvas')
|
|
55
|
+
canvas.width = Math.max(1, Math.round(wPt * ratio))
|
|
56
|
+
canvas.height = Math.max(1, Math.round(hPt * ratio))
|
|
57
|
+
const ctx = canvas.getContext('2d')
|
|
58
|
+
if (!ctx) return null
|
|
59
|
+
ctx.fillStyle = '#111'
|
|
60
|
+
ctx.textBaseline = 'middle'
|
|
61
|
+
if (f.type === 'checkbox') {
|
|
62
|
+
if (f.value !== 'true') return null
|
|
63
|
+
const s = Math.min(canvas.width, canvas.height)
|
|
64
|
+
ctx.lineWidth = s * 0.12
|
|
65
|
+
ctx.lineCap = 'round'
|
|
66
|
+
ctx.lineJoin = 'round'
|
|
67
|
+
ctx.strokeStyle = '#111'
|
|
68
|
+
ctx.beginPath()
|
|
69
|
+
ctx.moveTo(s * 0.2, s * 0.55)
|
|
70
|
+
ctx.lineTo(s * 0.42, s * 0.76)
|
|
71
|
+
ctx.lineTo(s * 0.82, s * 0.26)
|
|
72
|
+
ctx.stroke()
|
|
73
|
+
} else {
|
|
74
|
+
let size = canvas.height * 0.62
|
|
75
|
+
ctx.font = `${size}px ${font}`
|
|
76
|
+
while (size > 6 && ctx.measureText(f.value).width > canvas.width * 0.96) {
|
|
77
|
+
size *= 0.92
|
|
78
|
+
ctx.font = `${size}px ${font}`
|
|
79
|
+
}
|
|
80
|
+
ctx.fillText(f.value, canvas.width * 0.02, canvas.height / 2)
|
|
81
|
+
}
|
|
82
|
+
const blob = await new Promise<Blob | null>((res) => canvas.toBlob(res, 'image/png'))
|
|
83
|
+
return blob ? new Uint8Array(await blob.arrayBuffer()) : null
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function dataUrlBytes(url: string): Uint8Array {
|
|
87
|
+
const b64 = url.slice(url.indexOf(',') + 1)
|
|
88
|
+
const bin = atob(b64)
|
|
89
|
+
const out = new Uint8Array(bin.length)
|
|
90
|
+
for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i)
|
|
91
|
+
return out
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export interface SignPdfOptions {
|
|
95
|
+
/** The font for text fields (a CSS font list). Default the page's sans-serif */
|
|
96
|
+
font?: string
|
|
97
|
+
/** Written into the document's metadata */
|
|
98
|
+
producer?: string
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Writes the filled fields into a copy of the PDF and returns its bytes: signatures and initials as the images
|
|
103
|
+
* drawn, text, dates and ticks drawn the same way. A visual signature (what an e-signature flow shows and prints),
|
|
104
|
+
* not a cryptographic one: for a certificate-based digital signature (PAdES), sign the result on your server.
|
|
105
|
+
* Needs the `pdf-lib` package
|
|
106
|
+
*/
|
|
107
|
+
export async function signPdf(pdf: ArrayBuffer | Uint8Array, fields: PdfSignField[], options: SignPdfOptions = {}): Promise<Uint8Array> {
|
|
108
|
+
const { PDFDocument, degrees } = await import('pdf-lib')
|
|
109
|
+
const doc = await PDFDocument.load(pdf)
|
|
110
|
+
const pages = doc.getPages()
|
|
111
|
+
const font = options.font ?? 'system-ui, sans-serif'
|
|
112
|
+
for (const f of fields) {
|
|
113
|
+
const page = pages[f.page - 1]
|
|
114
|
+
if (!page || !f.value) continue
|
|
115
|
+
const box = page.getCropBox()
|
|
116
|
+
const rot = page.getRotation().angle
|
|
117
|
+
const swap = ((rot % 180) + 180) % 180 !== 0
|
|
118
|
+
const shownW = swap ? box.height : box.width
|
|
119
|
+
const shownH = swap ? box.width : box.height
|
|
120
|
+
const rect = { x: f.x * shownW, y: f.y * shownH, width: f.width * shownW, height: f.height * shownH }
|
|
121
|
+
const png = await fieldImage(f, rect.width, rect.height, font)
|
|
122
|
+
if (!png) continue
|
|
123
|
+
const image = await doc.embedPng(png)
|
|
124
|
+
// Signatures keep their shape, centered in the field
|
|
125
|
+
let { width, height } = rect
|
|
126
|
+
let dx = 0
|
|
127
|
+
let dy = 0
|
|
128
|
+
if (f.type === 'signature' || f.type === 'initials') {
|
|
129
|
+
const s = Math.min(rect.width / image.width, rect.height / image.height)
|
|
130
|
+
width = image.width * s
|
|
131
|
+
height = image.height * s
|
|
132
|
+
dx = (rect.width - width) / 2
|
|
133
|
+
dy = (rect.height - height) / 2
|
|
134
|
+
}
|
|
135
|
+
const at = shownToUser({ x: rect.x + dx, y: rect.y + dy, width, height }, { x: box.x, y: box.y, width: box.width, height: box.height }, rot)
|
|
136
|
+
page.drawImage(image, { x: at.x, y: at.y, width, height, rotate: degrees(at.rotate) })
|
|
137
|
+
}
|
|
138
|
+
if (options.producer) doc.setProducer(options.producer)
|
|
139
|
+
doc.setModificationDate(new Date())
|
|
140
|
+
return doc.save()
|
|
141
|
+
}
|
|
@@ -0,0 +1,459 @@
|
|
|
1
|
+
// Spreadsheet formulas for MSpreadsheet: A1 references, ranges, the usual operators and functions. Pure functions,
|
|
2
|
+
// no Vue: also usable on their own (to evaluate a saved sheet on the server, say)
|
|
3
|
+
|
|
4
|
+
/** What a cell holds: what was typed. A string starting with `=` is a formula */
|
|
5
|
+
export type SpreadsheetCell = string | number | boolean | null
|
|
6
|
+
|
|
7
|
+
/** A formula error, shown in the cell as its code (`#DIV/0!`, `#REF!`…) */
|
|
8
|
+
export class FormulaError {
|
|
9
|
+
constructor(public code: '#DIV/0!' | '#REF!' | '#NAME?' | '#VALUE!' | '#CIRC!' | '#ERROR!' | '#N/A') {}
|
|
10
|
+
toString() { return this.code }
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** What a cell shows once its formula is worked out */
|
|
14
|
+
export type SpreadsheetValue = number | string | boolean | null | FormulaError
|
|
15
|
+
|
|
16
|
+
// ── A1 notation ──
|
|
17
|
+
|
|
18
|
+
/** `0 → A`, `25 → Z`, `26 → AA` */
|
|
19
|
+
export function columnName(index: number): string {
|
|
20
|
+
let s = ''
|
|
21
|
+
let n = index + 1
|
|
22
|
+
while (n > 0) {
|
|
23
|
+
const m = (n - 1) % 26
|
|
24
|
+
s = String.fromCharCode(65 + m) + s
|
|
25
|
+
n = Math.floor((n - 1) / 26)
|
|
26
|
+
}
|
|
27
|
+
return s
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** `A → 0`, `AA → 26` */
|
|
31
|
+
export function columnIndex(name: string): number {
|
|
32
|
+
let n = 0
|
|
33
|
+
for (const ch of name.toUpperCase()) n = n * 26 + (ch.charCodeAt(0) - 64)
|
|
34
|
+
return n - 1
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** `{ row: 0, col: 0 } → A1` */
|
|
38
|
+
export function cellName(row: number, col: number): string {
|
|
39
|
+
return `${columnName(col)}${row + 1}`
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** `B3 → { row: 2, col: 1 }`, or null if it isn't a reference */
|
|
43
|
+
export function parseCellName(ref: string): { row: number; col: number } | null {
|
|
44
|
+
const m = /^\$?([A-Za-z]{1,3})\$?(\d+)$/.exec(ref.trim())
|
|
45
|
+
if (!m) return null
|
|
46
|
+
const row = Number(m[2]) - 1
|
|
47
|
+
return row < 0 ? null : { row, col: columnIndex(m[1]!) }
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// ── tokens ──
|
|
51
|
+
|
|
52
|
+
type Token =
|
|
53
|
+
| { t: 'num'; v: number }
|
|
54
|
+
| { t: 'str'; v: string }
|
|
55
|
+
| { t: 'ref'; col: number; row: number; absCol: boolean; absRow: boolean; text: string; start: number; end: number }
|
|
56
|
+
| { t: 'id'; v: string }
|
|
57
|
+
| { t: 'op'; v: string }
|
|
58
|
+
|
|
59
|
+
const REF = /^(\$?)([A-Za-z]{1,3})(\$?)(\d+)(?![A-Za-z0-9_(])/
|
|
60
|
+
|
|
61
|
+
function tokenize(src: string): Token[] {
|
|
62
|
+
const out: Token[] = []
|
|
63
|
+
let i = 0
|
|
64
|
+
while (i < src.length) {
|
|
65
|
+
const ch = src[i]!
|
|
66
|
+
if (/\s/.test(ch)) { i++; continue }
|
|
67
|
+
if (/[0-9.]/.test(ch)) {
|
|
68
|
+
const m = /^(\d+\.?\d*|\.\d+)(e[+-]?\d+)?/i.exec(src.slice(i))
|
|
69
|
+
if (!m) throw new FormulaError('#ERROR!')
|
|
70
|
+
out.push({ t: 'num', v: Number(m[0]) })
|
|
71
|
+
i += m[0].length
|
|
72
|
+
continue
|
|
73
|
+
}
|
|
74
|
+
if (ch === '"') {
|
|
75
|
+
let s = ''
|
|
76
|
+
i++
|
|
77
|
+
for (;;) {
|
|
78
|
+
if (i >= src.length) throw new FormulaError('#ERROR!')
|
|
79
|
+
if (src[i] === '"') {
|
|
80
|
+
if (src[i + 1] === '"') { s += '"'; i += 2; continue }
|
|
81
|
+
i++
|
|
82
|
+
break
|
|
83
|
+
}
|
|
84
|
+
s += src[i++]
|
|
85
|
+
}
|
|
86
|
+
out.push({ t: 'str', v: s })
|
|
87
|
+
continue
|
|
88
|
+
}
|
|
89
|
+
if (/[A-Za-z$_]/.test(ch)) {
|
|
90
|
+
const ref = REF.exec(src.slice(i))
|
|
91
|
+
if (ref) {
|
|
92
|
+
out.push({ t: 'ref', absCol: !!ref[1], col: columnIndex(ref[2]!), absRow: !!ref[3], row: Number(ref[4]) - 1, text: ref[0], start: i, end: i + ref[0].length })
|
|
93
|
+
i += ref[0].length
|
|
94
|
+
continue
|
|
95
|
+
}
|
|
96
|
+
const m = /^[A-Za-z_][A-Za-z0-9_.]*/.exec(src.slice(i))
|
|
97
|
+
if (!m) throw new FormulaError('#ERROR!')
|
|
98
|
+
out.push({ t: 'id', v: m[0].toUpperCase() })
|
|
99
|
+
i += m[0].length
|
|
100
|
+
continue
|
|
101
|
+
}
|
|
102
|
+
const two = src.slice(i, i + 2)
|
|
103
|
+
if (two === '<=' || two === '>=' || two === '<>') { out.push({ t: 'op', v: two }); i += 2; continue }
|
|
104
|
+
if ('+-*/^&=<>(),;:%'.includes(ch)) { out.push({ t: 'op', v: ch === ';' ? ',' : ch }); i++; continue }
|
|
105
|
+
throw new FormulaError('#ERROR!')
|
|
106
|
+
}
|
|
107
|
+
return out
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// ── parse ──
|
|
111
|
+
|
|
112
|
+
type Node =
|
|
113
|
+
| { k: 'num'; v: number }
|
|
114
|
+
| { k: 'str'; v: string }
|
|
115
|
+
| { k: 'bool'; v: boolean }
|
|
116
|
+
| { k: 'ref'; row: number; col: number }
|
|
117
|
+
| { k: 'range'; r1: number; c1: number; r2: number; c2: number }
|
|
118
|
+
| { k: 'un'; op: string; a: Node }
|
|
119
|
+
| { k: 'bin'; op: string; a: Node; b: Node }
|
|
120
|
+
| { k: 'pct'; a: Node }
|
|
121
|
+
| { k: 'call'; name: string; args: Node[] }
|
|
122
|
+
|
|
123
|
+
function parse(tokens: Token[]): Node {
|
|
124
|
+
let p = 0
|
|
125
|
+
const peek = () => tokens[p]
|
|
126
|
+
const isOp = (v: string) => { const t = tokens[p]; return t?.t === 'op' && t.v === v }
|
|
127
|
+
const expect = (v: string) => { if (!isOp(v)) throw new FormulaError('#ERROR!'); p++ }
|
|
128
|
+
|
|
129
|
+
const binary = (next: () => Node, ops: string[]) => (): Node => {
|
|
130
|
+
let a = next()
|
|
131
|
+
for (;;) {
|
|
132
|
+
const t = peek()
|
|
133
|
+
if (t?.t === 'op' && ops.includes(t.v)) { p++; a = { k: 'bin', op: t.v, a, b: next() } }
|
|
134
|
+
else return a
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
const primary = (): Node => {
|
|
138
|
+
const t = tokens[p++]
|
|
139
|
+
if (!t) throw new FormulaError('#ERROR!')
|
|
140
|
+
if (t.t === 'num') return { k: 'num', v: t.v }
|
|
141
|
+
if (t.t === 'str') return { k: 'str', v: t.v }
|
|
142
|
+
if (t.t === 'ref') {
|
|
143
|
+
if (isOp(':')) {
|
|
144
|
+
p++
|
|
145
|
+
const b = tokens[p++]
|
|
146
|
+
if (b?.t !== 'ref') throw new FormulaError('#ERROR!')
|
|
147
|
+
return { k: 'range', r1: Math.min(t.row, b.row), c1: Math.min(t.col, b.col), r2: Math.max(t.row, b.row), c2: Math.max(t.col, b.col) }
|
|
148
|
+
}
|
|
149
|
+
return { k: 'ref', row: t.row, col: t.col }
|
|
150
|
+
}
|
|
151
|
+
if (t.t === 'id') {
|
|
152
|
+
if (isOp('(')) {
|
|
153
|
+
p++
|
|
154
|
+
const args: Node[] = []
|
|
155
|
+
if (!isOp(')')) {
|
|
156
|
+
for (;;) {
|
|
157
|
+
args.push(expr())
|
|
158
|
+
if (isOp(',')) { p++; continue }
|
|
159
|
+
break
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
expect(')')
|
|
163
|
+
return { k: 'call', name: t.v, args }
|
|
164
|
+
}
|
|
165
|
+
if (t.v === 'TRUE' || t.v === 'FALSE') return { k: 'bool', v: t.v === 'TRUE' }
|
|
166
|
+
throw new FormulaError('#NAME?')
|
|
167
|
+
}
|
|
168
|
+
if (t.t === 'op' && t.v === '(') {
|
|
169
|
+
const e = expr()
|
|
170
|
+
expect(')')
|
|
171
|
+
return e
|
|
172
|
+
}
|
|
173
|
+
throw new FormulaError('#ERROR!')
|
|
174
|
+
}
|
|
175
|
+
const postfix = (): Node => {
|
|
176
|
+
let a = primary()
|
|
177
|
+
while (isOp('%')) { p++; a = { k: 'pct', a } }
|
|
178
|
+
return a
|
|
179
|
+
}
|
|
180
|
+
const unary = (): Node => {
|
|
181
|
+
if (isOp('-') || isOp('+')) {
|
|
182
|
+
const op = (tokens[p++] as { v: string }).v
|
|
183
|
+
return { k: 'un', op, a: unary() }
|
|
184
|
+
}
|
|
185
|
+
return postfix()
|
|
186
|
+
}
|
|
187
|
+
const power = binary(unary, ['^'])
|
|
188
|
+
const term = binary(power, ['*', '/'])
|
|
189
|
+
const additive = binary(term, ['+', '-'])
|
|
190
|
+
const concat = binary(additive, ['&'])
|
|
191
|
+
const comparison = binary(concat, ['=', '<>', '<', '>', '<=', '>='])
|
|
192
|
+
const expr = comparison
|
|
193
|
+
|
|
194
|
+
const node = expr()
|
|
195
|
+
if (p < tokens.length) throw new FormulaError('#ERROR!')
|
|
196
|
+
return node
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
const parsed = new Map<string, Node | FormulaError>()
|
|
200
|
+
function compile(formula: string): Node | FormulaError {
|
|
201
|
+
let n = parsed.get(formula)
|
|
202
|
+
if (!n) {
|
|
203
|
+
try { n = parse(tokenize(formula)) } catch (e) { n = e instanceof FormulaError ? e : new FormulaError('#ERROR!') }
|
|
204
|
+
if (parsed.size > 5000) parsed.clear()
|
|
205
|
+
parsed.set(formula, n)
|
|
206
|
+
}
|
|
207
|
+
return n
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
// ── evaluate ──
|
|
211
|
+
|
|
212
|
+
type Val = SpreadsheetValue
|
|
213
|
+
type Arg = Val | Val[]
|
|
214
|
+
|
|
215
|
+
function num(v: Val): number {
|
|
216
|
+
if (v instanceof FormulaError) throw v
|
|
217
|
+
if (v == null || v === '') return 0
|
|
218
|
+
if (typeof v === 'number') return v
|
|
219
|
+
if (typeof v === 'boolean') return v ? 1 : 0
|
|
220
|
+
const n = Number(v)
|
|
221
|
+
if (Number.isNaN(n)) throw new FormulaError('#VALUE!')
|
|
222
|
+
return n
|
|
223
|
+
}
|
|
224
|
+
function str(v: Val): string {
|
|
225
|
+
if (v instanceof FormulaError) throw v
|
|
226
|
+
if (v == null) return ''
|
|
227
|
+
if (typeof v === 'boolean') return v ? 'TRUE' : 'FALSE'
|
|
228
|
+
return typeof v === 'number' ? formatNumber(v) : v
|
|
229
|
+
}
|
|
230
|
+
function bool(v: Val): boolean {
|
|
231
|
+
if (v instanceof FormulaError) throw v
|
|
232
|
+
if (typeof v === 'string') {
|
|
233
|
+
const u = v.toUpperCase()
|
|
234
|
+
if (u === 'TRUE') return true
|
|
235
|
+
if (u === 'FALSE' || u === '') return false
|
|
236
|
+
throw new FormulaError('#VALUE!')
|
|
237
|
+
}
|
|
238
|
+
return !!v
|
|
239
|
+
}
|
|
240
|
+
/** All the numbers in some arguments: a range's text and blanks are skipped, a direct argument is converted */
|
|
241
|
+
function numbers(args: Arg[]): number[] {
|
|
242
|
+
const out: number[] = []
|
|
243
|
+
for (const a of args) {
|
|
244
|
+
if (Array.isArray(a)) for (const v of a) {
|
|
245
|
+
if (v instanceof FormulaError) throw v
|
|
246
|
+
if (typeof v === 'number') out.push(v)
|
|
247
|
+
}
|
|
248
|
+
else out.push(num(a))
|
|
249
|
+
}
|
|
250
|
+
return out
|
|
251
|
+
}
|
|
252
|
+
const flat = (args: Arg[]): Val[] => args.flatMap((a) => (Array.isArray(a) ? a : [a]))
|
|
253
|
+
const scalar = (a: Arg | undefined): Val => {
|
|
254
|
+
if (a === undefined) throw new FormulaError('#VALUE!')
|
|
255
|
+
if (Array.isArray(a)) throw new FormulaError('#VALUE!')
|
|
256
|
+
return a
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
function compare(a: Val, b: Val): number {
|
|
260
|
+
const ta = typeof a === 'number' || a == null ? 0 : typeof a === 'string' ? 1 : 2
|
|
261
|
+
const tb = typeof b === 'number' || b == null ? 0 : typeof b === 'string' ? 1 : 2
|
|
262
|
+
if (a == null && typeof b === 'string') return ''.localeCompare(b)
|
|
263
|
+
if (b == null && typeof a === 'string') return a.localeCompare('')
|
|
264
|
+
if (ta !== tb) return ta - tb
|
|
265
|
+
if (ta === 1) return (a as string).toLowerCase().localeCompare((b as string).toLowerCase())
|
|
266
|
+
return num(a) - num(b)
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/** The functions a formula can call. Add your own with `functions` on MSpreadsheet */
|
|
270
|
+
export type SpreadsheetFunction = (args: Arg[]) => Val
|
|
271
|
+
|
|
272
|
+
const round = (n: number, d: number) => { const f = 10 ** d; return Math.round(n * f) / f }
|
|
273
|
+
|
|
274
|
+
export const spreadsheetFunctions: Record<string, SpreadsheetFunction> = {
|
|
275
|
+
SUM: (a) => numbers(a).reduce((s, n) => s + n, 0),
|
|
276
|
+
AVERAGE: (a) => { const n = numbers(a); if (!n.length) throw new FormulaError('#DIV/0!'); return n.reduce((s, x) => s + x, 0) / n.length },
|
|
277
|
+
MIN: (a) => { const n = numbers(a); return n.length ? Math.min(...n) : 0 },
|
|
278
|
+
MAX: (a) => { const n = numbers(a); return n.length ? Math.max(...n) : 0 },
|
|
279
|
+
PRODUCT: (a) => numbers(a).reduce((s, n) => s * n, 1),
|
|
280
|
+
COUNT: (a) => flat(a).filter((v) => typeof v === 'number').length,
|
|
281
|
+
COUNTA: (a) => flat(a).filter((v) => v != null && v !== '').length,
|
|
282
|
+
COUNTBLANK: (a) => flat(a).filter((v) => v == null || v === '').length,
|
|
283
|
+
ROUND: (a) => round(num(scalar(a[0])), a[1] === undefined ? 0 : num(scalar(a[1]))),
|
|
284
|
+
ABS: (a) => Math.abs(num(scalar(a[0]))),
|
|
285
|
+
SQRT: (a) => { const n = num(scalar(a[0])); if (n < 0) throw new FormulaError('#VALUE!'); return Math.sqrt(n) },
|
|
286
|
+
POWER: (a) => num(scalar(a[0])) ** num(scalar(a[1])),
|
|
287
|
+
MOD: (a) => { const d = num(scalar(a[1])); if (d === 0) throw new FormulaError('#DIV/0!'); const n = num(scalar(a[0])); return n - d * Math.floor(n / d) },
|
|
288
|
+
INT: (a) => Math.floor(num(scalar(a[0]))),
|
|
289
|
+
IF: (a) => (bool(scalar(a[0])) ? (a[1] === undefined ? true : scalar(a[1])) : (a[2] === undefined ? false : scalar(a[2]))),
|
|
290
|
+
IFERROR: (a) => { const v = a[0]; return v instanceof FormulaError ? scalar(a[1]) : scalar(v) },
|
|
291
|
+
AND: (a) => flat(a).every((v) => bool(v)),
|
|
292
|
+
OR: (a) => flat(a).some((v) => bool(v)),
|
|
293
|
+
NOT: (a) => !bool(scalar(a[0])),
|
|
294
|
+
CONCAT: (a) => flat(a).map(str).join(''),
|
|
295
|
+
CONCATENATE: (a) => flat(a).map(str).join(''),
|
|
296
|
+
LEN: (a) => str(scalar(a[0])).length,
|
|
297
|
+
UPPER: (a) => str(scalar(a[0])).toUpperCase(),
|
|
298
|
+
LOWER: (a) => str(scalar(a[0])).toLowerCase(),
|
|
299
|
+
TRIM: (a) => str(scalar(a[0])).trim().replace(/\s+/g, ' '),
|
|
300
|
+
LEFT: (a) => str(scalar(a[0])).slice(0, a[1] === undefined ? 1 : num(scalar(a[1]))),
|
|
301
|
+
RIGHT: (a) => { const s = str(scalar(a[0])); const n = a[1] === undefined ? 1 : num(scalar(a[1])); return n ? s.slice(-n) : '' },
|
|
302
|
+
SUMIF: (a) => {
|
|
303
|
+
const range = Array.isArray(a[0]) ? a[0] : [scalar(a[0])]
|
|
304
|
+
const sums = a[2] === undefined ? range : Array.isArray(a[2]) ? a[2] : [a[2]]
|
|
305
|
+
const test = criterion(scalar(a[1]))
|
|
306
|
+
let s = 0
|
|
307
|
+
range.forEach((v, i) => { const x = sums[i]; if (test(v) && typeof x === 'number') s += x })
|
|
308
|
+
return s
|
|
309
|
+
},
|
|
310
|
+
COUNTIF: (a) => { const range = Array.isArray(a[0]) ? a[0] : [scalar(a[0])]; const test = criterion(scalar(a[1])); return range.filter(test).length },
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
/** `">5"`, `"<>x"`, `"apple"`, `3`: a condition for SUMIF/COUNTIF */
|
|
314
|
+
function criterion(c: Val): (v: Val) => boolean {
|
|
315
|
+
if (typeof c === 'string') {
|
|
316
|
+
const m = /^(<=|>=|<>|<|>|=)?(.*)$/.exec(c)!
|
|
317
|
+
const op = m[1] ?? '='
|
|
318
|
+
const raw = m[2]!
|
|
319
|
+
const target: Val = raw !== '' && !Number.isNaN(Number(raw)) ? Number(raw) : raw
|
|
320
|
+
return (v) => {
|
|
321
|
+
if (v instanceof FormulaError) return false
|
|
322
|
+
const d = compare(v, target)
|
|
323
|
+
return op === '=' ? d === 0 : op === '<>' ? d !== 0 : op === '<' ? d < 0 : op === '>' ? d > 0 : op === '<=' ? d <= 0 : d >= 0
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
return (v) => !(v instanceof FormulaError) && compare(v, c) === 0
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
/** Where a formula reads cells from: their values (formulas already worked out) */
|
|
330
|
+
export interface FormulaContext {
|
|
331
|
+
get(row: number, col: number): Val
|
|
332
|
+
functions?: Record<string, SpreadsheetFunction>
|
|
333
|
+
/** Rows and columns the sheet has: a reference outside them is `#REF!` */
|
|
334
|
+
rows?: number
|
|
335
|
+
cols?: number
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
function evalNode(n: Node, ctx: FormulaContext): Arg {
|
|
339
|
+
switch (n.k) {
|
|
340
|
+
case 'num': return n.v
|
|
341
|
+
case 'str': return n.v
|
|
342
|
+
case 'bool': return n.v
|
|
343
|
+
case 'ref':
|
|
344
|
+
if ((ctx.rows != null && n.row >= ctx.rows) || (ctx.cols != null && n.col >= ctx.cols)) throw new FormulaError('#REF!')
|
|
345
|
+
return ctx.get(n.row, n.col)
|
|
346
|
+
case 'range': {
|
|
347
|
+
const out: Val[] = []
|
|
348
|
+
const r2 = ctx.rows != null ? Math.min(n.r2, ctx.rows - 1) : n.r2
|
|
349
|
+
const c2 = ctx.cols != null ? Math.min(n.c2, ctx.cols - 1) : n.c2
|
|
350
|
+
for (let r = n.r1; r <= r2; r++) for (let c = n.c1; c <= c2; c++) out.push(ctx.get(r, c))
|
|
351
|
+
return out
|
|
352
|
+
}
|
|
353
|
+
case 'pct': return num(scalar(evalNode(n.a, ctx))) / 100
|
|
354
|
+
case 'un': { const v = num(scalar(evalNode(n.a, ctx))); return n.op === '-' ? -v : v }
|
|
355
|
+
case 'bin': {
|
|
356
|
+
const a = scalar(evalNode(n.a, ctx))
|
|
357
|
+
const b = scalar(evalNode(n.b, ctx))
|
|
358
|
+
switch (n.op) {
|
|
359
|
+
case '+': return num(a) + num(b)
|
|
360
|
+
case '-': return num(a) - num(b)
|
|
361
|
+
case '*': return num(a) * num(b)
|
|
362
|
+
case '/': { const d = num(b); if (d === 0) throw new FormulaError('#DIV/0!'); return num(a) / d }
|
|
363
|
+
case '^': return num(a) ** num(b)
|
|
364
|
+
case '&': return str(a) + str(b)
|
|
365
|
+
default: {
|
|
366
|
+
if (a instanceof FormulaError) throw a
|
|
367
|
+
if (b instanceof FormulaError) throw b
|
|
368
|
+
const d = compare(a, b)
|
|
369
|
+
return n.op === '=' ? d === 0 : n.op === '<>' ? d !== 0 : n.op === '<' ? d < 0 : n.op === '>' ? d > 0 : n.op === '<=' ? d <= 0 : d >= 0
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
case 'call': {
|
|
374
|
+
const fn = ctx.functions?.[n.name] ?? spreadsheetFunctions[n.name]
|
|
375
|
+
if (!fn) throw new FormulaError('#NAME?')
|
|
376
|
+
// IFERROR gets its first argument's error instead of failing with it
|
|
377
|
+
const args = n.args.map((a, i) => {
|
|
378
|
+
if (n.name === 'IFERROR' && i === 0) {
|
|
379
|
+
try { return evalNode(a, ctx) } catch (e) { if (e instanceof FormulaError) return e; throw e }
|
|
380
|
+
}
|
|
381
|
+
return evalNode(a, ctx)
|
|
382
|
+
})
|
|
383
|
+
return fn(args)
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
/** Works out a formula (without its leading `=`). Errors come back as a `FormulaError`, never thrown */
|
|
389
|
+
export function evaluateFormula(formula: string, ctx: FormulaContext): SpreadsheetValue {
|
|
390
|
+
const node = compile(formula)
|
|
391
|
+
if (node instanceof FormulaError) return node
|
|
392
|
+
try {
|
|
393
|
+
const v = evalNode(node, ctx)
|
|
394
|
+
if (Array.isArray(v)) return v.length === 1 ? v[0]! : new FormulaError('#VALUE!')
|
|
395
|
+
if (typeof v === 'number' && !Number.isFinite(v)) return new FormulaError('#DIV/0!')
|
|
396
|
+
return v
|
|
397
|
+
} catch (e) {
|
|
398
|
+
if (e instanceof FormulaError) return e
|
|
399
|
+
if (e instanceof RangeError) return new FormulaError('#CIRC!')
|
|
400
|
+
return new FormulaError('#ERROR!')
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
/**
|
|
405
|
+
* Evaluates a whole sheet lazily: `value(row, col)` works a cell out the first time it's asked for (and whatever it
|
|
406
|
+
* reads), then remembers it. Circular references come out as `#CIRC!`. Make a new one when the cells change.
|
|
407
|
+
*/
|
|
408
|
+
export function createSheetEvaluator(cells: SpreadsheetCell[][], options: { functions?: Record<string, SpreadsheetFunction>; rows?: number; cols?: number } = {}) {
|
|
409
|
+
const memo = new Map<number, SpreadsheetValue>()
|
|
410
|
+
const busy = new Set<number>()
|
|
411
|
+
const width = Math.max(options.cols ?? 0, ...cells.map((r) => r?.length ?? 0), 1)
|
|
412
|
+
const ctx: FormulaContext = { get: (r, c) => value(r, c), functions: options.functions, rows: options.rows, cols: options.cols }
|
|
413
|
+
function value(row: number, col: number): SpreadsheetValue {
|
|
414
|
+
const raw = cells[row]?.[col] ?? null
|
|
415
|
+
if (typeof raw !== 'string' || raw[0] !== '=') return raw === '' ? null : raw
|
|
416
|
+
const key = row * width + col
|
|
417
|
+
if (memo.has(key)) return memo.get(key)!
|
|
418
|
+
if (busy.has(key)) throw new FormulaError('#CIRC!')
|
|
419
|
+
busy.add(key)
|
|
420
|
+
let v: SpreadsheetValue
|
|
421
|
+
try { v = evaluateFormula(raw.slice(1), ctx) } finally { busy.delete(key) }
|
|
422
|
+
// A cycle reached through this cell: everything in it is #CIRC!
|
|
423
|
+
memo.set(key, v)
|
|
424
|
+
return v
|
|
425
|
+
}
|
|
426
|
+
return {
|
|
427
|
+
value(row: number, col: number): SpreadsheetValue {
|
|
428
|
+
try { return value(row, col) } catch (e) { return e instanceof FormulaError ? e : new FormulaError('#ERROR!') }
|
|
429
|
+
},
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
/**
|
|
434
|
+
* The formula moved by some rows and columns, as when it's copied or filled into another cell: relative references
|
|
435
|
+
* move, `$`-locked parts stay. A reference pushed off the sheet becomes `#REF!`.
|
|
436
|
+
*/
|
|
437
|
+
export function shiftFormula(formula: string, dRow: number, dCol: number): string {
|
|
438
|
+
if (formula[0] !== '=') return formula
|
|
439
|
+
let tokens: Token[]
|
|
440
|
+
try { tokens = tokenize(formula.slice(1)) } catch { return formula }
|
|
441
|
+
let out = ''
|
|
442
|
+
let last = 0
|
|
443
|
+
const src = formula.slice(1)
|
|
444
|
+
for (const t of tokens) {
|
|
445
|
+
if (t.t !== 'ref') continue
|
|
446
|
+
const row = t.absRow ? t.row : t.row + dRow
|
|
447
|
+
const col = t.absCol ? t.col : t.col + dCol
|
|
448
|
+
out += src.slice(last, t.start)
|
|
449
|
+
out += row < 0 || col < 0 ? '#REF!' : `${t.absCol ? '$' : ''}${columnName(col)}${t.absRow ? '$' : ''}${row + 1}`
|
|
450
|
+
last = t.end
|
|
451
|
+
}
|
|
452
|
+
return '=' + out + src.slice(last)
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
/** A number as a cell shows it: no float noise (`0.1 + 0.2` shows 0.3) */
|
|
456
|
+
export function formatNumber(n: number): string {
|
|
457
|
+
if (Number.isInteger(n)) return String(n)
|
|
458
|
+
return String(Number(n.toPrecision(12)))
|
|
459
|
+
}
|