@mdgs/pivotjet 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +628 -3
- package/bin/pivotjet.mjs +122 -0
- package/dist/core.cjs +4926 -0
- package/dist/core.cjs.map +7 -0
- package/dist/index.cjs +7277 -0
- package/dist/index.cjs.map +7 -0
- package/dist/pivotjet.min.js +334 -0
- package/dist/pivotjet.min.js.map +7 -0
- package/docs/images/cell-formats.png +0 -0
- package/docs/images/chart.png +0 -0
- package/docs/images/configure-fields.png +0 -0
- package/docs/images/designer.png +0 -0
- package/docs/images/large-dataset.png +0 -0
- package/package.json +108 -4
- package/src/cellfmt.js +218 -0
- package/src/chart.js +595 -0
- package/src/core.d.ts +424 -0
- package/src/core.js +18 -0
- package/src/csv.js +198 -0
- package/src/dataset.js +404 -0
- package/src/designer.js +995 -0
- package/src/elements.js +50 -0
- package/src/engine.js +778 -0
- package/src/errors.js +2 -0
- package/src/export.js +775 -0
- package/src/expr.js +180 -0
- package/src/format.js +42 -0
- package/src/holistic.js +237 -0
- package/src/index.d.ts +155 -0
- package/src/index.js +6 -0
- package/src/layouts.js +105 -0
- package/src/node.d.ts +10 -0
- package/src/node.js +29 -0
- package/src/pdffont.js +361 -0
- package/src/remote.js +164 -0
- package/src/report-render.js +31 -0
- package/src/report.js +103 -0
- package/src/reportstore.js +135 -0
- package/src/server.d.ts +20 -0
- package/src/server.js +272 -0
- package/src/stream.js +285 -0
- package/src/styles.js +162 -0
- package/src/util.js +73 -0
- package/src/viewer.js +632 -0
package/src/layouts.js
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
// Saved layouts: named pivot specs with a "default" layout, persisted through a small adapter.
|
|
2
|
+
//
|
|
3
|
+
// const store = new LayoutStore(new LocalStorageAdapter('sales'));
|
|
4
|
+
// await store.save('Revenue by region', designer.getSpec());
|
|
5
|
+
// designer.setSpec(await store.load(id));
|
|
6
|
+
//
|
|
7
|
+
// An adapter is any object with read(): Promise<State> and write(State): Promise<void>
|
|
8
|
+
// State = { layouts: [{ id, name, spec, updated }], defaultId: string|null }
|
|
9
|
+
// so IndexedDB, a database or your own API is a ~10 line adapter.
|
|
10
|
+
|
|
11
|
+
const clone = (o) => JSON.parse(JSON.stringify(o));
|
|
12
|
+
const empty = () => ({ layouts: [], defaultId: null });
|
|
13
|
+
const uid = () => (globalThis.crypto && crypto.randomUUID ? crypto.randomUUID() : 'l' + Date.now().toString(36) + Math.random().toString(36).slice(2, 8));
|
|
14
|
+
|
|
15
|
+
export class MemoryAdapter {
|
|
16
|
+
constructor(state) { this.state = state ? clone(state) : empty(); }
|
|
17
|
+
async read() { return clone(this.state); }
|
|
18
|
+
async write(s) { this.state = clone(s); }
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export class LocalStorageAdapter {
|
|
22
|
+
/** @param {string} [namespace] e.g. one per dataset/report */
|
|
23
|
+
constructor(namespace = 'default', storage) {
|
|
24
|
+
this.key = `pivotjet:layouts:${namespace}`;
|
|
25
|
+
this.storage = storage || (typeof localStorage !== 'undefined' ? localStorage : null);
|
|
26
|
+
if (!this.storage) this._mem = new MemoryAdapter();
|
|
27
|
+
}
|
|
28
|
+
async read() {
|
|
29
|
+
if (this._mem) return this._mem.read();
|
|
30
|
+
try { return { ...empty(), ...JSON.parse(this.storage.getItem(this.key) || '{}') }; } catch { return empty(); }
|
|
31
|
+
}
|
|
32
|
+
async write(s) {
|
|
33
|
+
if (this._mem) return this._mem.write(s);
|
|
34
|
+
this.storage.setItem(this.key, JSON.stringify(s));
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Whole-state sync with a server: GET url -> State, PUT url <- State (see createPivotServer `layouts`). */
|
|
39
|
+
export class RestAdapter {
|
|
40
|
+
constructor(url, { headers = {}, token, fetch: f } = {}) {
|
|
41
|
+
this.url = url;
|
|
42
|
+
this.headers = { 'content-type': 'application/json', ...headers };
|
|
43
|
+
if (token) this.headers.authorization = `Bearer ${token}`;
|
|
44
|
+
this.fetch = f;
|
|
45
|
+
}
|
|
46
|
+
async read() {
|
|
47
|
+
const r = await (this.fetch || globalThis.fetch)(this.url, { headers: this.headers });
|
|
48
|
+
if (!r.ok) throw new Error(`Could not load layouts (${r.status})`);
|
|
49
|
+
return { ...empty(), ...(await r.json()) };
|
|
50
|
+
}
|
|
51
|
+
async write(s) {
|
|
52
|
+
const r = await (this.fetch || globalThis.fetch)(this.url, { method: 'PUT', headers: this.headers, body: JSON.stringify(s) });
|
|
53
|
+
if (!r.ok) throw new Error(`Could not save layouts (${r.status})`);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export class LayoutStore {
|
|
58
|
+
constructor(adapter = new LocalStorageAdapter()) { this.adapter = adapter; this._q = Promise.resolve(); }
|
|
59
|
+
|
|
60
|
+
// serialise read-modify-write cycles so quick clicks can't lose updates
|
|
61
|
+
_tx(fn) {
|
|
62
|
+
const run = this._q.then(async () => { const s = await this.adapter.read(); const out = await fn(s); return out; });
|
|
63
|
+
this._q = run.catch(() => {});
|
|
64
|
+
return run;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** [{id, name, updated, isDefault}] newest first */
|
|
68
|
+
async list() {
|
|
69
|
+
const s = await this.adapter.read();
|
|
70
|
+
return s.layouts.map((l) => ({ id: l.id, name: l.name, updated: l.updated, isDefault: l.id === s.defaultId })).sort((a, b) => b.updated - a.updated);
|
|
71
|
+
}
|
|
72
|
+
async load(id) {
|
|
73
|
+
const s = await this.adapter.read();
|
|
74
|
+
const l = s.layouts.find((x) => x.id === id);
|
|
75
|
+
return l ? clone(l.spec) : null;
|
|
76
|
+
}
|
|
77
|
+
/** Save under `name`. An existing layout with the same name (or the given id) is overwritten. Returns its id. */
|
|
78
|
+
save(name, spec, { id } = {}) {
|
|
79
|
+
name = String(name || '').trim();
|
|
80
|
+
if (!name) return Promise.reject(new Error('A layout needs a name'));
|
|
81
|
+
return this._tx(async (s) => {
|
|
82
|
+
let l = s.layouts.find((x) => (id ? x.id === id : x.name.toLowerCase() === name.toLowerCase()));
|
|
83
|
+
if (!l) { l = { id: uid() }; s.layouts.push(l); }
|
|
84
|
+
Object.assign(l, { name, spec: clone(spec), updated: Date.now() });
|
|
85
|
+
await this.adapter.write(s);
|
|
86
|
+
return l.id;
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
remove(id) {
|
|
90
|
+
return this._tx(async (s) => {
|
|
91
|
+
s.layouts = s.layouts.filter((x) => x.id !== id);
|
|
92
|
+
if (s.defaultId === id) s.defaultId = null;
|
|
93
|
+
await this.adapter.write(s);
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
/** Mark a layout to be applied automatically (pass null to clear). */
|
|
97
|
+
setDefault(id) {
|
|
98
|
+
return this._tx(async (s) => { s.defaultId = id && s.layouts.some((x) => x.id === id) ? id : null; await this.adapter.write(s); });
|
|
99
|
+
}
|
|
100
|
+
async getDefault() {
|
|
101
|
+
const s = await this.adapter.read();
|
|
102
|
+
const l = s.layouts.find((x) => x.id === s.defaultId);
|
|
103
|
+
return l ? clone(l.spec) : null;
|
|
104
|
+
}
|
|
105
|
+
}
|
package/src/node.d.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { Dataset, StreamSource, CsvLoadOptions, PivotReport } from './core.js';
|
|
2
|
+
|
|
3
|
+
/** A thunk giving a fresh read stream per call (what StreamSource.fromCSV wants). */
|
|
4
|
+
export function csvFileSource(path: string): () => any;
|
|
5
|
+
/** Load a CSV file into memory; the file itself is streamed. `onProgress` also receives `fraction` (0..1). */
|
|
6
|
+
export function loadCSVFile(path: string, opts?: CsvLoadOptions & { onProgress?: (p: { rows: number; bytes: number; fraction: number; done?: boolean }) => void }): Promise<Dataset>;
|
|
7
|
+
/** Bounded-memory source over a CSV file of any size; every pivot re-reads the file. */
|
|
8
|
+
export function csvFileStream(path: string, opts?: { delimiter?: string; fields?: any[] }): Promise<StreamSource>;
|
|
9
|
+
/** Standalone .html for a report (embeds the browser bundle from this package's dist/). */
|
|
10
|
+
export function reportToHTMLFile(report: PivotReport, opts?: { bundle?: string; theme?: 'light' | 'dark' | 'auto' }): Promise<string>;
|
package/src/node.js
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
// Node-only helpers: read big CSV files from disk without loading them into memory first.
|
|
2
|
+
import { createReadStream } from 'node:fs';
|
|
3
|
+
import { stat, readFile } from 'node:fs/promises';
|
|
4
|
+
import { loadCSV } from './csv.js';
|
|
5
|
+
import { StreamSource } from './stream.js';
|
|
6
|
+
import { reportToHTML } from './report.js';
|
|
7
|
+
|
|
8
|
+
/** A thunk giving a fresh read stream per call (what StreamSource.fromCSV wants). */
|
|
9
|
+
export const csvFileSource = (path) => () => createReadStream(path, { highWaterMark: 1 << 20 });
|
|
10
|
+
|
|
11
|
+
/** Load a CSV file into an in-memory Dataset (streaming parse; the file is never held whole). */
|
|
12
|
+
export async function loadCSVFile(path, opts = {}) {
|
|
13
|
+
const { size } = await stat(path);
|
|
14
|
+
return loadCSV(createReadStream(path, { highWaterMark: 1 << 20 }), {
|
|
15
|
+
...opts,
|
|
16
|
+
onProgress: opts.onProgress && ((p) => opts.onProgress({ ...p, fraction: p.bytes / size })),
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Bounded-memory source over a CSV file of any size. Every pivot re-reads the file. */
|
|
21
|
+
export async function csvFileStream(path, opts = {}) {
|
|
22
|
+
return StreamSource.fromCSV(csvFileSource(path), opts);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Standalone .html for a report (embeds the browser bundle from this package's dist/). */
|
|
26
|
+
export async function reportToHTMLFile(report, opts = {}) {
|
|
27
|
+
const bundle = opts.bundle || await readFile(new URL('../dist/pivotjet.min.js', import.meta.url), 'utf8');
|
|
28
|
+
return reportToHTML(report, { ...opts, bundle });
|
|
29
|
+
}
|
package/src/pdffont.js
ADDED
|
@@ -0,0 +1,361 @@
|
|
|
1
|
+
// Fonts for the PDF exporter: the 12 standard PDF fonts (sans = Helvetica, serif = Times, mono = Courier; regular, bold,
|
|
2
|
+
// italic, bold italic) with real advance widths, plus optional embedded TrueType / OpenType fonts (full Unicode,
|
|
3
|
+
// glyph-subset for TrueType outlines). DOM-free.
|
|
4
|
+
//
|
|
5
|
+
// Standard-font width tables are typed from the published AFM metrics; Latin-1 and the cp1252 extras beyond ASCII
|
|
6
|
+
// use a per-family default, which only affects column fitting, never the glyphs drawn.
|
|
7
|
+
|
|
8
|
+
const H_REG = [278, 278, 355, 556, 556, 889, 667, 191, 333, 333, 389, 584, 278, 333, 278, 278, 556, 556, 556, 556, 556, 556, 556, 556, 556, 556, 278, 278, 584, 584, 584, 556, 1015, 667, 667, 722, 722, 667, 611, 778, 722, 278, 500, 667, 556, 833, 722, 778, 667, 778, 722, 667, 611, 722, 667, 944, 667, 667, 611, 278, 278, 278, 469, 556, 333, 556, 556, 500, 556, 556, 278, 556, 556, 222, 222, 500, 222, 833, 556, 556, 556, 556, 333, 500, 278, 556, 500, 722, 500, 500, 500, 334, 260, 334, 584];
|
|
9
|
+
const H_BOLD = [278, 333, 474, 556, 556, 889, 722, 238, 333, 333, 389, 584, 278, 333, 278, 278, 556, 556, 556, 556, 556, 556, 556, 556, 556, 556, 333, 333, 584, 584, 584, 611, 975, 722, 722, 722, 722, 667, 611, 778, 722, 278, 556, 722, 611, 833, 722, 778, 667, 778, 722, 667, 611, 722, 667, 944, 667, 667, 611, 333, 278, 333, 584, 556, 333, 556, 611, 556, 611, 556, 333, 611, 611, 278, 278, 556, 278, 889, 611, 611, 611, 611, 389, 556, 333, 611, 556, 778, 556, 556, 500, 389, 280, 389, 584];
|
|
10
|
+
const T_REG = [250, 333, 408, 500, 500, 833, 778, 180, 333, 333, 500, 564, 250, 333, 250, 278, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 278, 278, 564, 564, 564, 444, 921, 722, 667, 667, 722, 611, 556, 722, 722, 333, 389, 722, 611, 889, 722, 722, 556, 722, 667, 556, 611, 722, 722, 944, 722, 722, 611, 333, 278, 333, 469, 500, 333, 444, 500, 444, 500, 444, 333, 500, 500, 278, 278, 500, 278, 778, 500, 500, 500, 500, 333, 389, 278, 500, 500, 722, 500, 500, 444, 480, 200, 480, 541];
|
|
11
|
+
const T_BOLD = [250, 333, 555, 500, 500, 1000, 833, 278, 333, 333, 500, 570, 250, 333, 250, 278, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 333, 333, 570, 570, 570, 500, 930, 722, 667, 722, 722, 667, 611, 778, 778, 389, 500, 778, 667, 944, 722, 778, 611, 778, 722, 556, 667, 722, 722, 1000, 722, 722, 667, 333, 278, 333, 581, 500, 333, 500, 556, 444, 556, 444, 333, 500, 556, 278, 333, 556, 278, 833, 556, 500, 556, 556, 444, 389, 333, 556, 500, 722, 500, 500, 444, 394, 220, 394, 520];
|
|
12
|
+
const T_ITAL = [250, 333, 420, 500, 500, 833, 778, 214, 333, 333, 500, 675, 250, 333, 250, 278, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 333, 333, 675, 675, 675, 500, 920, 611, 611, 667, 722, 611, 611, 722, 722, 333, 444, 667, 556, 833, 667, 722, 611, 722, 611, 500, 556, 722, 611, 833, 611, 556, 556, 389, 278, 389, 422, 500, 333, 500, 500, 444, 500, 444, 278, 500, 500, 278, 278, 444, 278, 722, 500, 500, 500, 500, 389, 389, 278, 500, 444, 667, 444, 444, 389, 400, 275, 400, 541];
|
|
13
|
+
const T_BI = [250, 389, 555, 500, 500, 833, 778, 278, 333, 333, 500, 570, 250, 333, 250, 278, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 333, 333, 570, 570, 570, 500, 832, 667, 667, 667, 722, 667, 667, 722, 778, 389, 500, 667, 611, 889, 722, 722, 611, 722, 667, 556, 611, 722, 667, 889, 667, 611, 611, 333, 278, 333, 570, 500, 333, 500, 500, 444, 500, 444, 333, 500, 556, 278, 278, 500, 278, 778, 556, 500, 500, 500, 389, 389, 278, 556, 444, 667, 500, 444, 389, 348, 220, 348, 570];
|
|
14
|
+
export const _TABLES = { H_REG, H_BOLD, T_REG, T_BOLD, T_ITAL, T_BI };
|
|
15
|
+
|
|
16
|
+
const CP1252 = { '€': 0x80, '‚': 0x82, 'ƒ': 0x83, '„': 0x84, '…': 0x85, '†': 0x86, '‡': 0x87, 'ˆ': 0x88, '‰': 0x89, 'Š': 0x8a, '‹': 0x8b, 'Œ': 0x8c, 'Ž': 0x8e, '‘': 0x91, '’': 0x92, '“': 0x93, '”': 0x94, '•': 0x95, '–': 0x96, '—': 0x97, '˜': 0x98, '™': 0x99, 'š': 0x9a, '›': 0x9b, 'œ': 0x9c, 'ž': 0x9e, 'Ÿ': 0x9f };
|
|
17
|
+
const SPECIAL = { sans: { 0x85: 1000, 0x91: 222, 0x92: 222, 0x93: 333, 0x94: 333, 0x95: 350, 0x96: 556, 0x97: 1000, 0x99: 1000 }, serif: { 0x85: 1000, 0x91: 333, 0x92: 333, 0x93: 444, 0x94: 444, 0x95: 350, 0x96: 500, 0x97: 1000, 0x99: 980 }, mono: {} };
|
|
18
|
+
|
|
19
|
+
/** Map any JS string onto WinAnsi-range chars (everything else becomes '?'). */
|
|
20
|
+
export function winAnsi(str) {
|
|
21
|
+
let out = '';
|
|
22
|
+
for (const ch of String(str)) {
|
|
23
|
+
const c = ch.codePointAt(0);
|
|
24
|
+
if (c >= 32 && c <= 126) out += ch;
|
|
25
|
+
else if (c < 32 || c === 127) out += ' ';
|
|
26
|
+
else if (c >= 160 && c <= 255) out += ch;
|
|
27
|
+
else if (CP1252[ch] !== undefined) out += String.fromCharCode(CP1252[ch]);
|
|
28
|
+
else out += '?';
|
|
29
|
+
}
|
|
30
|
+
return out;
|
|
31
|
+
}
|
|
32
|
+
export function pdfStr(s) {
|
|
33
|
+
let o = '(';
|
|
34
|
+
for (let i = 0; i < s.length; i++) {
|
|
35
|
+
const c = s.charCodeAt(i) & 255;
|
|
36
|
+
if (c === 40) o += '\\(';
|
|
37
|
+
else if (c === 41) o += '\\)';
|
|
38
|
+
else if (c === 92) o += '\\\\';
|
|
39
|
+
else if (c > 126 || c < 32) o += '\\' + c.toString(8).padStart(3, '0');
|
|
40
|
+
else o += String.fromCharCode(c);
|
|
41
|
+
}
|
|
42
|
+
return o + ')';
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function table(src, family) {
|
|
46
|
+
const t = new Float64Array(256).fill(family === 'mono' ? 600 : family === 'serif' ? 500 : 556);
|
|
47
|
+
if (family !== 'mono') {
|
|
48
|
+
for (let i = 0; i < src.length; i++) t[32 + i] = src[i];
|
|
49
|
+
for (const k in SPECIAL[family]) t[k] = SPECIAL[family][k];
|
|
50
|
+
t[127] = src[0];
|
|
51
|
+
}
|
|
52
|
+
return t;
|
|
53
|
+
}
|
|
54
|
+
// family -> [regular, bold, italic, boldItalic] = [PostScript name, width table]
|
|
55
|
+
const STD = {
|
|
56
|
+
sans: [['Helvetica', table(H_REG, 'sans')], ['Helvetica-Bold', table(H_BOLD, 'sans')], ['Helvetica-Oblique', table(H_REG, 'sans')], ['Helvetica-BoldOblique', table(H_BOLD, 'sans')]],
|
|
57
|
+
serif: [['Times-Roman', table(T_REG, 'serif')], ['Times-Bold', table(T_BOLD, 'serif')], ['Times-Italic', table(T_ITAL, 'serif')], ['Times-BoldItalic', table(T_BI, 'serif')]],
|
|
58
|
+
mono: [['Courier', table(null, 'mono')], ['Courier-Bold', table(null, 'mono')], ['Courier-Oblique', table(null, 'mono')], ['Courier-BoldOblique', table(null, 'mono')]],
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
class StdFont {
|
|
62
|
+
constructor(ps, widths) { this.ps = ps; this.w = widths; this.embedded = false; }
|
|
63
|
+
prep(s) { return winAnsi(s); }
|
|
64
|
+
width(s, fs) { let w = 0; for (let i = 0; i < s.length; i++) w += this.w[s.charCodeAt(i) & 255]; return (w * fs) / 1000; }
|
|
65
|
+
fit(s, maxW, fs) {
|
|
66
|
+
if (s === '' || this.width(s, fs) <= maxW + 0.01) return s;
|
|
67
|
+
const ell = (3 * this.w[46] * fs) / 1000;
|
|
68
|
+
if (maxW <= ell) return '';
|
|
69
|
+
let w = 0, i = 0;
|
|
70
|
+
for (; i < s.length; i++) { const cw = (this.w[s.charCodeAt(i) & 255] * fs) / 1000; if (w + cw > maxW - ell) break; w += cw; }
|
|
71
|
+
return s.slice(0, i) + '...';
|
|
72
|
+
}
|
|
73
|
+
enc(s) { return pdfStr(s); }
|
|
74
|
+
pdfObjects(alloc) { return { root: alloc.add(`<< /Type /Font /Subtype /Type1 /BaseFont /${this.ps} /Encoding /WinAnsiEncoding >>`) }; }
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// ------------------------------------------------------------------------------------------ TrueType / OpenType
|
|
78
|
+
const u16 = (dv, o) => dv.getUint16(o);
|
|
79
|
+
const i16 = (dv, o) => dv.getInt16(o);
|
|
80
|
+
const u32 = (dv, o) => dv.getUint32(o);
|
|
81
|
+
const tagOf = (dv, o) => String.fromCharCode(dv.getUint8(o), dv.getUint8(o + 1), dv.getUint8(o + 2), dv.getUint8(o + 3));
|
|
82
|
+
|
|
83
|
+
function parseSfnt(buf) {
|
|
84
|
+
const dv = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
|
|
85
|
+
const sig = u32(dv, 0);
|
|
86
|
+
if (sig === 0x74746366) throw new Error('Font collections (.ttc) are not supported; pass a single .ttf or .otf file');
|
|
87
|
+
if (![0x00010000, 0x4f54544f, 0x74727565].includes(sig)) throw new Error('Not a TrueType/OpenType font (.ttf/.otf expected; WOFF is not supported)');
|
|
88
|
+
const n = u16(dv, 4), tables = {};
|
|
89
|
+
for (let i = 0; i < n; i++) {
|
|
90
|
+
const o = 12 + i * 16;
|
|
91
|
+
tables[tagOf(dv, o)] = { off: u32(dv, o + 8), len: u32(dv, o + 12) };
|
|
92
|
+
}
|
|
93
|
+
for (const t of ['head', 'hhea', 'maxp', 'hmtx', 'cmap']) if (!tables[t]) throw new Error(`Font is missing the "${t}" table`);
|
|
94
|
+
const head = tables.head.off, hhea = tables.hhea.off;
|
|
95
|
+
const f = {
|
|
96
|
+
buf, dv, tables, cff: !!tables['CFF '],
|
|
97
|
+
unitsPerEm: u16(dv, head + 18), locFormat: i16(dv, head + 50),
|
|
98
|
+
bbox: [i16(dv, head + 36), i16(dv, head + 38), i16(dv, head + 40), i16(dv, head + 42)],
|
|
99
|
+
ascent: i16(dv, hhea + 4), descent: i16(dv, hhea + 6), nHM: u16(dv, hhea + 34), numGlyphs: u16(dv, tables.maxp.off + 4),
|
|
100
|
+
italicAngle: tables.post ? i32fixed(dv, tables.post.off + 4) : 0,
|
|
101
|
+
capHeight: 0, fsType: 0,
|
|
102
|
+
};
|
|
103
|
+
if (!f.cff && !(tables.glyf && tables.loca)) throw new Error('Font has no outlines (glyf/loca or CFF)');
|
|
104
|
+
if (tables['OS/2']) {
|
|
105
|
+
const o = tables['OS/2'].off;
|
|
106
|
+
f.fsType = u16(dv, o + 8);
|
|
107
|
+
if (u16(dv, o) >= 2 && tables['OS/2'].len >= 90) f.capHeight = i16(dv, o + 88);
|
|
108
|
+
}
|
|
109
|
+
if (!f.capHeight) f.capHeight = Math.round(f.ascent * 0.7);
|
|
110
|
+
f.name = psName(f);
|
|
111
|
+
f.cmapLookup = makeCmap(f);
|
|
112
|
+
return f;
|
|
113
|
+
}
|
|
114
|
+
const i32fixed = (dv, o) => dv.getInt32(o) / 65536;
|
|
115
|
+
|
|
116
|
+
function psName(f) {
|
|
117
|
+
const t = f.tables.name;
|
|
118
|
+
if (!t) return 'EmbeddedFont';
|
|
119
|
+
const dv = f.dv, count = u16(dv, t.off + 2), so = t.off + u16(dv, t.off + 4);
|
|
120
|
+
for (let i = 0; i < count; i++) {
|
|
121
|
+
const o = t.off + 6 + i * 12;
|
|
122
|
+
if (u16(dv, o + 6) !== 6) continue;
|
|
123
|
+
const plat = u16(dv, o), len = u16(dv, o + 8), off = so + u16(dv, o + 10);
|
|
124
|
+
let s = '';
|
|
125
|
+
if (plat === 3 || plat === 0) for (let k = 0; k + 1 < len; k += 2) s += String.fromCharCode(u16(dv, off + k));
|
|
126
|
+
else for (let k = 0; k < len; k++) s += String.fromCharCode(dv.getUint8(off + k));
|
|
127
|
+
s = s.replace(/[^A-Za-z0-9-]/g, '');
|
|
128
|
+
if (s) return s.slice(0, 60);
|
|
129
|
+
}
|
|
130
|
+
return 'EmbeddedFont';
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function makeCmap(f) {
|
|
134
|
+
const dv = f.dv, base = f.tables.cmap.off, n = u16(dv, base + 2);
|
|
135
|
+
let best = null, score = -1;
|
|
136
|
+
for (let i = 0; i < n; i++) {
|
|
137
|
+
const plat = u16(dv, base + 4 + i * 8), enc = u16(dv, base + 6 + i * 8), off = base + u32(dv, base + 8 + i * 8);
|
|
138
|
+
const fmt = u16(dv, off);
|
|
139
|
+
const sc = plat === 3 && enc === 10 && fmt === 12 ? 4 : plat === 3 && enc === 1 && (fmt === 4 || fmt === 12) ? 3 : plat === 0 && (fmt === 4 || fmt === 12) ? 2 : -1;
|
|
140
|
+
if (sc > score) { score = sc; best = { off, fmt }; }
|
|
141
|
+
}
|
|
142
|
+
if (!best) throw new Error('Font has no Unicode character map');
|
|
143
|
+
const { off, fmt } = best;
|
|
144
|
+
const cache = new Map();
|
|
145
|
+
if (fmt === 12) {
|
|
146
|
+
const ng = u32(dv, off + 12);
|
|
147
|
+
return (cp) => {
|
|
148
|
+
let lo = 0, hi = ng - 1;
|
|
149
|
+
while (lo <= hi) {
|
|
150
|
+
const mid = (lo + hi) >> 1, g = off + 16 + mid * 12;
|
|
151
|
+
const s = u32(dv, g), e = u32(dv, g + 4);
|
|
152
|
+
if (cp < s) hi = mid - 1; else if (cp > e) lo = mid + 1; else return (u32(dv, g + 8) + cp - s) & 0xffff;
|
|
153
|
+
}
|
|
154
|
+
return 0;
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
const segX2 = u16(dv, off + 6), segs = segX2 / 2;
|
|
158
|
+
const endO = off + 14, startO = endO + segX2 + 2, deltaO = startO + segX2, rangeO = deltaO + segX2;
|
|
159
|
+
return (cp) => {
|
|
160
|
+
if (cp > 0xffff) return 0;
|
|
161
|
+
const hit = cache.get(cp);
|
|
162
|
+
if (hit !== undefined) return hit;
|
|
163
|
+
let gid = 0;
|
|
164
|
+
for (let i = 0; i < segs; i++) {
|
|
165
|
+
if (cp > u16(dv, endO + i * 2)) continue;
|
|
166
|
+
const s = u16(dv, startO + i * 2);
|
|
167
|
+
if (cp < s) break;
|
|
168
|
+
const ro = u16(dv, rangeO + i * 2), d = u16(dv, deltaO + i * 2);
|
|
169
|
+
if (ro === 0) gid = (cp + d) & 0xffff;
|
|
170
|
+
else { const g = u16(dv, rangeO + i * 2 + ro + (cp - s) * 2); gid = g === 0 ? 0 : (g + d) & 0xffff; }
|
|
171
|
+
break;
|
|
172
|
+
}
|
|
173
|
+
cache.set(cp, gid);
|
|
174
|
+
return gid;
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function advance(f, gid) {
|
|
179
|
+
const dv = f.dv, hm = f.tables.hmtx.off;
|
|
180
|
+
return u16(dv, hm + (gid < f.nHM ? gid : f.nHM - 1) * 4);
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
const pad4 = (n) => (n + 3) & ~3;
|
|
184
|
+
function checksum(bytes) {
|
|
185
|
+
let s = 0;
|
|
186
|
+
const n = bytes.length & ~3;
|
|
187
|
+
for (let i = 0; i < n; i += 4) s = (s + (((bytes[i] << 24) | (bytes[i + 1] << 16) | (bytes[i + 2] << 8) | bytes[i + 3]) >>> 0)) >>> 0;
|
|
188
|
+
let rest = 0;
|
|
189
|
+
for (let i = n; i < bytes.length; i++) rest |= bytes[i] << (24 - 8 * (i - n));
|
|
190
|
+
return (s + (rest >>> 0)) >>> 0;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** Keep only the outlines of `gids` (plus composite parts); glyph ids stay unchanged so text encoding is unaffected. */
|
|
194
|
+
function subsetTrueType(f, gids) {
|
|
195
|
+
const { dv, buf, tables } = f;
|
|
196
|
+
const glyf = tables.glyf, loca = tables.loca;
|
|
197
|
+
const locOf = (g) => (f.locFormat === 0 ? u16(dv, loca.off + g * 2) * 2 : u32(dv, loca.off + g * 4));
|
|
198
|
+
const keep = new Set([0]);
|
|
199
|
+
const add = (g) => {
|
|
200
|
+
if (g >= f.numGlyphs || keep.has(g)) return;
|
|
201
|
+
keep.add(g);
|
|
202
|
+
const s = locOf(g), e = locOf(g + 1);
|
|
203
|
+
if (e - s < 10 || i16(dv, glyf.off + s) >= 0) return;
|
|
204
|
+
let p = glyf.off + s + 10;
|
|
205
|
+
for (;;) {
|
|
206
|
+
const flags = u16(dv, p), comp = u16(dv, p + 2);
|
|
207
|
+
add(comp);
|
|
208
|
+
p += 4 + (flags & 1 ? 4 : 2);
|
|
209
|
+
if (flags & 0x8) p += 2; else if (flags & 0x40) p += 4; else if (flags & 0x80) p += 8;
|
|
210
|
+
if (!(flags & 0x20)) break;
|
|
211
|
+
}
|
|
212
|
+
};
|
|
213
|
+
for (const g of gids) add(g);
|
|
214
|
+
const chunks = [], newLoca = new DataView(new ArrayBuffer((f.numGlyphs + 1) * 4));
|
|
215
|
+
let size = 0;
|
|
216
|
+
for (let g = 0; g < f.numGlyphs; g++) {
|
|
217
|
+
newLoca.setUint32(g * 4, size);
|
|
218
|
+
if (keep.has(g)) {
|
|
219
|
+
const s = locOf(g), e = locOf(g + 1);
|
|
220
|
+
if (e > s) { const c = buf.subarray(glyf.off + s, glyf.off + e); chunks.push(c); size += c.length; const p = pad4(size) - size; if (p) { chunks.push(new Uint8Array(p)); size += p; } }
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
newLoca.setUint32(f.numGlyphs * 4, size);
|
|
224
|
+
const glyfOut = new Uint8Array(size);
|
|
225
|
+
let o = 0;
|
|
226
|
+
for (const c of chunks) { glyfOut.set(c, o); o += c.length; }
|
|
227
|
+
const out = { glyf: glyfOut, loca: new Uint8Array(newLoca.buffer) };
|
|
228
|
+
for (const t of ['head', 'hhea', 'maxp', 'hmtx', 'cvt ', 'fpgm', 'prep']) if (tables[t]) out[t] = buf.slice(tables[t].off, tables[t].off + tables[t].len);
|
|
229
|
+
out.head[50] = 0; out.head[51] = 1; // long loca
|
|
230
|
+
out.head.fill(0, 8, 12); // checkSumAdjustment, recomputed below
|
|
231
|
+
const tags = Object.keys(out).sort();
|
|
232
|
+
const n = tags.length;
|
|
233
|
+
let off = 12 + n * 16;
|
|
234
|
+
const dirs = [];
|
|
235
|
+
for (const t of tags) { dirs.push({ t, off, len: out[t].length, sum: checksum(out[t]) }); off += pad4(out[t].length); }
|
|
236
|
+
const file = new Uint8Array(off), fdv = new DataView(file.buffer);
|
|
237
|
+
fdv.setUint32(0, 0x00010000);
|
|
238
|
+
fdv.setUint16(4, n);
|
|
239
|
+
let sr = 1, es = 0;
|
|
240
|
+
while (sr * 2 <= n) { sr *= 2; es++; }
|
|
241
|
+
fdv.setUint16(6, sr * 16); fdv.setUint16(8, es); fdv.setUint16(10, n * 16 - sr * 16);
|
|
242
|
+
dirs.forEach((d, i) => {
|
|
243
|
+
const p = 12 + i * 16;
|
|
244
|
+
for (let k = 0; k < 4; k++) file[p + k] = d.t.charCodeAt(k);
|
|
245
|
+
fdv.setUint32(p + 4, d.sum); fdv.setUint32(p + 8, d.off); fdv.setUint32(p + 12, d.len);
|
|
246
|
+
file.set(out[d.t], d.off);
|
|
247
|
+
});
|
|
248
|
+
const whole = checksum(file);
|
|
249
|
+
const head = dirs.find((d) => d.t === 'head');
|
|
250
|
+
fdv.setUint32(head.off + 8, (0xb1b0afba - whole) >>> 0);
|
|
251
|
+
return file;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
const latin1 = (u8) => {
|
|
255
|
+
let s = '';
|
|
256
|
+
for (let i = 0; i < u8.length; i += 8192) s += String.fromCharCode.apply(null, u8.subarray(i, i + 8192));
|
|
257
|
+
return s;
|
|
258
|
+
};
|
|
259
|
+
const hex4 = (n) => n.toString(16).padStart(4, '0');
|
|
260
|
+
const utf16hex = (cp) => (cp > 0xffff ? hex4(0xd800 + ((cp - 0x10000) >> 10)) + hex4(0xdc00 + ((cp - 0x10000) & 0x3ff)) : hex4(cp));
|
|
261
|
+
|
|
262
|
+
class EmbeddedFont {
|
|
263
|
+
constructor(bytes) {
|
|
264
|
+
const check = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
|
|
265
|
+
this.f = parseSfnt(check);
|
|
266
|
+
if (this.f.fsType & 0x0002) throw new Error(`Font "${this.f.name}" does not permit embedding (fsType restricted)`);
|
|
267
|
+
this.embedded = true;
|
|
268
|
+
this.used = new Map(); // gid -> code point
|
|
269
|
+
this.k = 1000 / this.f.unitsPerEm;
|
|
270
|
+
}
|
|
271
|
+
prep(s) { return String(s).replace(/[\u0000-\u001f\u007f]/g, ' '); }
|
|
272
|
+
gid(cp) { return this.f.cmapLookup(cp); }
|
|
273
|
+
width(s, fs) {
|
|
274
|
+
let w = 0;
|
|
275
|
+
for (const ch of s) w += advance(this.f, this.gid(ch.codePointAt(0)));
|
|
276
|
+
return (w * fs) / this.f.unitsPerEm;
|
|
277
|
+
}
|
|
278
|
+
fit(s, maxW, fs) {
|
|
279
|
+
if (s === '' || this.width(s, fs) <= maxW + 0.01) return s;
|
|
280
|
+
const ell = this.width('...', fs);
|
|
281
|
+
if (maxW <= ell) return '';
|
|
282
|
+
let w = 0, out = '';
|
|
283
|
+
for (const ch of s) { const cw = this.width(ch, fs); if (w + cw > maxW - ell) break; w += cw; out += ch; }
|
|
284
|
+
return out + '...';
|
|
285
|
+
}
|
|
286
|
+
enc(s) {
|
|
287
|
+
let h = '<';
|
|
288
|
+
for (const ch of s) {
|
|
289
|
+
const cp = ch.codePointAt(0), g = this.gid(cp);
|
|
290
|
+
if (g && !this.used.has(g)) this.used.set(g, cp);
|
|
291
|
+
h += hex4(g);
|
|
292
|
+
}
|
|
293
|
+
return h + '>';
|
|
294
|
+
}
|
|
295
|
+
pdfObjects(alloc) {
|
|
296
|
+
const f = this.f, tag = 'AAAAAA+' + f.name;
|
|
297
|
+
const gids = [...this.used.keys()].sort((a, b) => a - b);
|
|
298
|
+
const data = f.cff ? f.buf : subsetTrueType(f, gids);
|
|
299
|
+
const ffId = alloc.add(`<< /Length ${data.length}${f.cff ? ' /Subtype /OpenType' : ` /Length1 ${data.length}`} >>\nstream\n${latin1(data)}\nendstream`);
|
|
300
|
+
const sc = (v) => Math.round(v * this.k);
|
|
301
|
+
const descId = alloc.add(`<< /Type /FontDescriptor /FontName /${tag} /Flags 32 /FontBBox [${f.bbox.map(sc).join(' ')}] /ItalicAngle ${f.italicAngle} /Ascent ${sc(f.ascent)} /Descent ${sc(f.descent)} /CapHeight ${sc(f.capHeight)} /StemV 80 /${f.cff ? 'FontFile3' : 'FontFile2'} ${ffId} 0 R >>`);
|
|
302
|
+
const wArr = gids.map((g) => `${g} [${sc(advance(f, g))}]`).join(' ');
|
|
303
|
+
const cidId = alloc.add(`<< /Type /Font /Subtype /${f.cff ? 'CIDFontType0' : 'CIDFontType2'} /BaseFont /${tag} /CIDSystemInfo << /Registry (Adobe) /Ordering (Identity) /Supplement 0 >> /FontDescriptor ${descId} 0 R /DW 1000 /W [${wArr}]${f.cff ? '' : ' /CIDToGIDMap /Identity'} >>`);
|
|
304
|
+
const maps = [];
|
|
305
|
+
const entries = [...this.used.entries()].sort((a, b) => a[0] - b[0]);
|
|
306
|
+
for (let i = 0; i < entries.length; i += 100) {
|
|
307
|
+
const part = entries.slice(i, i + 100);
|
|
308
|
+
maps.push(`${part.length} beginbfchar\n${part.map(([g, cp]) => `<${hex4(g)}> <${utf16hex(cp)}>`).join('\n')}\nendbfchar`);
|
|
309
|
+
}
|
|
310
|
+
const cmap = `/CIDInit /ProcSet findresource begin\n12 dict begin\nbegincmap\n/CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def\n/CMapName /Adobe-Identity-UCS def\n/CMapType 2 def\n1 begincodespacerange\n<0000> <FFFF>\nendcodespacerange\n${maps.join('\n')}\nendcmap\nCMapName currentdict /CMap defineresource pop\nend\nend`;
|
|
311
|
+
const tuId = alloc.add(`<< /Length ${cmap.length} >>\nstream\n${cmap}\nendstream`);
|
|
312
|
+
return { root: alloc.add(`<< /Type /Font /Subtype /Type0 /BaseFont /${tag} /Encoding /Identity-H /DescendantFonts [${cidId} 0 R] /ToUnicode ${tuId} 0 R >>`) };
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/**
|
|
317
|
+
* @param {Record<string, {regular?:Uint8Array, bold?:Uint8Array, italic?:Uint8Array, boldItalic?:Uint8Array}>} [custom] family name -> TrueType/OpenType bytes
|
|
318
|
+
* @param {string} [defaultFamily] 'sans' | 'serif' | 'mono' | a key of `custom`
|
|
319
|
+
*/
|
|
320
|
+
export function createFontSet(custom = {}, defaultFamily = 'sans') {
|
|
321
|
+
const std = new Map(), emb = new Map(), objs = new Map();
|
|
322
|
+
const styleKey = (b, i) => (b && i ? 'boldItalic' : b ? 'bold' : i ? 'italic' : 'regular');
|
|
323
|
+
const stdFont = (fam, b, i) => {
|
|
324
|
+
const idx = (b ? 1 : 0) + (i ? 2 : 0), key = `${fam}${idx}`;
|
|
325
|
+
let f = std.get(key);
|
|
326
|
+
if (!f) { const [ps, w] = STD[fam][idx]; f = new StdFont(ps, w); std.set(key, f); }
|
|
327
|
+
return f;
|
|
328
|
+
};
|
|
329
|
+
const embFont = (name, b, i) => {
|
|
330
|
+
const fam = custom[name];
|
|
331
|
+
const want = styleKey(b, i);
|
|
332
|
+
const pick = fam[want] ? want : fam[b ? 'bold' : 'regular'] && !i ? (b ? 'bold' : 'regular') : fam.regular ? 'regular' : Object.keys(fam).find((k) => fam[k]);
|
|
333
|
+
if (!pick) throw new Error(`Font family "${name}" has no font data`);
|
|
334
|
+
const key = `${name}/${pick}`;
|
|
335
|
+
let f = emb.get(key);
|
|
336
|
+
if (!f) { f = new EmbeddedFont(fam[pick]); emb.set(key, f); }
|
|
337
|
+
return f;
|
|
338
|
+
};
|
|
339
|
+
const usedFonts = [];
|
|
340
|
+
const names = new Map();
|
|
341
|
+
const note = (f) => { if (!names.has(f)) { names.set(f, 'F' + (names.size + 1)); usedFonts.push(f); } return f; };
|
|
342
|
+
const set = {
|
|
343
|
+
defaultFamily,
|
|
344
|
+
has: (name) => Object.prototype.hasOwnProperty.call(custom, name),
|
|
345
|
+
/** a font object: prep(s) -> drawable string, width(s, size), fit(s, maxW, size), enc(s) -> PDF string token */
|
|
346
|
+
resolve(family, bold, italic) {
|
|
347
|
+
const fam = family || defaultFamily;
|
|
348
|
+
if (STD[fam]) return note(stdFont(fam, !!bold, !!italic));
|
|
349
|
+
if (custom[fam]) return note(embFont(fam, !!bold, !!italic));
|
|
350
|
+
return note(stdFont('sans', !!bold, !!italic)); // unknown family name: fall back quietly
|
|
351
|
+
},
|
|
352
|
+
nameOf: (f) => names.get(f),
|
|
353
|
+
/** Call once all text is drawn: writes the font objects through `alloc.add(body) -> id`. */
|
|
354
|
+
finish(alloc) {
|
|
355
|
+
const ids = new Map();
|
|
356
|
+
for (const f of usedFonts) ids.set(f, f.pdfObjects(alloc).root);
|
|
357
|
+
return { resources: usedFonts.map((f) => `/${names.get(f)} ${ids.get(f)} 0 R`).join(' ') };
|
|
358
|
+
},
|
|
359
|
+
};
|
|
360
|
+
return set;
|
|
361
|
+
}
|