+752
@@ -0,0 +1,752 @@
|
||||
{
|
||||
"hoistPattern": [
|
||||
"*"
|
||||
],
|
||||
"included": {
|
||||
"dependencies": true,
|
||||
"devDependencies": false,
|
||||
"optionalDependencies": true
|
||||
},
|
||||
"injectedDeps": {},
|
||||
"ignoredBuilds": [],
|
||||
"layoutVersion": 5,
|
||||
"hoistedLocations": {
|
||||
"@napi-rs/canvas@0.1.100": [
|
||||
"node_modules\\@napi-rs\\canvas"
|
||||
],
|
||||
"@viz-js/viz@3.25.0": [
|
||||
"node_modules\\@viz-js\\viz"
|
||||
],
|
||||
"docx@9.6.1": [
|
||||
"node_modules\\docx"
|
||||
],
|
||||
"jpeg-js@0.4.4": [
|
||||
"node_modules\\jpeg-js"
|
||||
],
|
||||
"live-server@1.2.2": [
|
||||
"node_modules\\live-server"
|
||||
],
|
||||
"lucide@1.8.0": [
|
||||
"node_modules\\lucide"
|
||||
],
|
||||
"marked@17.0.5": [
|
||||
"node_modules\\marked"
|
||||
],
|
||||
"pdf-lib@1.17.1": [
|
||||
"node_modules\\pdf-lib"
|
||||
],
|
||||
"pdfjs-dist@5.6.205": [
|
||||
"node_modules\\pdfjs-dist"
|
||||
],
|
||||
"pixelmatch@7.2.0": [
|
||||
"node_modules\\pixelmatch"
|
||||
],
|
||||
"pngjs@7.0.0": [
|
||||
"node_modules\\pngjs"
|
||||
],
|
||||
"pnpm@11.25.0": [
|
||||
"node_modules\\pnpm"
|
||||
],
|
||||
"@types/node@22.20.1": [
|
||||
"node_modules\\pptxgenjs\\node_modules\\@types\\node"
|
||||
],
|
||||
"undici-types@6.21.0": [
|
||||
"node_modules\\pptxgenjs\\node_modules\\undici-types"
|
||||
],
|
||||
"sharp@0.35.5(@types/node@25.9.5)": [
|
||||
"node_modules\\sharp"
|
||||
],
|
||||
"tesseract.js@7.0.0": [
|
||||
"node_modules\\tesseract.js"
|
||||
],
|
||||
"@napi-rs/canvas-win32-arm64-msvc@0.1.100": [
|
||||
"node_modules\\@napi-rs\\canvas-win32-arm64-msvc"
|
||||
],
|
||||
"@types/node@25.9.5": [
|
||||
"node_modules\\@types\\node"
|
||||
],
|
||||
"hash.js@1.1.7": [
|
||||
"node_modules\\hash.js"
|
||||
],
|
||||
"jszip@3.10.1": [
|
||||
"node_modules\\jszip"
|
||||
],
|
||||
"nanoid@5.1.16": [
|
||||
"node_modules\\nanoid"
|
||||
],
|
||||
"xml@1.0.1": [
|
||||
"node_modules\\xml"
|
||||
],
|
||||
"xml-js@1.6.11": [
|
||||
"node_modules\\xml-js"
|
||||
],
|
||||
"is-glob@4.0.3": [
|
||||
"node_modules\\chokidar\\node_modules\\is-glob"
|
||||
],
|
||||
"normalize-path@3.0.0": [
|
||||
"node_modules\\chokidar\\node_modules\\normalize-path"
|
||||
],
|
||||
"colors@1.4.0": [
|
||||
"node_modules\\colors"
|
||||
],
|
||||
"connect@3.7.0": [
|
||||
"node_modules\\connect"
|
||||
],
|
||||
"cors@2.8.6": [
|
||||
"node_modules\\cors"
|
||||
],
|
||||
"event-stream@3.3.4": [
|
||||
"node_modules\\event-stream"
|
||||
],
|
||||
"faye-websocket@0.11.4": [
|
||||
"node_modules\\faye-websocket"
|
||||
],
|
||||
"http-auth@3.1.3": [
|
||||
"node_modules\\http-auth"
|
||||
],
|
||||
"morgan@1.12.0": [
|
||||
"node_modules\\morgan"
|
||||
],
|
||||
"object-assign@4.1.1": [
|
||||
"node_modules\\object-assign"
|
||||
],
|
||||
"opn@6.0.0": [
|
||||
"node_modules\\opn"
|
||||
],
|
||||
"proxy-middleware@0.15.0": [
|
||||
"node_modules\\proxy-middleware"
|
||||
],
|
||||
"debug@4.4.3": [
|
||||
"node_modules\\send\\node_modules\\debug"
|
||||
],
|
||||
"encodeurl@2.0.0": [
|
||||
"node_modules\\send\\node_modules\\encodeurl"
|
||||
],
|
||||
"mime-types@3.0.2": [
|
||||
"node_modules\\send\\node_modules\\mime-types"
|
||||
],
|
||||
"statuses@2.0.2": [
|
||||
"node_modules\\send\\node_modules\\statuses",
|
||||
"node_modules\\http-errors\\node_modules\\statuses"
|
||||
],
|
||||
"http-errors@1.8.1": [
|
||||
"node_modules\\serve-index\\node_modules\\http-errors"
|
||||
],
|
||||
"depd@1.1.2": [
|
||||
"node_modules\\serve-index\\node_modules\\depd"
|
||||
],
|
||||
"@pdf-lib/standard-fonts@1.0.0": [
|
||||
"node_modules\\@pdf-lib\\standard-fonts"
|
||||
],
|
||||
"@pdf-lib/upng@1.0.1": [
|
||||
"node_modules\\@pdf-lib\\upng"
|
||||
],
|
||||
"pako@1.0.11": [
|
||||
"node_modules\\pako"
|
||||
],
|
||||
"tslib@1.14.1": [
|
||||
"node_modules\\tslib"
|
||||
],
|
||||
"node-readable-to-web-readable-stream@0.4.2": [
|
||||
"node_modules\\node-readable-to-web-readable-stream"
|
||||
],
|
||||
"playwright-core@1.62.1": [
|
||||
"node_modules\\playwright-core"
|
||||
],
|
||||
"https@1.0.0": [
|
||||
"node_modules\\https"
|
||||
],
|
||||
"image-size@1.2.1": [
|
||||
"node_modules\\image-size"
|
||||
],
|
||||
"@img/colour@1.1.0": [
|
||||
"node_modules\\@img\\colour"
|
||||
],
|
||||
"detect-libc@2.1.2": [
|
||||
"node_modules\\detect-libc"
|
||||
],
|
||||
"semver@7.8.5": [
|
||||
"node_modules\\semver"
|
||||
],
|
||||
"@img/sharp-win32-arm64@0.35.5": [
|
||||
"node_modules\\@img\\sharp-win32-arm64"
|
||||
],
|
||||
"bmp-js@0.1.0": [
|
||||
"node_modules\\bmp-js"
|
||||
],
|
||||
"idb-keyval@6.3.0": [
|
||||
"node_modules\\idb-keyval"
|
||||
],
|
||||
"is-url@1.2.4": [
|
||||
"node_modules\\is-url"
|
||||
],
|
||||
"node-fetch@2.7.0": [
|
||||
"node_modules\\node-fetch"
|
||||
],
|
||||
"opencollective-postinstall@2.0.3": [
|
||||
"node_modules\\opencollective-postinstall"
|
||||
],
|
||||
"regenerator-runtime@0.13.11": [
|
||||
"node_modules\\regenerator-runtime"
|
||||
],
|
||||
"tesseract.js-core@7.0.0": [
|
||||
"node_modules\\tesseract.js-core"
|
||||
],
|
||||
"wasm-feature-detect@1.9.0": [
|
||||
"node_modules\\wasm-feature-detect"
|
||||
],
|
||||
"zlibjs@0.3.1": [
|
||||
"node_modules\\zlibjs"
|
||||
],
|
||||
"undici-types@7.24.6": [
|
||||
"node_modules\\undici-types"
|
||||
],
|
||||
"inherits@2.0.4": [
|
||||
"node_modules\\inherits"
|
||||
],
|
||||
"minimalistic-assert@1.0.1": [
|
||||
"node_modules\\minimalistic-assert"
|
||||
],
|
||||
"lie@3.3.0": [
|
||||
"node_modules\\lie"
|
||||
],
|
||||
"readable-stream@2.3.8": [
|
||||
"node_modules\\readable-stream"
|
||||
],
|
||||
"setimmediate@1.0.5": [
|
||||
"node_modules\\setimmediate"
|
||||
],
|
||||
"sax@1.6.1": [
|
||||
"node_modules\\sax"
|
||||
],
|
||||
"anymatch@2.0.0": [
|
||||
"node_modules\\anymatch"
|
||||
],
|
||||
"async-each@1.0.6": [
|
||||
"node_modules\\async-each"
|
||||
],
|
||||
"braces@2.3.2": [
|
||||
"node_modules\\braces"
|
||||
],
|
||||
"glob-parent@3.1.0": [
|
||||
"node_modules\\glob-parent"
|
||||
],
|
||||
"is-binary-path@1.0.1": [
|
||||
"node_modules\\is-binary-path"
|
||||
],
|
||||
"path-is-absolute@1.0.1": [
|
||||
"node_modules\\path-is-absolute"
|
||||
],
|
||||
"readdirp@2.2.1": [
|
||||
"node_modules\\readdirp"
|
||||
],
|
||||
"upath@1.2.0": [
|
||||
"node_modules\\upath"
|
||||
],
|
||||
"is-extglob@2.1.1": [
|
||||
"node_modules\\is-extglob"
|
||||
],
|
||||
"ms@2.0.0": [
|
||||
"node_modules\\debug\\node_modules\\ms"
|
||||
],
|
||||
"on-finished@2.3.0": [
|
||||
"node_modules\\finalhandler\\node_modules\\on-finished"
|
||||
],
|
||||
"parseurl@1.3.3": [
|
||||
"node_modules\\parseurl"
|
||||
],
|
||||
"utils-merge@1.0.1": [
|
||||
"node_modules\\utils-merge"
|
||||
],
|
||||
"vary@1.1.2": [
|
||||
"node_modules\\vary"
|
||||
],
|
||||
"duplexer@0.1.2": [
|
||||
"node_modules\\duplexer"
|
||||
],
|
||||
"from@0.1.7": [
|
||||
"node_modules\\from"
|
||||
],
|
||||
"map-stream@0.1.0": [
|
||||
"node_modules\\map-stream"
|
||||
],
|
||||
"pause-stream@0.0.11": [
|
||||
"node_modules\\pause-stream"
|
||||
],
|
||||
"split@0.3.3": [
|
||||
"node_modules\\split"
|
||||
],
|
||||
"stream-combiner@0.0.4": [
|
||||
"node_modules\\stream-combiner"
|
||||
],
|
||||
"through@2.3.8": [
|
||||
"node_modules\\through"
|
||||
],
|
||||
"websocket-driver@0.7.5": [
|
||||
"node_modules\\websocket-driver"
|
||||
],
|
||||
"apache-crypt@1.2.6": [
|
||||
"node_modules\\apache-crypt"
|
||||
],
|
||||
"apache-md5@1.1.8": [
|
||||
"node_modules\\apache-md5"
|
||||
],
|
||||
"bcryptjs@2.4.3": [
|
||||
"node_modules\\bcryptjs"
|
||||
],
|
||||
"uuid@3.4.0": [
|
||||
"node_modules\\uuid"
|
||||
],
|
||||
"basic-auth@2.0.1": [
|
||||
"node_modules\\basic-auth"
|
||||
],
|
||||
"depd@2.0.0": [
|
||||
"node_modules\\depd"
|
||||
],
|
||||
"on-finished@2.4.1": [
|
||||
"node_modules\\on-finished"
|
||||
],
|
||||
"on-headers@1.1.0": [
|
||||
"node_modules\\on-headers"
|
||||
],
|
||||
"is-wsl@1.1.0": [
|
||||
"node_modules\\is-wsl"
|
||||
],
|
||||
"escape-html@1.0.3": [
|
||||
"node_modules\\escape-html"
|
||||
],
|
||||
"etag@1.8.1": [
|
||||
"node_modules\\etag"
|
||||
],
|
||||
"fresh@2.0.0": [
|
||||
"node_modules\\fresh"
|
||||
],
|
||||
"ms@2.1.3": [
|
||||
"node_modules\\ms"
|
||||
],
|
||||
"range-parser@1.3.0": [
|
||||
"node_modules\\range-parser"
|
||||
],
|
||||
"mime-db@1.54.0": [
|
||||
"node_modules\\mime-db"
|
||||
],
|
||||
"accepts@1.3.8": [
|
||||
"node_modules\\accepts"
|
||||
],
|
||||
"batch@0.6.1": [
|
||||
"node_modules\\batch"
|
||||
],
|
||||
"mime-db@1.52.0": [
|
||||
"node_modules\\mime-types\\node_modules\\mime-db"
|
||||
],
|
||||
"setprototypeof@1.2.0": [
|
||||
"node_modules\\setprototypeof"
|
||||
],
|
||||
"statuses@1.5.0": [
|
||||
"node_modules\\statuses"
|
||||
],
|
||||
"toidentifier@1.0.1": [
|
||||
"node_modules\\toidentifier"
|
||||
],
|
||||
"queue@6.0.2": [
|
||||
"node_modules\\queue"
|
||||
],
|
||||
"whatwg-url@5.0.0": [
|
||||
"node_modules\\whatwg-url"
|
||||
],
|
||||
"immediate@3.0.6": [
|
||||
"node_modules\\immediate"
|
||||
],
|
||||
"core-util-is@1.0.3": [
|
||||
"node_modules\\core-util-is"
|
||||
],
|
||||
"isarray@1.0.0": [
|
||||
"node_modules\\isarray"
|
||||
],
|
||||
"process-nextick-args@2.0.1": [
|
||||
"node_modules\\process-nextick-args"
|
||||
],
|
||||
"safe-buffer@5.1.2": [
|
||||
"node_modules\\safe-buffer"
|
||||
],
|
||||
"string_decoder@1.1.1": [
|
||||
"node_modules\\string_decoder"
|
||||
],
|
||||
"util-deprecate@1.0.2": [
|
||||
"node_modules\\util-deprecate"
|
||||
],
|
||||
"define-property@2.0.2": [
|
||||
"node_modules\\micromatch\\node_modules\\define-property",
|
||||
"node_modules\\to-regex\\node_modules\\define-property",
|
||||
"node_modules\\nanomatch\\node_modules\\define-property"
|
||||
],
|
||||
"extend-shallow@3.0.2": [
|
||||
"node_modules\\micromatch\\node_modules\\extend-shallow",
|
||||
"node_modules\\split-string\\node_modules\\extend-shallow",
|
||||
"node_modules\\to-regex\\node_modules\\extend-shallow",
|
||||
"node_modules\\nanomatch\\node_modules\\extend-shallow",
|
||||
"node_modules\\regex-not\\node_modules\\extend-shallow"
|
||||
],
|
||||
"kind-of@6.0.3": [
|
||||
"node_modules\\micromatch\\node_modules\\kind-of",
|
||||
"node_modules\\nanomatch\\node_modules\\kind-of"
|
||||
],
|
||||
"is-extendable@1.0.1": [
|
||||
"node_modules\\micromatch\\node_modules\\is-extendable",
|
||||
"node_modules\\split-string\\node_modules\\is-extendable",
|
||||
"node_modules\\to-regex\\node_modules\\is-extendable",
|
||||
"node_modules\\nanomatch\\node_modules\\is-extendable",
|
||||
"node_modules\\regex-not\\node_modules\\is-extendable",
|
||||
"node_modules\\mixin-deep\\node_modules\\is-extendable"
|
||||
],
|
||||
"normalize-path@2.1.1": [
|
||||
"node_modules\\normalize-path"
|
||||
],
|
||||
"arr-flatten@1.1.0": [
|
||||
"node_modules\\arr-flatten"
|
||||
],
|
||||
"array-unique@0.3.2": [
|
||||
"node_modules\\array-unique"
|
||||
],
|
||||
"extend-shallow@2.0.1": [
|
||||
"node_modules\\extend-shallow"
|
||||
],
|
||||
"fill-range@4.0.0": [
|
||||
"node_modules\\fill-range"
|
||||
],
|
||||
"isobject@3.0.1": [
|
||||
"node_modules\\isobject"
|
||||
],
|
||||
"repeat-element@1.1.4": [
|
||||
"node_modules\\repeat-element"
|
||||
],
|
||||
"snapdragon@0.8.2": [
|
||||
"node_modules\\snapdragon"
|
||||
],
|
||||
"define-property@1.0.0": [
|
||||
"node_modules\\snapdragon-node\\node_modules\\define-property",
|
||||
"node_modules\\extglob\\node_modules\\define-property",
|
||||
"node_modules\\base\\node_modules\\define-property"
|
||||
],
|
||||
"is-glob@3.1.0": [
|
||||
"node_modules\\is-glob"
|
||||
],
|
||||
"path-dirname@1.0.2": [
|
||||
"node_modules\\path-dirname"
|
||||
],
|
||||
"binary-extensions@1.13.1": [
|
||||
"node_modules\\binary-extensions"
|
||||
],
|
||||
"graceful-fs@4.2.11": [
|
||||
"node_modules\\graceful-fs"
|
||||
],
|
||||
"encodeurl@1.0.2": [
|
||||
"node_modules\\encodeurl"
|
||||
],
|
||||
"unpipe@1.0.0": [
|
||||
"node_modules\\unpipe"
|
||||
],
|
||||
"ee-first@1.1.1": [
|
||||
"node_modules\\ee-first"
|
||||
],
|
||||
"http-parser-js@0.5.10": [
|
||||
"node_modules\\http-parser-js"
|
||||
],
|
||||
"websocket-extensions@0.1.4": [
|
||||
"node_modules\\websocket-extensions"
|
||||
],
|
||||
"unix-crypt-td-js@1.1.4": [
|
||||
"node_modules\\unix-crypt-td-js"
|
||||
],
|
||||
"negotiator@0.6.3": [
|
||||
"node_modules\\negotiator"
|
||||
],
|
||||
"tr46@0.0.3": [
|
||||
"node_modules\\tr46"
|
||||
],
|
||||
"webidl-conversions@3.0.1": [
|
||||
"node_modules\\webidl-conversions"
|
||||
],
|
||||
"arr-diff@4.0.0": [
|
||||
"node_modules\\arr-diff"
|
||||
],
|
||||
"fragment-cache@0.2.1": [
|
||||
"node_modules\\fragment-cache"
|
||||
],
|
||||
"object.pick@1.3.0": [
|
||||
"node_modules\\object.pick"
|
||||
],
|
||||
"is-descriptor@1.0.4": [
|
||||
"node_modules\\is-descriptor"
|
||||
],
|
||||
"assign-symbols@1.0.0": [
|
||||
"node_modules\\assign-symbols"
|
||||
],
|
||||
"is-plain-object@2.0.4": [
|
||||
"node_modules\\is-plain-object"
|
||||
],
|
||||
"remove-trailing-separator@1.1.0": [
|
||||
"node_modules\\remove-trailing-separator"
|
||||
],
|
||||
"is-extendable@0.1.1": [
|
||||
"node_modules\\is-extendable"
|
||||
],
|
||||
"is-number@3.0.0": [
|
||||
"node_modules\\is-number"
|
||||
],
|
||||
"repeat-string@1.6.1": [
|
||||
"node_modules\\repeat-string"
|
||||
],
|
||||
"to-regex-range@2.1.1": [
|
||||
"node_modules\\to-regex-range"
|
||||
],
|
||||
"is-descriptor@0.1.8": [
|
||||
"node_modules\\define-property\\node_modules\\is-descriptor"
|
||||
],
|
||||
"map-cache@0.2.2": [
|
||||
"node_modules\\map-cache"
|
||||
],
|
||||
"source-map@0.5.7": [
|
||||
"node_modules\\source-map"
|
||||
],
|
||||
"source-map-resolve@0.5.3": [
|
||||
"node_modules\\source-map-resolve"
|
||||
],
|
||||
"use@3.1.1": [
|
||||
"node_modules\\use"
|
||||
],
|
||||
"snapdragon-util@3.0.1": [
|
||||
"node_modules\\snapdragon-util"
|
||||
],
|
||||
"safe-regex@1.1.0": [
|
||||
"node_modules\\safe-regex"
|
||||
],
|
||||
"expand-brackets@2.1.4": [
|
||||
"node_modules\\expand-brackets"
|
||||
],
|
||||
"is-windows@1.0.2": [
|
||||
"node_modules\\is-windows"
|
||||
],
|
||||
"is-accessor-descriptor@1.0.2": [
|
||||
"node_modules\\is-accessor-descriptor"
|
||||
],
|
||||
"is-data-descriptor@1.0.1": [
|
||||
"node_modules\\is-data-descriptor"
|
||||
],
|
||||
"kind-of@3.2.2": [
|
||||
"node_modules\\kind-of"
|
||||
],
|
||||
"cache-base@1.0.1": [
|
||||
"node_modules\\cache-base"
|
||||
],
|
||||
"class-utils@0.3.6": [
|
||||
"node_modules\\class-utils"
|
||||
],
|
||||
"component-emitter@1.3.1": [
|
||||
"node_modules\\component-emitter"
|
||||
],
|
||||
"pascalcase@0.1.1": [
|
||||
"node_modules\\pascalcase"
|
||||
],
|
||||
"atob@2.1.2": [
|
||||
"node_modules\\atob"
|
||||
],
|
||||
"decode-uri-component@0.2.2": [
|
||||
"node_modules\\decode-uri-component"
|
||||
],
|
||||
"resolve-url@0.2.1": [
|
||||
"node_modules\\resolve-url"
|
||||
],
|
||||
"source-map-url@0.4.1": [
|
||||
"node_modules\\source-map-url"
|
||||
],
|
||||
"urix@0.1.0": [
|
||||
"node_modules\\urix"
|
||||
],
|
||||
"ret@0.1.15": [
|
||||
"node_modules\\ret"
|
||||
],
|
||||
"posix-character-classes@0.1.1": [
|
||||
"node_modules\\posix-character-classes"
|
||||
],
|
||||
"hasown@2.0.4": [
|
||||
"node_modules\\hasown"
|
||||
],
|
||||
"is-buffer@1.1.6": [
|
||||
"node_modules\\is-buffer"
|
||||
],
|
||||
"collection-visit@1.0.0": [
|
||||
"node_modules\\collection-visit"
|
||||
],
|
||||
"get-value@2.0.6": [
|
||||
"node_modules\\get-value"
|
||||
],
|
||||
"has-value@1.0.0": [
|
||||
"node_modules\\has-value"
|
||||
],
|
||||
"set-value@2.0.1": [
|
||||
"node_modules\\set-value"
|
||||
],
|
||||
"to-object-path@0.3.0": [
|
||||
"node_modules\\to-object-path"
|
||||
],
|
||||
"union-value@1.0.1": [
|
||||
"node_modules\\union-value"
|
||||
],
|
||||
"isobject@2.1.0": [
|
||||
"node_modules\\unset-value\\node_modules\\has-value\\node_modules\\isobject"
|
||||
],
|
||||
"has-values@0.1.4": [
|
||||
"node_modules\\unset-value\\node_modules\\has-values"
|
||||
],
|
||||
"arr-union@3.1.0": [
|
||||
"node_modules\\arr-union"
|
||||
],
|
||||
"static-extend@0.1.2": [
|
||||
"node_modules\\static-extend"
|
||||
],
|
||||
"for-in@1.0.2": [
|
||||
"node_modules\\for-in"
|
||||
],
|
||||
"function-bind@1.1.2": [
|
||||
"node_modules\\function-bind"
|
||||
],
|
||||
"map-visit@1.0.0": [
|
||||
"node_modules\\map-visit"
|
||||
],
|
||||
"object-visit@1.0.1": [
|
||||
"node_modules\\object-visit"
|
||||
],
|
||||
"kind-of@4.0.0": [
|
||||
"node_modules\\has-values\\node_modules\\kind-of"
|
||||
],
|
||||
"object-copy@0.1.0": [
|
||||
"node_modules\\object-copy"
|
||||
],
|
||||
"copy-descriptor@0.1.1": [
|
||||
"node_modules\\copy-descriptor"
|
||||
],
|
||||
"playwright@1.62.1": [
|
||||
"node_modules\\playwright"
|
||||
],
|
||||
"pptxgenjs@4.0.1": [
|
||||
"node_modules\\pptxgenjs"
|
||||
],
|
||||
"chokidar@2.1.8": [
|
||||
"node_modules\\chokidar"
|
||||
],
|
||||
"send@1.2.1": [
|
||||
"node_modules\\send"
|
||||
],
|
||||
"serve-index@1.9.2": [
|
||||
"node_modules\\serve-index"
|
||||
],
|
||||
"debug@2.6.9": [
|
||||
"node_modules\\debug"
|
||||
],
|
||||
"finalhandler@1.1.2": [
|
||||
"node_modules\\finalhandler"
|
||||
],
|
||||
"http-errors@2.0.1": [
|
||||
"node_modules\\http-errors"
|
||||
],
|
||||
"mime-types@2.1.35": [
|
||||
"node_modules\\mime-types"
|
||||
],
|
||||
"micromatch@3.1.10": [
|
||||
"node_modules\\micromatch"
|
||||
],
|
||||
"snapdragon-node@2.1.1": [
|
||||
"node_modules\\snapdragon-node"
|
||||
],
|
||||
"split-string@3.1.0": [
|
||||
"node_modules\\split-string"
|
||||
],
|
||||
"to-regex@3.0.2": [
|
||||
"node_modules\\to-regex"
|
||||
],
|
||||
"extglob@2.0.4": [
|
||||
"node_modules\\extglob"
|
||||
],
|
||||
"nanomatch@1.2.13": [
|
||||
"node_modules\\nanomatch"
|
||||
],
|
||||
"regex-not@1.0.2": [
|
||||
"node_modules\\regex-not"
|
||||
],
|
||||
"base@0.11.2": [
|
||||
"node_modules\\base"
|
||||
],
|
||||
"define-property@0.2.5": [
|
||||
"node_modules\\define-property"
|
||||
],
|
||||
"mixin-deep@1.3.2": [
|
||||
"node_modules\\mixin-deep"
|
||||
],
|
||||
"has-value@0.3.1": [
|
||||
"node_modules\\unset-value\\node_modules\\has-value"
|
||||
],
|
||||
"has-values@1.0.0": [
|
||||
"node_modules\\has-values"
|
||||
],
|
||||
"unset-value@1.0.0": [
|
||||
"node_modules\\unset-value"
|
||||
]
|
||||
},
|
||||
"nodeLinker": "hoisted",
|
||||
"packageManager": "pnpm@11.25.0",
|
||||
"pendingBuilds": [],
|
||||
"publicHoistPattern": [],
|
||||
"prunedAt": "Wed, 07 Oct 2026 19:15:07 GMT",
|
||||
"skipped": [
|
||||
"@emnapi/runtime@1.11.3",
|
||||
"@img/sharp-darwin-arm64@0.35.5",
|
||||
"@img/sharp-darwin-x64@0.35.5",
|
||||
"@img/sharp-freebsd-wasm32@0.35.5",
|
||||
"@img/sharp-libvips-darwin-arm64@1.3.4",
|
||||
"@img/sharp-libvips-darwin-x64@1.3.4",
|
||||
"@img/sharp-libvips-linux-arm64@1.3.4",
|
||||
"@img/sharp-libvips-linux-arm@1.3.4",
|
||||
"@img/sharp-libvips-linux-ppc64@1.3.4",
|
||||
"@img/sharp-libvips-linux-riscv64@1.3.4",
|
||||
"@img/sharp-libvips-linux-s390x@1.3.4",
|
||||
"@img/sharp-libvips-linux-x64@1.3.4",
|
||||
"@img/sharp-libvips-linuxmusl-arm64@1.3.4",
|
||||
"@img/sharp-libvips-linuxmusl-x64@1.3.4",
|
||||
"@img/sharp-linux-arm64@0.35.5",
|
||||
"@img/sharp-linux-arm@0.35.5",
|
||||
"@img/sharp-linux-ppc64@0.35.5",
|
||||
"@img/sharp-linux-riscv64@0.35.5",
|
||||
"@img/sharp-linux-s390x@0.35.5",
|
||||
"@img/sharp-linux-x64@0.35.5",
|
||||
"@img/sharp-linuxmusl-arm64@0.35.5",
|
||||
"@img/sharp-linuxmusl-x64@0.35.5",
|
||||
"@img/sharp-wasm32@0.35.5",
|
||||
"@img/sharp-webcontainers-wasm32@0.35.5",
|
||||
"@img/sharp-win32-ia32@0.35.5",
|
||||
"@img/sharp-win32-x64@0.35.5",
|
||||
"@napi-rs/canvas-android-arm64@0.1.100",
|
||||
"@napi-rs/canvas-darwin-arm64@0.1.100",
|
||||
"@napi-rs/canvas-darwin-x64@0.1.100",
|
||||
"@napi-rs/canvas-linux-arm-gnueabihf@0.1.100",
|
||||
"@napi-rs/canvas-linux-arm64-gnu@0.1.100",
|
||||
"@napi-rs/canvas-linux-arm64-musl@0.1.100",
|
||||
"@napi-rs/canvas-linux-riscv64-gnu@0.1.100",
|
||||
"@napi-rs/canvas-linux-x64-gnu@0.1.100",
|
||||
"@napi-rs/canvas-linux-x64-musl@0.1.100",
|
||||
"@napi-rs/canvas-win32-x64-msvc@0.1.100",
|
||||
"bindings@1.5.0",
|
||||
"file-uri-to-path@1.0.0",
|
||||
"fsevents@1.2.13",
|
||||
"fsevents@2.3.2",
|
||||
"nan@2.28.0",
|
||||
"tslib@2.8.1"
|
||||
],
|
||||
"storeDir": "C:\\Users\\runneradmin\\AppData\\Local\\pnpm\\store\\v11",
|
||||
"virtualStoreDir": "C:\\Users\\runneradmin\\AppData\\Local\\Temp\\codex-primary-runtime-wf1SNt\\install\\node_modules\\.pnpm",
|
||||
"virtualStoreDirMaxLength": 60,
|
||||
"allowBuilds": {
|
||||
"fsevents@1.2.13": false,
|
||||
"tesseract.js@7.0.0": false
|
||||
}
|
||||
}
|
||||
+1
File diff suppressed because one or more lines are too long
Generated
Vendored
+44
@@ -0,0 +1,44 @@
|
||||
{
|
||||
"lastValidatedTimestamp": 1791400507461,
|
||||
"projects": {
|
||||
"C:\\Users\\runneradmin\\AppData\\Local\\Temp\\codex-primary-runtime-wf1SNt\\install": {
|
||||
"name": "@openai/codex-electron-bundled-runtimes",
|
||||
"version": "0.0.0"
|
||||
}
|
||||
},
|
||||
"pnpmfiles": [],
|
||||
"settings": {
|
||||
"enableGlobalVirtualStore": false,
|
||||
"allowBuilds": {
|
||||
"fsevents@1.2.13": false,
|
||||
"tesseract.js@7.0.0": false
|
||||
},
|
||||
"autoInstallPeers": true,
|
||||
"catalogs": {},
|
||||
"dedupeDirectDeps": false,
|
||||
"dedupeInjectedDeps": true,
|
||||
"dedupePeerDependents": true,
|
||||
"dedupePeers": false,
|
||||
"dev": false,
|
||||
"excludeLinksFromLockfile": false,
|
||||
"hoistPattern": [
|
||||
"*"
|
||||
],
|
||||
"hoistWorkspacePackages": true,
|
||||
"injectWorkspacePackages": false,
|
||||
"linkWorkspacePackages": false,
|
||||
"minimumReleaseAge": "10080",
|
||||
"minimumReleaseAgeStrict": true,
|
||||
"minimumReleaseAgeIgnoreMissingTime": false,
|
||||
"nodeLinker": "hoisted",
|
||||
"optional": true,
|
||||
"peersSuffixMaxLength": 1000,
|
||||
"preferWorkspacePackages": false,
|
||||
"production": true,
|
||||
"publicHoistPattern": [],
|
||||
"workspacePackagePatterns": [
|
||||
"."
|
||||
]
|
||||
},
|
||||
"filteredInstall": false
|
||||
}
|
||||
+2261
File diff suppressed because it is too large
Load Diff
+82
@@ -0,0 +1,82 @@
|
||||
# Licensing
|
||||
|
||||
## color
|
||||
|
||||
Copyright (c) 2012 Heather Arthur
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of this software and associated documentation files (the
|
||||
"Software"), to deal in the Software without restriction, including
|
||||
without limitation the rights to use, copy, modify, merge, publish,
|
||||
distribute, sublicense, and/or sell copies of the Software, and to
|
||||
permit persons to whom the Software is furnished to do so, subject to
|
||||
the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be
|
||||
included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
## color-convert
|
||||
|
||||
Copyright (c) 2011-2016 Heather Arthur <fayearthur@gmail.com>.
|
||||
Copyright (c) 2016-2021 Josh Junon <josh@junon.me>.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of this software and associated documentation files (the
|
||||
"Software"), to deal in the Software without restriction, including
|
||||
without limitation the rights to use, copy, modify, merge, publish,
|
||||
distribute, sublicense, and/or sell copies of the Software, and to
|
||||
permit persons to whom the Software is furnished to do so, subject to
|
||||
the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be
|
||||
included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
## color-string
|
||||
|
||||
Copyright (c) 2011 Heather Arthur <fayearthur@gmail.com>
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of this software and associated documentation files (the
|
||||
"Software"), to deal in the Software without restriction, including
|
||||
without limitation the rights to use, copy, modify, merge, publish,
|
||||
distribute, sublicense, and/or sell copies of the Software, and to
|
||||
permit persons to whom the Software is furnished to do so, subject to
|
||||
the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be
|
||||
included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
## color-name
|
||||
|
||||
The MIT License (MIT)
|
||||
Copyright (c) 2015 Dmitry Ivanov
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
# `@img/colour`
|
||||
|
||||
The latest version of the
|
||||
[color](https://www.npmjs.com/package/color)
|
||||
package is now ESM-only,
|
||||
however some JavaScript runtimes do not yet support this,
|
||||
which includes versions of Node.js prior to 20.19.0.
|
||||
|
||||
This package converts the `color` package and its dependencies,
|
||||
all of which are MIT-licensed, to CommonJS.
|
||||
|
||||
- [color](https://www.npmjs.com/package/color)
|
||||
- [color-convert](https://www.npmjs.com/package/color-convert)
|
||||
- [color-string](https://www.npmjs.com/package/color-string)
|
||||
- [color-name](https://www.npmjs.com/package/color-name)
|
||||
+1596
File diff suppressed because it is too large
Load Diff
+1
@@ -0,0 +1 @@
|
||||
module.exports = require("./color.cjs").default;
|
||||
+929
@@ -0,0 +1,929 @@
|
||||
// Generated by dts-bundle-generator v9.5.1
|
||||
|
||||
type Channels = number;
|
||||
type RGB = [
|
||||
r: number,
|
||||
g: number,
|
||||
b: number
|
||||
];
|
||||
type HSL = [
|
||||
h: number,
|
||||
s: number,
|
||||
l: number
|
||||
];
|
||||
type HSV = [
|
||||
h: number,
|
||||
s: number,
|
||||
v: number
|
||||
];
|
||||
type CMYK = [
|
||||
c: number,
|
||||
m: number,
|
||||
y: number,
|
||||
k: number
|
||||
];
|
||||
type LAB = [
|
||||
l: number,
|
||||
a: number,
|
||||
b: number
|
||||
];
|
||||
type LCH = [
|
||||
l: number,
|
||||
c: number,
|
||||
h: number
|
||||
];
|
||||
type HCG = [
|
||||
h: number,
|
||||
c: number,
|
||||
g: number
|
||||
];
|
||||
type HWB = [
|
||||
h: number,
|
||||
w: number,
|
||||
b: number
|
||||
];
|
||||
type XYZ = [
|
||||
x: number,
|
||||
y: number,
|
||||
z: number
|
||||
];
|
||||
type Apple = [
|
||||
r16: number,
|
||||
g16: number,
|
||||
b16: number
|
||||
];
|
||||
type Gray = [
|
||||
gray: number
|
||||
];
|
||||
type ANSI16 = number;
|
||||
type ANSI256 = number;
|
||||
type Keyword = string;
|
||||
type HEX = string;
|
||||
declare namespace route {
|
||||
type rgb = {
|
||||
hsl(from: RGB): HSL;
|
||||
hsl(...from: RGB): HSL;
|
||||
hsl(from: RGB): HSL;
|
||||
hsl(...from: RGB): HSL;
|
||||
hsv(from: RGB): HSV;
|
||||
hsv(...from: RGB): HSV;
|
||||
hwb(from: RGB): HWB;
|
||||
hwb(...from: RGB): HWB;
|
||||
cmyk(from: RGB): CMYK;
|
||||
cmyk(...from: RGB): CMYK;
|
||||
xyz(from: RGB): XYZ;
|
||||
xyz(...from: RGB): XYZ;
|
||||
lab(from: RGB): LAB;
|
||||
lab(...from: RGB): LAB;
|
||||
lch(from: RGB): LCH;
|
||||
lch(...from: RGB): LCH;
|
||||
hex(from: RGB): HEX;
|
||||
hex(...from: RGB): HEX;
|
||||
keyword(from: RGB): Keyword;
|
||||
keyword(...from: RGB): Keyword;
|
||||
ansi16(from: RGB): ANSI16;
|
||||
ansi16(...from: RGB): ANSI16;
|
||||
ansi256(from: RGB): ANSI256;
|
||||
ansi256(...from: RGB): ANSI256;
|
||||
hcg(from: RGB): HCG;
|
||||
hcg(...from: RGB): HCG;
|
||||
apple(from: RGB): Apple;
|
||||
apple(...from: RGB): Apple;
|
||||
gray(from: RGB): Gray;
|
||||
gray(...from: RGB): Gray;
|
||||
};
|
||||
type hsl = {
|
||||
rgb(from: HSL): RGB;
|
||||
rgb(...from: HSL): RGB;
|
||||
hsv(from: HSL): HSV;
|
||||
hsv(...from: HSL): HSV;
|
||||
hwb(from: HSL): HWB;
|
||||
hwb(...from: HSL): HWB;
|
||||
cmyk(from: HSL): CMYK;
|
||||
cmyk(...from: HSL): CMYK;
|
||||
xyz(from: HSL): XYZ;
|
||||
xyz(...from: HSL): XYZ;
|
||||
lab(from: HSL): LAB;
|
||||
lab(...from: HSL): LAB;
|
||||
lch(from: HSL): LCH;
|
||||
lch(...from: HSL): LCH;
|
||||
hex(from: HSL): HEX;
|
||||
hex(...from: HSL): HEX;
|
||||
keyword(from: HSL): Keyword;
|
||||
keyword(...from: HSL): Keyword;
|
||||
ansi16(from: HSL): ANSI16;
|
||||
ansi16(...from: HSL): ANSI16;
|
||||
ansi256(from: HSL): ANSI256;
|
||||
ansi256(...from: HSL): ANSI256;
|
||||
hcg(from: HSL): HCG;
|
||||
hcg(...from: HSL): HCG;
|
||||
apple(from: HSL): Apple;
|
||||
apple(...from: HSL): Apple;
|
||||
gray(from: HSL): Gray;
|
||||
gray(...from: HSL): Gray;
|
||||
};
|
||||
type hsv = {
|
||||
rgb(from: HSV): RGB;
|
||||
rgb(...from: HSV): RGB;
|
||||
hsl(from: HSV): HSL;
|
||||
hsl(...from: HSV): HSL;
|
||||
hwb(from: HSV): HWB;
|
||||
hwb(...from: HSV): HWB;
|
||||
cmyk(from: HSV): CMYK;
|
||||
cmyk(...from: HSV): CMYK;
|
||||
xyz(from: HSV): XYZ;
|
||||
xyz(...from: HSV): XYZ;
|
||||
lab(from: HSV): LAB;
|
||||
lab(...from: HSV): LAB;
|
||||
lch(from: HSV): LCH;
|
||||
lch(...from: HSV): LCH;
|
||||
hex(from: HSV): HEX;
|
||||
hex(...from: HSV): HEX;
|
||||
keyword(from: HSV): Keyword;
|
||||
keyword(...from: HSV): Keyword;
|
||||
ansi16(from: HSV): ANSI16;
|
||||
ansi16(...from: HSV): ANSI16;
|
||||
ansi256(from: HSV): ANSI256;
|
||||
ansi256(...from: HSV): ANSI256;
|
||||
hcg(from: HSV): HCG;
|
||||
hcg(...from: HSV): HCG;
|
||||
apple(from: HSV): Apple;
|
||||
apple(...from: HSV): Apple;
|
||||
gray(from: HSV): Gray;
|
||||
gray(...from: HSV): Gray;
|
||||
};
|
||||
type hwb = {
|
||||
rgb(from: HWB): RGB;
|
||||
rgb(...from: HWB): RGB;
|
||||
hsl(from: HWB): HSL;
|
||||
hsl(...from: HWB): HSL;
|
||||
hsv(from: HWB): HSV;
|
||||
hsv(...from: HWB): HSV;
|
||||
cmyk(from: HWB): CMYK;
|
||||
cmyk(...from: HWB): CMYK;
|
||||
xyz(from: HWB): XYZ;
|
||||
xyz(...from: HWB): XYZ;
|
||||
lab(from: HWB): LAB;
|
||||
lab(...from: HWB): LAB;
|
||||
lch(from: HWB): LCH;
|
||||
lch(...from: HWB): LCH;
|
||||
hex(from: HWB): HEX;
|
||||
hex(...from: HWB): HEX;
|
||||
keyword(from: HWB): Keyword;
|
||||
keyword(...from: HWB): Keyword;
|
||||
ansi16(from: HWB): ANSI16;
|
||||
ansi16(...from: HWB): ANSI16;
|
||||
ansi256(from: HWB): ANSI256;
|
||||
ansi256(...from: HWB): ANSI256;
|
||||
hcg(from: HWB): HCG;
|
||||
hcg(...from: HWB): HCG;
|
||||
apple(from: HWB): Apple;
|
||||
apple(...from: HWB): Apple;
|
||||
gray(from: HWB): Gray;
|
||||
gray(...from: HWB): Gray;
|
||||
};
|
||||
type cmyk = {
|
||||
rgb(from: CMYK): RGB;
|
||||
rgb(...from: CMYK): RGB;
|
||||
hsl(from: CMYK): HSL;
|
||||
hsl(...from: CMYK): HSL;
|
||||
hsv(from: CMYK): HSV;
|
||||
hsv(...from: CMYK): HSV;
|
||||
hwb(from: CMYK): HWB;
|
||||
hwb(...from: CMYK): HWB;
|
||||
xyz(from: CMYK): XYZ;
|
||||
xyz(...from: CMYK): XYZ;
|
||||
lab(from: CMYK): LAB;
|
||||
lab(...from: CMYK): LAB;
|
||||
lch(from: CMYK): LCH;
|
||||
lch(...from: CMYK): LCH;
|
||||
hex(from: CMYK): HEX;
|
||||
hex(...from: CMYK): HEX;
|
||||
keyword(from: CMYK): Keyword;
|
||||
keyword(...from: CMYK): Keyword;
|
||||
ansi16(from: CMYK): ANSI16;
|
||||
ansi16(...from: CMYK): ANSI16;
|
||||
ansi256(from: CMYK): ANSI256;
|
||||
ansi256(...from: CMYK): ANSI256;
|
||||
hcg(from: CMYK): HCG;
|
||||
hcg(...from: CMYK): HCG;
|
||||
apple(from: CMYK): Apple;
|
||||
apple(...from: CMYK): Apple;
|
||||
gray(from: CMYK): Gray;
|
||||
gray(...from: CMYK): Gray;
|
||||
};
|
||||
type xyz = {
|
||||
rgb(from: XYZ): RGB;
|
||||
rgb(...from: XYZ): RGB;
|
||||
hsl(from: XYZ): HSL;
|
||||
hsl(...from: XYZ): HSL;
|
||||
hsv(from: XYZ): HSV;
|
||||
hsv(...from: XYZ): HSV;
|
||||
hwb(from: XYZ): HWB;
|
||||
hwb(...from: XYZ): HWB;
|
||||
cmyk(from: XYZ): CMYK;
|
||||
cmyk(...from: XYZ): CMYK;
|
||||
lab(from: XYZ): LAB;
|
||||
lab(...from: XYZ): LAB;
|
||||
lch(from: XYZ): LCH;
|
||||
lch(...from: XYZ): LCH;
|
||||
hex(from: XYZ): HEX;
|
||||
hex(...from: XYZ): HEX;
|
||||
keyword(from: XYZ): Keyword;
|
||||
keyword(...from: XYZ): Keyword;
|
||||
ansi16(from: XYZ): ANSI16;
|
||||
ansi16(...from: XYZ): ANSI16;
|
||||
ansi256(from: XYZ): ANSI256;
|
||||
ansi256(...from: XYZ): ANSI256;
|
||||
hcg(from: XYZ): HCG;
|
||||
hcg(...from: XYZ): HCG;
|
||||
apple(from: XYZ): Apple;
|
||||
apple(...from: XYZ): Apple;
|
||||
gray(from: XYZ): Gray;
|
||||
gray(...from: XYZ): Gray;
|
||||
};
|
||||
type lab = {
|
||||
rgb(from: LAB): RGB;
|
||||
rgb(...from: LAB): RGB;
|
||||
hsl(from: LAB): HSL;
|
||||
hsl(...from: LAB): HSL;
|
||||
hsv(from: LAB): HSV;
|
||||
hsv(...from: LAB): HSV;
|
||||
hwb(from: LAB): HWB;
|
||||
hwb(...from: LAB): HWB;
|
||||
cmyk(from: LAB): CMYK;
|
||||
cmyk(...from: LAB): CMYK;
|
||||
xyz(from: LAB): XYZ;
|
||||
xyz(...from: LAB): XYZ;
|
||||
lch(from: LAB): LCH;
|
||||
lch(...from: LAB): LCH;
|
||||
hex(from: LAB): HEX;
|
||||
hex(...from: LAB): HEX;
|
||||
keyword(from: LAB): Keyword;
|
||||
keyword(...from: LAB): Keyword;
|
||||
ansi16(from: LAB): ANSI16;
|
||||
ansi16(...from: LAB): ANSI16;
|
||||
ansi256(from: LAB): ANSI256;
|
||||
ansi256(...from: LAB): ANSI256;
|
||||
hcg(from: LAB): HCG;
|
||||
hcg(...from: LAB): HCG;
|
||||
apple(from: LAB): Apple;
|
||||
apple(...from: LAB): Apple;
|
||||
gray(from: LAB): Gray;
|
||||
gray(...from: LAB): Gray;
|
||||
};
|
||||
type lch = {
|
||||
rgb(from: LCH): RGB;
|
||||
rgb(...from: LCH): RGB;
|
||||
hsl(from: LCH): HSL;
|
||||
hsl(...from: LCH): HSL;
|
||||
hsv(from: LCH): HSV;
|
||||
hsv(...from: LCH): HSV;
|
||||
hwb(from: LCH): HWB;
|
||||
hwb(...from: LCH): HWB;
|
||||
cmyk(from: LCH): CMYK;
|
||||
cmyk(...from: LCH): CMYK;
|
||||
xyz(from: LCH): XYZ;
|
||||
xyz(...from: LCH): XYZ;
|
||||
lab(from: LCH): LAB;
|
||||
lab(...from: LCH): LAB;
|
||||
hex(from: LCH): HEX;
|
||||
hex(...from: LCH): HEX;
|
||||
keyword(from: LCH): Keyword;
|
||||
keyword(...from: LCH): Keyword;
|
||||
ansi16(from: LCH): ANSI16;
|
||||
ansi16(...from: LCH): ANSI16;
|
||||
ansi256(from: LCH): ANSI256;
|
||||
ansi256(...from: LCH): ANSI256;
|
||||
hcg(from: LCH): HCG;
|
||||
hcg(...from: LCH): HCG;
|
||||
apple(from: LCH): Apple;
|
||||
apple(...from: LCH): Apple;
|
||||
gray(from: LCH): Gray;
|
||||
gray(...from: LCH): Gray;
|
||||
};
|
||||
type hex = {
|
||||
rgb(from: HEX): RGB;
|
||||
hsl(from: HEX): HSL;
|
||||
hsv(from: HEX): HSV;
|
||||
hwb(from: HEX): HWB;
|
||||
cmyk(from: HEX): CMYK;
|
||||
xyz(from: HEX): XYZ;
|
||||
lab(from: HEX): LAB;
|
||||
lch(from: HEX): LCH;
|
||||
keyword(from: HEX): Keyword;
|
||||
ansi16(from: HEX): ANSI16;
|
||||
ansi256(from: HEX): ANSI256;
|
||||
hcg(from: HEX): HCG;
|
||||
apple(from: HEX): Apple;
|
||||
gray(from: HEX): Gray;
|
||||
};
|
||||
type keyword = {
|
||||
rgb(from: Keyword): RGB;
|
||||
hsl(from: Keyword): HSL;
|
||||
hsv(from: Keyword): HSV;
|
||||
hwb(from: Keyword): HWB;
|
||||
cmyk(from: Keyword): CMYK;
|
||||
xyz(from: Keyword): XYZ;
|
||||
lab(from: Keyword): LAB;
|
||||
lch(from: Keyword): LCH;
|
||||
hex(from: Keyword): HEX;
|
||||
ansi16(from: Keyword): ANSI16;
|
||||
ansi256(from: Keyword): ANSI256;
|
||||
hcg(from: Keyword): HCG;
|
||||
apple(from: Keyword): Apple;
|
||||
gray(from: Keyword): Gray;
|
||||
};
|
||||
type ansi16 = {
|
||||
rgb(from: ANSI16): RGB;
|
||||
hsl(from: ANSI16): HSL;
|
||||
hsv(from: ANSI16): HSV;
|
||||
hwb(from: ANSI16): HWB;
|
||||
cmyk(from: ANSI16): CMYK;
|
||||
xyz(from: ANSI16): XYZ;
|
||||
lab(from: ANSI16): LAB;
|
||||
lch(from: ANSI16): LCH;
|
||||
hex(from: ANSI16): HEX;
|
||||
keyword(from: ANSI16): Keyword;
|
||||
ansi256(from: ANSI16): ANSI256;
|
||||
hcg(from: ANSI16): HCG;
|
||||
apple(from: ANSI16): Apple;
|
||||
gray(from: ANSI16): Gray;
|
||||
};
|
||||
type ansi256 = {
|
||||
rgb(from: ANSI256): RGB;
|
||||
hsl(from: ANSI256): HSL;
|
||||
hsv(from: ANSI256): HSV;
|
||||
hwb(from: ANSI256): HWB;
|
||||
cmyk(from: ANSI256): CMYK;
|
||||
xyz(from: ANSI256): XYZ;
|
||||
lab(from: ANSI256): LAB;
|
||||
lch(from: ANSI256): LCH;
|
||||
hex(from: ANSI256): HEX;
|
||||
keyword(from: ANSI256): Keyword;
|
||||
ansi16(from: ANSI256): ANSI16;
|
||||
hcg(from: ANSI256): HCG;
|
||||
apple(from: ANSI256): Apple;
|
||||
gray(from: ANSI256): Gray;
|
||||
};
|
||||
type hcg = {
|
||||
rgb(from: HCG): RGB;
|
||||
rgb(...from: HCG): RGB;
|
||||
hsl(from: HCG): HSL;
|
||||
hsl(...from: HCG): HSL;
|
||||
hsv(from: HCG): HSV;
|
||||
hsv(...from: HCG): HSV;
|
||||
hwb(from: HCG): HWB;
|
||||
hwb(...from: HCG): HWB;
|
||||
cmyk(from: HCG): CMYK;
|
||||
cmyk(...from: HCG): CMYK;
|
||||
xyz(from: HCG): XYZ;
|
||||
xyz(...from: HCG): XYZ;
|
||||
lab(from: HCG): LAB;
|
||||
lab(...from: HCG): LAB;
|
||||
lch(from: HCG): LCH;
|
||||
lch(...from: HCG): LCH;
|
||||
hex(from: HCG): HEX;
|
||||
hex(...from: HCG): HEX;
|
||||
keyword(from: HCG): Keyword;
|
||||
keyword(...from: HCG): Keyword;
|
||||
ansi16(from: HCG): ANSI16;
|
||||
ansi16(...from: HCG): ANSI16;
|
||||
ansi256(from: HCG): ANSI256;
|
||||
ansi256(...from: HCG): ANSI256;
|
||||
apple(from: HCG): Apple;
|
||||
apple(...from: HCG): Apple;
|
||||
gray(from: HCG): Gray;
|
||||
gray(...from: HCG): Gray;
|
||||
};
|
||||
type apple = {
|
||||
rgb(from: Apple): RGB;
|
||||
rgb(...from: Apple): RGB;
|
||||
hsl(from: Apple): HSL;
|
||||
hsl(...from: Apple): HSL;
|
||||
hsv(from: Apple): HSV;
|
||||
hsv(...from: Apple): HSV;
|
||||
hwb(from: Apple): HWB;
|
||||
hwb(...from: Apple): HWB;
|
||||
cmyk(from: Apple): CMYK;
|
||||
cmyk(...from: Apple): CMYK;
|
||||
xyz(from: Apple): XYZ;
|
||||
xyz(...from: Apple): XYZ;
|
||||
lab(from: Apple): LAB;
|
||||
lab(...from: Apple): LAB;
|
||||
lch(from: Apple): LCH;
|
||||
lch(...from: Apple): LCH;
|
||||
hex(from: Apple): HEX;
|
||||
hex(...from: Apple): HEX;
|
||||
keyword(from: Apple): Keyword;
|
||||
keyword(...from: Apple): Keyword;
|
||||
ansi16(from: Apple): ANSI16;
|
||||
ansi16(...from: Apple): ANSI16;
|
||||
ansi256(from: Apple): ANSI256;
|
||||
ansi256(...from: Apple): ANSI256;
|
||||
hcg(from: Apple): HCG;
|
||||
hcg(...from: Apple): HCG;
|
||||
gray(from: Apple): Gray;
|
||||
gray(...from: Apple): Gray;
|
||||
};
|
||||
type gray = {
|
||||
rgb(from: Gray): RGB;
|
||||
rgb(...from: Gray): RGB;
|
||||
hsl(from: Gray): HSL;
|
||||
hsl(...from: Gray): HSL;
|
||||
hsv(from: Gray): HSV;
|
||||
hsv(...from: Gray): HSV;
|
||||
hwb(from: Gray): HWB;
|
||||
hwb(...from: Gray): HWB;
|
||||
cmyk(from: Gray): CMYK;
|
||||
cmyk(...from: Gray): CMYK;
|
||||
xyz(from: Gray): XYZ;
|
||||
xyz(...from: Gray): XYZ;
|
||||
lab(from: Gray): LAB;
|
||||
lab(...from: Gray): LAB;
|
||||
lch(from: Gray): LCH;
|
||||
lch(...from: Gray): LCH;
|
||||
hex(from: Gray): HEX;
|
||||
hex(...from: Gray): HEX;
|
||||
keyword(from: Gray): Keyword;
|
||||
keyword(...from: Gray): Keyword;
|
||||
ansi16(from: Gray): ANSI16;
|
||||
ansi16(...from: Gray): ANSI16;
|
||||
ansi256(from: Gray): ANSI256;
|
||||
ansi256(...from: Gray): ANSI256;
|
||||
hcg(from: Gray): HCG;
|
||||
hcg(...from: Gray): HCG;
|
||||
apple(from: Gray): Apple;
|
||||
apple(...from: Gray): Apple;
|
||||
};
|
||||
}
|
||||
declare function route(fromModel: "rgb"): route.rgb;
|
||||
declare function route(fromModel: "hsl"): route.hsl;
|
||||
declare function route(fromModel: "hsv"): route.hsv;
|
||||
declare function route(fromModel: "hwb"): route.hwb;
|
||||
declare function route(fromModel: "cmyk"): route.cmyk;
|
||||
declare function route(fromModel: "xyz"): route.xyz;
|
||||
declare function route(fromModel: "lab"): route.lab;
|
||||
declare function route(fromModel: "lch"): route.lch;
|
||||
declare function route(fromModel: "hex"): route.hex;
|
||||
declare function route(fromModel: "keyword"): route.keyword;
|
||||
declare function route(fromModel: "ansi16"): route.ansi16;
|
||||
declare function route(fromModel: "ansi256"): route.ansi256;
|
||||
declare function route(fromModel: "hcg"): route.hcg;
|
||||
declare function route(fromModel: "apple"): route.apple;
|
||||
declare function route(fromModel: "gray"): route.gray;
|
||||
type Convert = {
|
||||
rgb: {
|
||||
channels: Channels;
|
||||
labels: "rgb";
|
||||
hsl: {
|
||||
(...rgb: RGB): HSL;
|
||||
raw: (...rgb: RGB) => HSL;
|
||||
};
|
||||
hsv: {
|
||||
(...rgb: RGB): HSV;
|
||||
raw: (...rgb: RGB) => HSV;
|
||||
};
|
||||
hwb: {
|
||||
(...rgb: RGB): HWB;
|
||||
raw: (...rgb: RGB) => HWB;
|
||||
};
|
||||
hcg: {
|
||||
(...rgb: RGB): HCG;
|
||||
raw: (...rgb: RGB) => HCG;
|
||||
};
|
||||
cmyk: {
|
||||
(...rgb: RGB): CMYK;
|
||||
raw: (...rgb: RGB) => CMYK;
|
||||
};
|
||||
keyword: {
|
||||
(...rgb: RGB): Keyword;
|
||||
raw: (...rgb: RGB) => Keyword;
|
||||
};
|
||||
ansi16: {
|
||||
(...rgb: RGB): ANSI16;
|
||||
raw: (...rgb: RGB) => ANSI16;
|
||||
};
|
||||
ansi256: {
|
||||
(...rgb: RGB): ANSI256;
|
||||
raw: (...rgb: RGB) => ANSI256;
|
||||
};
|
||||
apple: {
|
||||
(...rgb: RGB): Apple;
|
||||
raw: (...rgb: RGB) => Apple;
|
||||
};
|
||||
hex: {
|
||||
(...rgb: RGB): HEX;
|
||||
raw: (...rgb: RGB) => HEX;
|
||||
};
|
||||
gray: {
|
||||
(...rgb: RGB): Gray;
|
||||
raw: (...rgb: RGB) => Gray;
|
||||
};
|
||||
} & route.rgb & {
|
||||
[F in keyof route.rgb]: {
|
||||
raw: route.rgb[F];
|
||||
};
|
||||
};
|
||||
keyword: {
|
||||
channels: Channels;
|
||||
rgb: {
|
||||
(keyword: Keyword): RGB;
|
||||
raw: (keyword: Keyword) => RGB;
|
||||
};
|
||||
} & route.keyword & {
|
||||
[F in keyof route.keyword]: {
|
||||
raw: route.keyword[F];
|
||||
};
|
||||
};
|
||||
hsl: {
|
||||
channels: Channels;
|
||||
labels: "hsl";
|
||||
rgb: {
|
||||
(...hsl: HSL): RGB;
|
||||
raw: (...hsl: HSL) => RGB;
|
||||
};
|
||||
hsv: {
|
||||
(...hsl: HSL): HSV;
|
||||
raw: (...hsl: HSL) => HSV;
|
||||
};
|
||||
hcg: {
|
||||
(...hsl: HSL): HCG;
|
||||
raw: (...hsl: HSL) => HCG;
|
||||
};
|
||||
} & route.hsl & {
|
||||
[F in keyof route.hsl]: {
|
||||
raw: route.hsl[F];
|
||||
};
|
||||
};
|
||||
hsv: {
|
||||
channels: Channels;
|
||||
labels: "hsv";
|
||||
hcg: {
|
||||
(...hsv: HSV): HCG;
|
||||
raw: (...hsv: HSV) => HCG;
|
||||
};
|
||||
rgb: {
|
||||
(...hsv: HSV): RGB;
|
||||
raw: (...hsv: HSV) => RGB;
|
||||
};
|
||||
hsv: {
|
||||
(...hsv: HSV): HSV;
|
||||
raw: (...hsv: HSV) => HSV;
|
||||
};
|
||||
hsl: {
|
||||
(...hsv: HSV): HSL;
|
||||
raw: (...hsv: HSV) => HSL;
|
||||
};
|
||||
hwb: {
|
||||
(...hsv: HSV): HWB;
|
||||
raw: (...hsv: HSV) => HWB;
|
||||
};
|
||||
ansi16: {
|
||||
(...hsv: HSV): ANSI16;
|
||||
raw: (...hsv: HSV) => ANSI16;
|
||||
};
|
||||
} & route.hsv & {
|
||||
[F in keyof route.hsv]: {
|
||||
raw: route.hsv[F];
|
||||
};
|
||||
};
|
||||
hwb: {
|
||||
channels: Channels;
|
||||
labels: "hwb";
|
||||
hcg: {
|
||||
(...hwb: HWB): HCG;
|
||||
raw: (...hwb: HWB) => HCG;
|
||||
};
|
||||
rgb: {
|
||||
(...hwb: HWB): RGB;
|
||||
raw: (...hwb: HWB) => RGB;
|
||||
};
|
||||
} & route.hwb & {
|
||||
[F in keyof route.hwb]: {
|
||||
raw: route.hwb[F];
|
||||
};
|
||||
};
|
||||
cmyk: {
|
||||
channels: Channels;
|
||||
labels: "cmyk";
|
||||
rgb: {
|
||||
(...cmyk: CMYK): RGB;
|
||||
raw: (...cmyk: CMYK) => RGB;
|
||||
};
|
||||
} & route.cmyk & {
|
||||
[F in keyof route.cmyk]: {
|
||||
raw: route.cmyk[F];
|
||||
};
|
||||
};
|
||||
xyz: {
|
||||
channels: Channels;
|
||||
labels: "xyz";
|
||||
rgb: {
|
||||
(...xyz: XYZ): RGB;
|
||||
raw: (...xyz: XYZ) => RGB;
|
||||
};
|
||||
lab: {
|
||||
(...xyz: XYZ): LAB;
|
||||
raw: (...xyz: XYZ) => LAB;
|
||||
};
|
||||
} & route.xyz & {
|
||||
[F in keyof route.xyz]: {
|
||||
raw: route.xyz[F];
|
||||
};
|
||||
};
|
||||
lab: {
|
||||
channels: Channels;
|
||||
labels: "lab";
|
||||
xyz: {
|
||||
(...lab: LAB): XYZ;
|
||||
raw: (...lab: LAB) => XYZ;
|
||||
};
|
||||
lch: {
|
||||
(...lab: LAB): LCH;
|
||||
raw: (...lab: LAB) => LCH;
|
||||
};
|
||||
} & route.lab & {
|
||||
[F in keyof route.lab]: {
|
||||
raw: route.lab[F];
|
||||
};
|
||||
};
|
||||
lch: {
|
||||
channels: Channels;
|
||||
labels: "lch";
|
||||
lab: {
|
||||
(...lch: LCH): LAB;
|
||||
raw: (...lch: LCH) => LAB;
|
||||
};
|
||||
} & route.lch & {
|
||||
[F in keyof route.lch]: {
|
||||
raw: route.lch[F];
|
||||
};
|
||||
};
|
||||
hex: {
|
||||
channels: Channels;
|
||||
labels: [
|
||||
"hex"
|
||||
];
|
||||
rgb: {
|
||||
(hex: HEX): RGB;
|
||||
raw: (hex: HEX) => RGB;
|
||||
};
|
||||
} & route.hex & {
|
||||
[F in keyof route.hex]: {
|
||||
raw: route.hex[F];
|
||||
};
|
||||
};
|
||||
ansi16: {
|
||||
channels: Channels;
|
||||
labels: [
|
||||
"ansi16"
|
||||
];
|
||||
rgb: {
|
||||
(ansi16: ANSI16): RGB;
|
||||
raw: (ansi16: ANSI16) => RGB;
|
||||
};
|
||||
} & route.ansi16 & {
|
||||
[F in keyof route.ansi16]: {
|
||||
raw: route.ansi16[F];
|
||||
};
|
||||
};
|
||||
ansi256: {
|
||||
channels: Channels;
|
||||
labels: [
|
||||
"ansi256"
|
||||
];
|
||||
rgb: {
|
||||
(ansi256: ANSI256): RGB;
|
||||
raw: (ansi256: ANSI256) => RGB;
|
||||
};
|
||||
} & route.ansi256 & {
|
||||
[F in keyof route.ansi256]: {
|
||||
raw: route.ansi256[F];
|
||||
};
|
||||
};
|
||||
hcg: {
|
||||
channels: Channels;
|
||||
labels: [
|
||||
"h",
|
||||
"c",
|
||||
"g"
|
||||
];
|
||||
rgb: {
|
||||
(...hcg: HCG): RGB;
|
||||
raw: (...hcg: HCG) => RGB;
|
||||
};
|
||||
hsv: {
|
||||
(...hcg: HCG): HSV;
|
||||
raw: (...hcg: HCG) => HSV;
|
||||
};
|
||||
hwb: {
|
||||
(...hcg: HCG): HWB;
|
||||
raw: (...hcg: HCG) => HWB;
|
||||
};
|
||||
} & route.hcg & {
|
||||
[F in keyof route.hcg]: {
|
||||
raw: route.hcg[F];
|
||||
};
|
||||
};
|
||||
apple: {
|
||||
channels: Channels;
|
||||
labels: [
|
||||
"r16",
|
||||
"g16",
|
||||
"b16"
|
||||
];
|
||||
rgb: {
|
||||
(...apple: Apple): RGB;
|
||||
raw: (...apple: Apple) => RGB;
|
||||
};
|
||||
} & route.apple & {
|
||||
[F in keyof route.apple]: {
|
||||
raw: route.apple[F];
|
||||
};
|
||||
};
|
||||
gray: {
|
||||
channels: Channels;
|
||||
labels: [
|
||||
"gray"
|
||||
];
|
||||
rgb: {
|
||||
(...gray: Gray): RGB;
|
||||
raw: (...gray: Gray) => RGB;
|
||||
};
|
||||
hsl: {
|
||||
(...gray: Gray): HSL;
|
||||
raw: (...gray: Gray) => HSL;
|
||||
};
|
||||
hsv: {
|
||||
(...gray: Gray): HSV;
|
||||
raw: (...gray: Gray) => HSV;
|
||||
};
|
||||
hwb: {
|
||||
(...gray: Gray): HWB;
|
||||
raw: (...gray: Gray) => HWB;
|
||||
};
|
||||
cmyk: {
|
||||
(...gray: Gray): CMYK;
|
||||
raw: (...gray: Gray) => CMYK;
|
||||
};
|
||||
lab: {
|
||||
(...gray: Gray): LAB;
|
||||
raw: (...gray: Gray) => LAB;
|
||||
};
|
||||
hex: {
|
||||
(...gray: Gray): HEX;
|
||||
raw: (...gray: Gray) => HEX;
|
||||
};
|
||||
} & route.gray & {
|
||||
[F in keyof route.gray]: {
|
||||
raw: route.gray[F];
|
||||
};
|
||||
};
|
||||
};
|
||||
declare const convert: Convert;
|
||||
export type ColorLike = ColorInstance | string | ArrayLike<number> | number | Record<string, any>;
|
||||
export type ColorJson = {
|
||||
model: string;
|
||||
color: number[];
|
||||
valpha: number;
|
||||
};
|
||||
export type ColorObject = {
|
||||
alpha?: number | undefined;
|
||||
} & Record<string, number>;
|
||||
// eslint-disable-next-line @typescript-eslint/consistent-type-definitions
|
||||
export interface ColorInstance {
|
||||
toString(): string;
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||
toJSON(): ColorJson;
|
||||
string(places?: number): string;
|
||||
percentString(places?: number): string;
|
||||
array(): number[];
|
||||
object(): ColorObject;
|
||||
unitArray(): number[];
|
||||
unitObject(): {
|
||||
r: number;
|
||||
g: number;
|
||||
b: number;
|
||||
alpha?: number | undefined;
|
||||
};
|
||||
round(places?: number): ColorInstance;
|
||||
alpha(): number;
|
||||
alpha(value: number): ColorInstance;
|
||||
red(): number;
|
||||
red(value: number): ColorInstance;
|
||||
green(): number;
|
||||
green(value: number): ColorInstance;
|
||||
blue(): number;
|
||||
blue(value: number): ColorInstance;
|
||||
hue(): number;
|
||||
hue(value: number): ColorInstance;
|
||||
saturationl(): number;
|
||||
saturationl(value: number): ColorInstance;
|
||||
lightness(): number;
|
||||
lightness(value: number): ColorInstance;
|
||||
saturationv(): number;
|
||||
saturationv(value: number): ColorInstance;
|
||||
value(): number;
|
||||
value(value: number): ColorInstance;
|
||||
chroma(): number;
|
||||
chroma(value: number): ColorInstance;
|
||||
gray(): number;
|
||||
gray(value: number): ColorInstance;
|
||||
white(): number;
|
||||
white(value: number): ColorInstance;
|
||||
wblack(): number;
|
||||
wblack(value: number): ColorInstance;
|
||||
cyan(): number;
|
||||
cyan(value: number): ColorInstance;
|
||||
magenta(): number;
|
||||
magenta(value: number): ColorInstance;
|
||||
yellow(): number;
|
||||
yellow(value: number): ColorInstance;
|
||||
black(): number;
|
||||
black(value: number): ColorInstance;
|
||||
x(): number;
|
||||
x(value: number): ColorInstance;
|
||||
y(): number;
|
||||
y(value: number): ColorInstance;
|
||||
z(): number;
|
||||
z(value: number): ColorInstance;
|
||||
l(): number;
|
||||
l(value: number): ColorInstance;
|
||||
a(): number;
|
||||
a(value: number): ColorInstance;
|
||||
b(): number;
|
||||
b(value: number): ColorInstance;
|
||||
keyword(): string;
|
||||
keyword<V extends string>(value: V): ColorInstance;
|
||||
hex(): string;
|
||||
hex<V extends string>(value: V): ColorInstance;
|
||||
hexa(): string;
|
||||
hexa<V extends string>(value: V): ColorInstance;
|
||||
rgbNumber(): number;
|
||||
luminosity(): number;
|
||||
contrast(color2: ColorInstance): number;
|
||||
level(color2: ColorInstance): "AAA" | "AA" | "";
|
||||
isDark(): boolean;
|
||||
isLight(): boolean;
|
||||
negate(): ColorInstance;
|
||||
lighten(ratio: number): ColorInstance;
|
||||
darken(ratio: number): ColorInstance;
|
||||
saturate(ratio: number): ColorInstance;
|
||||
desaturate(ratio: number): ColorInstance;
|
||||
whiten(ratio: number): ColorInstance;
|
||||
blacken(ratio: number): ColorInstance;
|
||||
grayscale(): ColorInstance;
|
||||
fade(ratio: number): ColorInstance;
|
||||
opaquer(ratio: number): ColorInstance;
|
||||
rotate(degrees: number): ColorInstance;
|
||||
mix(mixinColor: ColorInstance, weight?: number): ColorInstance;
|
||||
rgb(...arguments_: number[]): ColorInstance;
|
||||
hsl(...arguments_: number[]): ColorInstance;
|
||||
hsv(...arguments_: number[]): ColorInstance;
|
||||
hwb(...arguments_: number[]): ColorInstance;
|
||||
cmyk(...arguments_: number[]): ColorInstance;
|
||||
xyz(...arguments_: number[]): ColorInstance;
|
||||
lab(...arguments_: number[]): ColorInstance;
|
||||
lch(...arguments_: number[]): ColorInstance;
|
||||
ansi16(...arguments_: number[]): ColorInstance;
|
||||
ansi256(...arguments_: number[]): ColorInstance;
|
||||
hcg(...arguments_: number[]): ColorInstance;
|
||||
apple(...arguments_: number[]): ColorInstance;
|
||||
}
|
||||
export type ColorConstructor = {
|
||||
(object?: ColorLike, model?: keyof (typeof convert)): ColorInstance;
|
||||
new (object?: ColorLike, model?: keyof (typeof convert)): ColorInstance;
|
||||
rgb(...value: number[]): ColorInstance;
|
||||
rgb(color: ColorLike): ColorInstance;
|
||||
hsl(...value: number[]): ColorInstance;
|
||||
hsl(color: ColorLike): ColorInstance;
|
||||
hsv(...value: number[]): ColorInstance;
|
||||
hsv(color: ColorLike): ColorInstance;
|
||||
hwb(...value: number[]): ColorInstance;
|
||||
hwb(color: ColorLike): ColorInstance;
|
||||
cmyk(...value: number[]): ColorInstance;
|
||||
cmyk(color: ColorLike): ColorInstance;
|
||||
xyz(...value: number[]): ColorInstance;
|
||||
xyz(color: ColorLike): ColorInstance;
|
||||
lab(...value: number[]): ColorInstance;
|
||||
lab(color: ColorLike): ColorInstance;
|
||||
lch(...value: number[]): ColorInstance;
|
||||
lch(color: ColorLike): ColorInstance;
|
||||
ansi16(...value: number[]): ColorInstance;
|
||||
ansi16(color: ColorLike): ColorInstance;
|
||||
ansi256(...value: number[]): ColorInstance;
|
||||
ansi256(color: ColorLike): ColorInstance;
|
||||
hcg(...value: number[]): ColorInstance;
|
||||
hcg(color: ColorLike): ColorInstance;
|
||||
apple(...value: number[]): ColorInstance;
|
||||
apple(color: ColorLike): ColorInstance;
|
||||
};
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||
declare const Color: ColorConstructor;
|
||||
|
||||
export {
|
||||
Color as default,
|
||||
};
|
||||
|
||||
export {};
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
{
|
||||
"name": "@img/colour",
|
||||
"version": "1.1.0",
|
||||
"description": "The ESM-only 'color' package made compatible for use with CommonJS runtimes",
|
||||
"license": "MIT",
|
||||
"main": "index.cjs",
|
||||
"types": "index.d.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./index.d.ts",
|
||||
"require": "./index.cjs",
|
||||
"default": "./index.cjs"
|
||||
},
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"authors": [
|
||||
"Heather Arthur <fayearthur@gmail.com>",
|
||||
"Josh Junon <josh@junon.me>",
|
||||
"Maxime Thirouin",
|
||||
"Dyma Ywanov <dfcreative@gmail.com>",
|
||||
"LitoMore (https://github.com/LitoMore)"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"files": [
|
||||
"color.cjs",
|
||||
"index.d.ts"
|
||||
],
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/lovell/colour.git"
|
||||
},
|
||||
"type": "commonjs",
|
||||
"keywords": [
|
||||
"color",
|
||||
"colour",
|
||||
"cjs",
|
||||
"commonjs"
|
||||
],
|
||||
"scripts": {
|
||||
"build:cjs": "esbuild node_modules/color/index.js --bundle --platform=node --outfile=color.cjs",
|
||||
"build:dts": "dts-bundle-generator ./dts-src.ts -o index.d.ts --project tsconfig.build.json --external-inlines color --external-inlines color-convert --export-referenced-types=false",
|
||||
"build": "npm run build:cjs && npm run build:dts",
|
||||
"test": "node --test"
|
||||
},
|
||||
"devDependencies": {
|
||||
"color": "5.0.3",
|
||||
"color-convert": "3.1.3",
|
||||
"color-name": "2.1.0",
|
||||
"color-string": "2.1.4",
|
||||
"dts-bundle-generator": "^9.5.1",
|
||||
"esbuild": "^0.27.3"
|
||||
}
|
||||
}
|
||||
Generated
Vendored
+191
@@ -0,0 +1,191 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction, and
|
||||
distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by the copyright
|
||||
owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all other entities
|
||||
that control, are controlled by, or are under common control with that entity.
|
||||
For the purposes of this definition, "control" means (i) the power, direct or
|
||||
indirect, to cause the direction or management of such entity, whether by
|
||||
contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity exercising
|
||||
permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications, including
|
||||
but not limited to software source code, documentation source, and configuration
|
||||
files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical transformation or
|
||||
translation of a Source form, including but not limited to compiled object code,
|
||||
generated documentation, and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or Object form, made
|
||||
available under the License, as indicated by a copyright notice that is included
|
||||
in or attached to the work (an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object form, that
|
||||
is based on (or derived from) the Work and for which the editorial revisions,
|
||||
annotations, elaborations, or other modifications represent, as a whole, an
|
||||
original work of authorship. For the purposes of this License, Derivative Works
|
||||
shall not include works that remain separable from, or merely link (or bind by
|
||||
name) to the interfaces of, the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including the original version
|
||||
of the Work and any modifications or additions to that Work or Derivative Works
|
||||
thereof, that is intentionally submitted to Licensor for inclusion in the Work
|
||||
by the copyright owner or by an individual or Legal Entity authorized to submit
|
||||
on behalf of the copyright owner. For the purposes of this definition,
|
||||
"submitted" means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems, and
|
||||
issue tracking systems that are managed by, or on behalf of, the Licensor for
|
||||
the purpose of discussing and improving the Work, but excluding communication
|
||||
that is conspicuously marked or otherwise designated in writing by the copyright
|
||||
owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf
|
||||
of whom a Contribution has been received by Licensor and subsequently
|
||||
incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License.
|
||||
|
||||
Subject to the terms and conditions of this License, each Contributor hereby
|
||||
grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
|
||||
irrevocable copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the Work and such
|
||||
Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License.
|
||||
|
||||
Subject to the terms and conditions of this License, each Contributor hereby
|
||||
grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
|
||||
irrevocable (except as stated in this section) patent license to make, have
|
||||
made, use, offer to sell, sell, import, and otherwise transfer the Work, where
|
||||
such license applies only to those patent claims licensable by such Contributor
|
||||
that are necessarily infringed by their Contribution(s) alone or by combination
|
||||
of their Contribution(s) with the Work to which such Contribution(s) was
|
||||
submitted. If You institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work or a
|
||||
Contribution incorporated within the Work constitutes direct or contributory
|
||||
patent infringement, then any patent licenses granted to You under this License
|
||||
for that Work shall terminate as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution.
|
||||
|
||||
You may reproduce and distribute copies of the Work or Derivative Works thereof
|
||||
in any medium, with or without modifications, and in Source or Object form,
|
||||
provided that You meet the following conditions:
|
||||
|
||||
You must give any other recipients of the Work or Derivative Works a copy of
|
||||
this License; and
|
||||
You must cause any modified files to carry prominent notices stating that You
|
||||
changed the files; and
|
||||
You must retain, in the Source form of any Derivative Works that You distribute,
|
||||
all copyright, patent, trademark, and attribution notices from the Source form
|
||||
of the Work, excluding those notices that do not pertain to any part of the
|
||||
Derivative Works; and
|
||||
If the Work includes a "NOTICE" text file as part of its distribution, then any
|
||||
Derivative Works that You distribute must include a readable copy of the
|
||||
attribution notices contained within such NOTICE file, excluding those notices
|
||||
that do not pertain to any part of the Derivative Works, in at least one of the
|
||||
following places: within a NOTICE text file distributed as part of the
|
||||
Derivative Works; within the Source form or documentation, if provided along
|
||||
with the Derivative Works; or, within a display generated by the Derivative
|
||||
Works, if and wherever such third-party notices normally appear. The contents of
|
||||
the NOTICE file are for informational purposes only and do not modify the
|
||||
License. You may add Your own attribution notices within Derivative Works that
|
||||
You distribute, alongside or as an addendum to the NOTICE text from the Work,
|
||||
provided that such additional attribution notices cannot be construed as
|
||||
modifying the License.
|
||||
You may add Your own copyright statement to Your modifications and may provide
|
||||
additional or different license terms and conditions for use, reproduction, or
|
||||
distribution of Your modifications, or for any such Derivative Works as a whole,
|
||||
provided Your use, reproduction, and distribution of the Work otherwise complies
|
||||
with the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions.
|
||||
|
||||
Unless You explicitly state otherwise, any Contribution intentionally submitted
|
||||
for inclusion in the Work by You to the Licensor shall be under the terms and
|
||||
conditions of this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify the terms of
|
||||
any separate license agreement you may have executed with Licensor regarding
|
||||
such Contributions.
|
||||
|
||||
6. Trademarks.
|
||||
|
||||
This License does not grant permission to use the trade names, trademarks,
|
||||
service marks, or product names of the Licensor, except as required for
|
||||
reasonable and customary use in describing the origin of the Work and
|
||||
reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty.
|
||||
|
||||
Unless required by applicable law or agreed to in writing, Licensor provides the
|
||||
Work (and each Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied,
|
||||
including, without limitation, any warranties or conditions of TITLE,
|
||||
NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are
|
||||
solely responsible for determining the appropriateness of using or
|
||||
redistributing the Work and assume any risks associated with Your exercise of
|
||||
permissions under this License.
|
||||
|
||||
8. Limitation of Liability.
|
||||
|
||||
In no event and under no legal theory, whether in tort (including negligence),
|
||||
contract, or otherwise, unless required by applicable law (such as deliberate
|
||||
and grossly negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special, incidental,
|
||||
or consequential damages of any character arising as a result of this License or
|
||||
out of the use or inability to use the Work (including but not limited to
|
||||
damages for loss of goodwill, work stoppage, computer failure or malfunction, or
|
||||
any and all other commercial damages or losses), even if such Contributor has
|
||||
been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability.
|
||||
|
||||
While redistributing the Work or Derivative Works thereof, You may choose to
|
||||
offer, and charge a fee for, acceptance of support, warranty, indemnity, or
|
||||
other liability obligations and/or rights consistent with this License. However,
|
||||
in accepting such obligations, You may act only on Your own behalf and on Your
|
||||
sole responsibility, not on behalf of any other Contributor, and only if You
|
||||
agree to indemnify, defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason of your
|
||||
accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work
|
||||
|
||||
To apply the Apache License to your work, attach the following boilerplate
|
||||
notice, with the fields enclosed by brackets "[]" replaced with your own
|
||||
identifying information. (Don't include the brackets!) The text should be
|
||||
enclosed in the appropriate comment syntax for the file format. We also
|
||||
recommend that a file or class name and description of purpose be included on
|
||||
the same "printed page" as the copyright notice for easier identification within
|
||||
third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
Generated
Vendored
+59
@@ -0,0 +1,59 @@
|
||||
# `@img/sharp-win32-arm64`
|
||||
|
||||
Prebuilt sharp for use with Windows 64-bit ARM.
|
||||
|
||||
## Licensing
|
||||
|
||||
Copyright 2013 Lovell Fuller and others.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
[https://www.apache.org/licenses/LICENSE-2.0](https://www.apache.org/licenses/LICENSE-2.0)
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
|
||||
This software contains third-party libraries
|
||||
used under the terms of the following licenses:
|
||||
|
||||
| Library | Used under the terms of |
|
||||
|---------------|-----------------------------------------------------------------------------------------------------------|
|
||||
| aom | BSD 2-Clause + [Alliance for Open Media Patent License 1.0](https://aomedia.org/license/patent-license/) |
|
||||
| cairo | Mozilla Public License 1.1 |
|
||||
| cgif | MIT License |
|
||||
| expat | MIT License |
|
||||
| fontconfig | [fontconfig License](https://gitlab.freedesktop.org/fontconfig/fontconfig/blob/main/COPYING) (BSD-like) |
|
||||
| freetype | [freetype License](https://git.savannah.gnu.org/cgit/freetype/freetype2.git/tree/docs/FTL.TXT) (BSD-like) |
|
||||
| fribidi | LGPLv3 |
|
||||
| glib | LGPLv3 |
|
||||
| harfbuzz | MIT License |
|
||||
| highway | BSD 3-Clause |
|
||||
| lcms | MIT License |
|
||||
| libarchive | BSD 2-Clause |
|
||||
| libexif | LGPLv3 |
|
||||
| libffi | MIT License |
|
||||
| libheif | LGPLv3 |
|
||||
| libimagequant | [BSD 2-Clause](https://github.com/lovell/libimagequant/blob/main/COPYRIGHT) |
|
||||
| libnsgif | MIT License |
|
||||
| libpng | [libpng License](https://github.com/pnggroup/libpng/blob/master/LICENSE) |
|
||||
| librsvg | LGPLv3 |
|
||||
| libtiff | [libtiff License](https://gitlab.com/libtiff/libtiff/blob/master/LICENSE.md) (BSD-like) |
|
||||
| libultrahdr | MIT License |
|
||||
| libvips | LGPLv3 |
|
||||
| libwebp | New BSD License |
|
||||
| libxml2 | MIT License |
|
||||
| mozjpeg | [zlib License, IJG License, BSD 3-Clause](https://github.com/mozilla/mozjpeg/blob/master/LICENSE.md) |
|
||||
| pango | LGPLv3 |
|
||||
| pixman | MIT License |
|
||||
| proxy-libintl | LGPLv3 |
|
||||
| zlib-ng | [zlib License](https://github.com/zlib-ng/zlib-ng/blob/develop/LICENSE.md) |
|
||||
|
||||
Use of libraries under the terms of the LGPLv3 is via the
|
||||
"any later version" clause of the LGPLv2 or LGPLv2.1.
|
||||
|
||||
Please report any errors or omissions via
|
||||
https://github.com/lovell/sharp-libvips/issues/new
|
||||
Generated
Vendored
+1
@@ -0,0 +1 @@
|
||||
module.exports = require('./lib/sharp-win32-arm64-0.35.5.node');
|
||||
Generated
Vendored
BIN
Binary file not shown.
Generated
Vendored
BIN
Binary file not shown.
Generated
Vendored
BIN
Binary file not shown.
Generated
Vendored
+40
@@ -0,0 +1,40 @@
|
||||
{
|
||||
"name": "@img/sharp-win32-arm64",
|
||||
"version": "0.35.5",
|
||||
"description": "Prebuilt sharp for use with Windows 64-bit ARM",
|
||||
"author": "Lovell Fuller <npm@lovell.info>",
|
||||
"homepage": "https://sharp.pixelplumbing.com",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/lovell/sharp.git",
|
||||
"directory": "npm/win32-arm64"
|
||||
},
|
||||
"license": "Apache-2.0 AND LGPL-3.0-or-later",
|
||||
"funding": {
|
||||
"url": "https://opencollective.com/libvips"
|
||||
},
|
||||
"preferUnplugged": true,
|
||||
"files": [
|
||||
"index.cjs",
|
||||
"lib",
|
||||
"versions.json"
|
||||
],
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"type": "commonjs",
|
||||
"exports": {
|
||||
"./sharp.node": "./index.cjs",
|
||||
"./package": "./package.json",
|
||||
"./versions": "./versions.json"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20.9.0"
|
||||
},
|
||||
"os": [
|
||||
"win32"
|
||||
],
|
||||
"cpu": [
|
||||
"arm64"
|
||||
]
|
||||
}
|
||||
Generated
Vendored
+30
@@ -0,0 +1,30 @@
|
||||
{
|
||||
"aom": "3.15.1",
|
||||
"archive": "3.8.9",
|
||||
"cairo": "1.18.6",
|
||||
"cgif": "0.5.4",
|
||||
"exif": "0.6.26",
|
||||
"expat": "2.8.5",
|
||||
"ffi": "3.8.0",
|
||||
"fontconfig": "2.18.3",
|
||||
"freetype": "2.14.3",
|
||||
"fribidi": "1.0.17",
|
||||
"glib": "2.90.0",
|
||||
"harfbuzz": "14.5.0",
|
||||
"heif": "1.23.5",
|
||||
"highway": "1.4.0",
|
||||
"imagequant": "2.4.1",
|
||||
"lcms": "2.19.1",
|
||||
"mozjpeg": "0826579",
|
||||
"pango": "1.58.2",
|
||||
"pixman": "0.46.4",
|
||||
"png": "1.6.58",
|
||||
"proxy-libintl": "0.5",
|
||||
"rsvg": "2.63.2",
|
||||
"tiff": "4.7.2",
|
||||
"uhdr": "2.0.2",
|
||||
"vips": "8.18.7",
|
||||
"webp": "1.6.0",
|
||||
"xml2": "2.15.4",
|
||||
"zlib-ng": "2.3.3"
|
||||
}
|
||||
Generated
Vendored
+45
@@ -0,0 +1,45 @@
|
||||
{
|
||||
"name": "@napi-rs/canvas-win32-arm64-msvc",
|
||||
"version": "0.1.100",
|
||||
"os": [
|
||||
"win32"
|
||||
],
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"main": "skia.win32-arm64-msvc.node",
|
||||
"files": [
|
||||
"skia.win32-arm64-msvc.node",
|
||||
"icudtl.dat"
|
||||
],
|
||||
"description": "Canvas for Node.js with skia backend",
|
||||
"keywords": [
|
||||
"napi-rs",
|
||||
"NAPI",
|
||||
"N-API",
|
||||
"Rust",
|
||||
"node-addon",
|
||||
"node-addon-api",
|
||||
"canvas",
|
||||
"image",
|
||||
"pdf",
|
||||
"svg",
|
||||
"skia"
|
||||
],
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 10"
|
||||
},
|
||||
"publishConfig": {
|
||||
"registry": "https://registry.npmjs.org/",
|
||||
"access": "public"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/Brooooooklyn/canvas.git"
|
||||
},
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/Brooooooklyn"
|
||||
}
|
||||
}
|
||||
Generated
Vendored
BIN
Binary file not shown.
+21
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2020 lynweklm@gmail.com
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
+448
@@ -0,0 +1,448 @@
|
||||
# `skr canvas`
|
||||
|
||||
[](https://github.com/Brooooooklyn/canvas/actions/workflows/CI.yaml)
|
||||

|
||||
[](https://packagephobia.com/result?p=@napi-rs/canvas)
|
||||
[](https://npmcharts.com/compare/@napi-rs/canvas?minimal=true)
|
||||
|
||||
> 🚀 Help me to become a full-time open-source developer by [sponsoring me on Github](https://github.com/sponsors/Brooooooklyn)
|
||||
|
||||
Google Skia binding to Node.js via [Node-API](https://napi.rs), **0 System dependencies!**
|
||||
|
||||
⚠️ This project is in pre-release stage. And there may be some bugs.<br/>
|
||||
For details on planned features and future direction please refer to the [Roadmap](https://github.com/Brooooooklyn/canvas/issues/113).
|
||||
|
||||
[中文文档](./README-zh.md)
|
||||
|
||||
# Install
|
||||
|
||||
```bash
|
||||
yarn add @napi-rs/canvas
|
||||
npm install @napi-rs/canvas
|
||||
```
|
||||
|
||||
# Support matrix
|
||||
|
||||
## System requirement
|
||||
|
||||
### `arm64`
|
||||
|
||||
[**_cortex-a57_**](https://en.wikipedia.org/wiki/ARM_Cortex-A57) or newer CPU architecture on **Linux**.
|
||||
|
||||
All Apple M chips on **macOS**.
|
||||
|
||||
### `armv7`
|
||||
|
||||
[**_cortex-a7_**](https://en.wikipedia.org/wiki/ARM_Cortex-A7) or newer CPU architecture.
|
||||
|
||||
### glibc
|
||||
|
||||
Since Skia relies on the [glibc](https://www.gnu.org/software/libc/) 2.18 API, you need to have at least glibc version >= 2.18 on your system.
|
||||
|
||||
## AWS Lambda usage
|
||||
|
||||
To use this library on Lambda you will need to use a Lambda layer.
|
||||
|
||||
You can simply attach a lambda layer by getting an ARN from [Canvas-Lambda-Layer](https://github.com/ShivamJoker/Canvas-Lambda-Layer)
|
||||
|
||||
> Make sure to exclude `@napi-rs/canvas` while bundling your Lambda.
|
||||
|
||||
# Usage
|
||||
|
||||
```js
|
||||
const { promises } = require('node:fs')
|
||||
const { join } = require('node:path')
|
||||
const { createCanvas, loadImage } = require('@napi-rs/canvas')
|
||||
|
||||
const canvas = createCanvas(300, 320)
|
||||
const ctx = canvas.getContext('2d')
|
||||
|
||||
ctx.lineWidth = 10
|
||||
ctx.strokeStyle = '#03a9f4'
|
||||
ctx.fillStyle = '#03a9f4'
|
||||
|
||||
// Wall
|
||||
ctx.strokeRect(75, 140, 150, 110)
|
||||
|
||||
// Door
|
||||
ctx.fillRect(130, 190, 40, 60)
|
||||
|
||||
// Roof
|
||||
ctx.beginPath()
|
||||
ctx.moveTo(50, 140)
|
||||
ctx.lineTo(150, 60)
|
||||
ctx.lineTo(250, 140)
|
||||
ctx.closePath()
|
||||
ctx.stroke()
|
||||
|
||||
async function main() {
|
||||
// load images from disk or from a URL
|
||||
const catImage = await loadImage('path/to/cat.png')
|
||||
const dogImage = await loadImage('https://example.com/path/to/dog.jpg')
|
||||
|
||||
ctx.drawImage(catImage, 0, 0, catImage.width, catImage.height)
|
||||
|
||||
ctx.drawImage(dogImage, canvas.width / 2, canvas.height / 2, dogImage.width, dogImage.height)
|
||||
|
||||
// export canvas as image
|
||||
const pngData = await canvas.encode('png') // JPEG, AVIF and WebP are also supported
|
||||
// encoding in libuv thread pool, non-blocking
|
||||
await promises.writeFile(join(__dirname, 'simple.png'), pngData)
|
||||
}
|
||||
|
||||
main()
|
||||
```
|
||||
|
||||

|
||||
|
||||
## Emoji text
|
||||
|
||||
```js
|
||||
const { writeFileSync } = require('fs')
|
||||
const { join } = require('path')
|
||||
|
||||
const { createCanvas, GlobalFonts } = require('@napi-rs/canvas')
|
||||
|
||||
GlobalFonts.registerFromPath(join(__dirname, '..', 'fonts', 'AppleColorEmoji@2x.ttf'), 'Apple Emoji')
|
||||
GlobalFonts.registerFromPath(join(__dirname, '..', '__test__', 'fonts', 'COLRv1.ttf'), 'COLRv1')
|
||||
|
||||
console.info(GlobalFonts.families)
|
||||
|
||||
const canvas = createCanvas(760, 360)
|
||||
const ctx = canvas.getContext('2d')
|
||||
|
||||
ctx.font = '50px Apple Emoji'
|
||||
ctx.strokeText('😀😃😄😁😆😅😂🤣☺️😊😊😇', 50, 150)
|
||||
|
||||
ctx.font = '100px COLRv1'
|
||||
ctx.fillText('abc', 50, 300)
|
||||
|
||||
const b = canvas.toBuffer('image/png')
|
||||
|
||||
writeFileSync(join(__dirname, 'draw-emoji.png'), b)
|
||||
```
|
||||
|
||||

|
||||
|
||||
# Performance
|
||||
|
||||
See [benchmark](./benchmark) for benchmark code.
|
||||
|
||||
Hardware info:
|
||||
|
||||
```
|
||||
,MMMM. Host - xxxxxxxxxxxxxxxxxxxxxxx
|
||||
.MMMMMM Machine - Mac15,9
|
||||
MMMMM, Kernel - 24.0.0
|
||||
.;MMMMM:' MMMMMMMMMM;. OS - macOS 15.0.1 Sequoia
|
||||
MMMMMMMMMMMMNWMMMMMMMMMMM: DE - Aqua
|
||||
.MMMMMMMMMMMMMMMMMMMMMMMMWM. WM - Quartz Compositor
|
||||
MMMMMMMMMMMMMMMMMMMMMMMMM. Packages - 194 (Homebrew), 32 (cargo)
|
||||
;MMMMMMMMMMMMMMMMMMMMMMMM: Shell - zsh
|
||||
:MMMMMMMMMMMMMMMMMMMMMMMM: Terminal - warpterminal (Version v0.2024.10.23.14.49.stable_00)
|
||||
.MMMMMMMMMMMMMMMMMMMMMMMMM. Resolution - 5120x2880@160fps (as 2560x1440)
|
||||
MMMMMMMMMMMMMMMMMMMMMMMMMMM. 2992x1934@120fps (as 1496x967)
|
||||
.MMMMMMMMMMMMMMMMMMMMMMMMMM. 2232x1512@60fps (as 1116x756)
|
||||
MMMMMMMMMMMMMMMMMMMMMMMM Uptime - 1d 2h 32m
|
||||
;MMMMMMMMMMMMMMMMMMMM. CPU - Apple M3 Max (16)
|
||||
.MMMM,. .MMMM,. CPU Load - 16%
|
||||
Memory - 50.1 GB / 134.2 GB
|
||||
Battery - 78% & Discharging
|
||||
Disk Space - 624.0 GB / 994.7 GB
|
||||
```
|
||||
|
||||
```
|
||||
❯ yarn bench
|
||||
Draw a House and export to PNG
|
||||
┌─────────┬─────────────────┬───────────────────────┬──────────────────────────┬────────────────────────────┬───────────────────────────┬─────────┐
|
||||
│ (index) │ Task name │ Latency average (ns) │ Latency median (ns) │ Throughput average (ops/s) │ Throughput median (ops/s) │ Samples │
|
||||
├─────────┼─────────────────┼───────────────────────┼──────────────────────────┼────────────────────────────┼───────────────────────────┼─────────┤
|
||||
│ 0 │ '@napi-rs/skia' │ '14676992.14 ± 0.68%' │ '14602333.00' │ '68 ± 0.59%' │ '68' │ 69 │
|
||||
│ 1 │ 'skia-canvas' │ '21167809.17 ± 2.05%' │ '20960021.00 ± 13646.00' │ '47 ± 1.31%' │ '48' │ 64 │
|
||||
│ 2 │ 'node-canvas' │ '16552027.42 ± 0.70%' │ '16451291.50 ± 2208.50' │ '60 ± 0.62%' │ '61' │ 64 │
|
||||
└─────────┴─────────────────┴───────────────────────┴──────────────────────────┴────────────────────────────┴───────────────────────────┴─────────┘
|
||||
Draw Gradient and export to PNG
|
||||
┌─────────┬─────────────────┬───────────────────────┬─────────────────────────┬────────────────────────────┬───────────────────────────┬─────────┐
|
||||
│ (index) │ Task name │ Latency average (ns) │ Latency median (ns) │ Throughput average (ops/s) │ Throughput median (ops/s) │ Samples │
|
||||
├─────────┼─────────────────┼───────────────────────┼─────────────────────────┼────────────────────────────┼───────────────────────────┼─────────┤
|
||||
│ 0 │ '@napi-rs/skia' │ '15228495.58 ± 0.53%' │ '15146312.50 ± 1187.50' │ '66 ± 0.48%' │ '66' │ 66 │
|
||||
│ 1 │ 'skia-canvas' │ '21725564.41 ± 2.20%' │ '21412520.50 ± 2104.50' │ '46 ± 1.39%' │ '47' │ 64 │
|
||||
│ 2 │ 'node-canvas' │ '17976022.14 ± 1.53%' │ '17563479.50 ± 5104.50' │ '56 ± 1.38%' │ '57' │ 64 │
|
||||
└─────────┴─────────────────┴───────────────────────┴─────────────────────────┴────────────────────────────┴───────────────────────────┴─────────┘
|
||||
```
|
||||
|
||||
# Features
|
||||
|
||||
## Path2D
|
||||
|
||||
```typescript
|
||||
new Path2D()
|
||||
new Path2D(path: Path2D)
|
||||
// new Path2D('M108.956,403.826c0,0,0.178,3.344-1.276,3.311 c-1.455-0.033-30.507-84.917-66.752-80.957C40.928,326.18,72.326,313.197,108.956,403.826z')
|
||||
new Path2D(path: string)
|
||||
```
|
||||
|
||||
```typescript
|
||||
export interface DOMMatrix2DInit {
|
||||
a: number
|
||||
b: number
|
||||
c: number
|
||||
d: number
|
||||
e: number
|
||||
f: number
|
||||
}
|
||||
|
||||
export class Path2D {
|
||||
constructor(path?: Path2D | string)
|
||||
|
||||
addPath(path: Path2D, transform?: DOMMatrix2DInit): void
|
||||
arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, anticlockwise?: boolean): void
|
||||
arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void
|
||||
bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, y: number): void
|
||||
closePath(): void
|
||||
ellipse(
|
||||
x: number,
|
||||
y: number,
|
||||
radiusX: number,
|
||||
radiusY: number,
|
||||
rotation: number,
|
||||
startAngle: number,
|
||||
endAngle: number,
|
||||
anticlockwise?: boolean,
|
||||
): void
|
||||
lineTo(x: number, y: number): void
|
||||
moveTo(x: number, y: number): void
|
||||
quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void
|
||||
rect(x: number, y: number, w: number, h: number): void
|
||||
|
||||
// PathKit methods
|
||||
op(path: Path2D, operation: PathOp): Path2D
|
||||
toSVGString(): string
|
||||
getFillType(): FillType
|
||||
getFillTypeString(): string
|
||||
setFillType(type: FillType): void
|
||||
simplify(): Path2D
|
||||
asWinding(): Path2D
|
||||
stroke(stroke?: StrokeOptions): Path2D
|
||||
transform(transform: DOMMatrix2DInit): Path2D
|
||||
getBounds(): [left: number, top: number, right: number, bottom: number]
|
||||
computeTightBounds(): [left: number, top: number, right: number, bottom: number]
|
||||
trim(start: number, end: number, isComplement?: boolean): Path2D
|
||||
round(radius: number): Path2D
|
||||
equals(path: Path2D): boolean
|
||||
}
|
||||
```
|
||||
|
||||
## PathKit
|
||||
|
||||
`PathKit` is a toolset for manipulating Path in `Skia`, supporting **_quadratic beziers_**, **_cubic beziers_** and **_conics_**.
|
||||
The main features are.
|
||||
|
||||
### Path Operation
|
||||
|
||||
`.op(path, PathOp)`
|
||||
|
||||
```js
|
||||
const pathOne = new Path2D(
|
||||
'M8 50H92C96.4183 50 100 53.5817 100 58V142C100 146.418 96.4183 150 92 150H8C3.58172 150 0 146.418 0 142V58C0 53.5817 3.58172 50 8 50Z',
|
||||
)
|
||||
const pathTwo = new Path2D(
|
||||
'"M58 0H142C146.418 0 150 3.58172 150 8V92C150 96.4183 146.418 100 142 100H58C53.5817 100 50 96.4183 50 92V8C50 3.58172 53.5817 0 58 0Z',
|
||||
)
|
||||
|
||||
pathOne.op(pathTwo, PathOp.Intersect).toSVGString()
|
||||
// => "M100 100L58 100C53.5817 100 50 96.4183 50 92L50 50L92 50C96.4183 50 100 53.5817 100 58L100 100Z"
|
||||
```
|
||||
|
||||
- **Union**, subtract the op path from the first path
|
||||
- **Difference**, intersect the two paths
|
||||
- **ReverseDifference**, union (inclusive-or) the two paths
|
||||
- **Intersect**, exclusive-or the two paths
|
||||
- **XOR**, subtract the first path from the op path
|
||||
|
||||

|
||||
|
||||
### Covert `FillType` in **_Path_**
|
||||
|
||||
`.asWinding()`
|
||||
|
||||
You can convert `fill-rule="evenodd"` to `fill-rule="nonzero"` in SVG.
|
||||
This is useful for **OpenType** font-related tools, as `fill-rule="nonzero"` is only supported in **OpenType** fonts.
|
||||
|
||||

|
||||
|
||||
```js
|
||||
const pathCircle = new Path2D(
|
||||
'M24.2979 13.6364H129.394V40.9091H24.2979L14.6278 27.2727L24.2979 13.6364ZM21.9592 0C19.0246 0 16.2716 1.42436 14.571 3.82251L1.67756 22.0043C-0.559186 25.1585 -0.559186 29.387 1.67756 32.5411L14.571 50.7227C16.2716 53.1209 19.0246 54.5455 21.9592 54.5455H70.4673V68.1818H16.073C11.0661 68.1818 7.00728 72.2518 7.00728 77.2727V113.636C7.00728 118.657 11.0661 122.727 16.073 122.727H70.4673V150H84.0658V122.727H128.041C130.975 122.727 133.729 121.303 135.429 118.905L148.323 100.723C150.559 97.5686 150.559 93.3405 148.323 90.1864L135.429 72.0045C133.729 69.6064 130.975 68.1818 128.041 68.1818H84.0658V54.5455H133.927C138.934 54.5455 142.993 50.4755 142.993 45.4545V9.09091C142.993 4.07014 138.934 0 133.927 0H21.9592ZM125.702 109.091H20.6058V81.8182H125.702L135.372 95.4545L125.702 109.091Z',
|
||||
)
|
||||
pathCircle.setFillType(FillType.EvenOdd)
|
||||
pathCircle.asWinding().toSVGString()
|
||||
// => "M24.2979 13.6364L129.394 13.6364L129.394 40.9091L24.2979 40.9091L14.6278 27.2727L24.2979 13.6364ZM21.9592 0C19.0246 0 16.2716 1.42436 14.571 3.82251L1.67756 22.0043C-0.559186 25.1585 -0.559186 29.387 1.67756 32.5411L14.571 50.7227C16.2716 53.1209 19.0246 54.5455 21.9592 54.5455L70.4673 54.5455L70.4673 68.1818L16.073 68.1818C11.0661 68.1818 7.00728 72.2518 7.00728 77.2727L7.00728 113.636C7.00728 118.657 11.0661 122.727 16.073 122.727L70.4673 122.727L70.4673 150L84.0658 150L84.0658 122.727L128.041 122.727C130.975 122.727 133.729 121.303 135.429 118.905L148.323 100.723C150.559 97.5686 150.559 93.3405 148.323 90.1864L135.429 72.0045C133.729 69.6064 130.975 68.1818 128.041 68.1818L84.0658 68.1818L84.0658 54.5455L133.927 54.5455C138.934 54.5455 142.993 50.4755 142.993 45.4545L142.993 9.09091C142.993 4.07014 138.934 0 133.927 0L21.9592 0ZM125.702 109.091L20.6058 109.091L20.6058 81.8182L125.702 81.8182L135.372 95.4545L125.702 109.091Z"
|
||||
```
|
||||
|
||||
### Simplify **_Path_**
|
||||
|
||||
`.simplify()`
|
||||
|
||||
Set the path to the same non-overlapping contour as the original path area, which means that it can also remove overlapping paths.
|
||||
|
||||
<img width="800" src="./docs/imgs/simplify.png" >
|
||||
|
||||
[SVG with overlapping paths](./docs/imgs/overlapping-path.svg) (Left)
|
||||
|
||||
```js
|
||||
const path =
|
||||
'M2.933,89.89 L89.005,3.818 Q90.412,2.411 92.249,1.65 Q94.087,0.889 96.076,0.889 Q98.065,0.889 99.903,1.65 Q101.741,2.411 103.147,3.818 L189.22,89.89 Q190.626,91.296 191.387,93.134 Q192.148,94.972 192.148,96.961 Q192.148,98.95 191.387,100.788 Q190.626,102.625 189.219,104.032 Q187.813,105.439 185.975,106.2 Q184.138,106.961 182.148,106.961 Q180.159,106.961 178.322,106.2 Q176.484,105.439 175.077,104.032 L89.005,17.96 L96.076,10.889 L103.147,17.96 L17.075,104.032 Q15.668,105.439 13.831,106.2 Q11.993,106.961 10.004,106.961 Q8.015,106.961 6.177,106.2 Q4.339,105.439 2.933,104.032 Q1.526,102.625 0.765,100.788 Q0.004,98.95 0.004,96.961 Q0.004,94.972 0.765,93.134 Q1.526,91.296 2.933,89.89 Z'
|
||||
|
||||
path.simplify().toSVGString()
|
||||
// => "M89.005 3.818L2.933 89.89Q1.526 91.296 0.765 93.134Q0.004 94.972 0.004 96.961Q0.004 98.95 0.765 100.788Q1.526 102.625 2.933 104.032Q4.339 105.439 6.177 106.2Q8.015 106.961 10.004 106.961Q11.993 106.961 13.831 106.2Q15.668 105.439 17.075 104.032L96.076 25.031L175.077 104.032Q176.484 105.439 178.322 106.2Q180.159 106.961 182.148 106.961Q184.138 106.961 185.975 106.2Q187.813 105.439 189.219 104.032Q190.626 102.625 191.387 100.788Q192.148 98.95 192.148 96.961Q192.148 94.972 191.387 93.134Q190.626 91.296 189.22 89.89L103.147 3.818Q101.741 2.411 99.903 1.65Q98.065 0.889 96.076 0.889Q94.087 0.889 92.249 1.65Q90.412 2.411 89.005 3.818Z"
|
||||
```
|
||||
|
||||
## Lottie Animation
|
||||
|
||||
Render [Lottie](https://airbnb.io/lottie/) animations using Skia's [Skottie](https://skia.org/docs/user/modules/skottie/) module.
|
||||
|
||||
### Load Animation
|
||||
|
||||
```js
|
||||
const { LottieAnimation } = require('@napi-rs/canvas')
|
||||
|
||||
// Load from file
|
||||
const animation = LottieAnimation.loadFromFile('animation.json')
|
||||
|
||||
// Load from JSON string with resource path for external assets
|
||||
const animation = LottieAnimation.loadFromData(jsonString, {
|
||||
resourcePath: '/path/to/assets',
|
||||
})
|
||||
```
|
||||
|
||||
### Animation Properties
|
||||
|
||||
```js
|
||||
animation.duration // Total duration in seconds
|
||||
animation.fps // Frames per second
|
||||
animation.frames // Total frame count
|
||||
animation.width // Animation width
|
||||
animation.height // Animation height
|
||||
animation.version // Lottie format version
|
||||
```
|
||||
|
||||
### Playback Control
|
||||
|
||||
```js
|
||||
animation.seekFrame(30) // Seek to frame 30
|
||||
animation.seek(1.5) // Seek to 1.5 seconds
|
||||
```
|
||||
|
||||
### Render to Canvas
|
||||
|
||||
```js
|
||||
const { createCanvas, LottieAnimation } = require('@napi-rs/canvas')
|
||||
|
||||
const animation = LottieAnimation.loadFromFile('animation.json')
|
||||
const canvas = createCanvas(animation.width, animation.height)
|
||||
const ctx = canvas.getContext('2d')
|
||||
|
||||
// Render at original size
|
||||
animation.render(ctx)
|
||||
|
||||
// Render with custom destination rect
|
||||
animation.render(ctx, { x: 0, y: 0, width: 800, height: 600 })
|
||||
```
|
||||
|
||||
### Supported Features
|
||||
|
||||
- **Embedded images** - Base64-encoded images (`data:image/png;base64,...`)
|
||||
- **Embedded fonts** - Vector glyph paths for text rendering without system fonts
|
||||
- **External assets** - Load images from `resourcePath` directory
|
||||
- **dotLottie format** - Extract `.lottie` ZIP files at runtime (see example)
|
||||
|
||||
### Example: Encode Lottie to Video
|
||||
|
||||
See [`example/lottie-to-video.ts`](./example/lottie-to-video.ts) for encoding Lottie animations to MP4 using [`@napi-rs/webcodecs`](https://github.com/Brooooooklyn/webcodecs-node).
|
||||
|
||||
```js
|
||||
import { createCanvas, LottieAnimation } from '@napi-rs/canvas'
|
||||
import {
|
||||
VideoEncoder,
|
||||
VideoFrame,
|
||||
Mp4Muxer,
|
||||
type EncodedVideoChunk,
|
||||
type EncodedVideoChunkMetadata,
|
||||
} from '@napi-rs/webcodecs'
|
||||
|
||||
const animation = LottieAnimation.loadFromFile('animation.json')
|
||||
const canvas = createCanvas(animation.width, animation.height)
|
||||
const ctx = canvas.getContext('2d')
|
||||
|
||||
for (let frame = 0; frame < animation.frames; frame++) {
|
||||
animation.seekFrame(frame)
|
||||
ctx.fillStyle = '#ffffff'
|
||||
ctx.fillRect(0, 0, canvas.width, canvas.height)
|
||||
animation.render(ctx)
|
||||
// Encode frame to video...
|
||||
}
|
||||
```
|
||||
|
||||
# [Example](./example/tiger.js)
|
||||
|
||||
> The tiger.json was serialized from [gojs/samples/tiger](https://github.com/NorthwoodsSoftware/GoJS/blob/master/samples/tiger.html)
|
||||
|
||||
<img width="500" src="example/tiger.png">
|
||||
|
||||
```shell
|
||||
node example/anime-girl.js
|
||||
```
|
||||
|
||||
| SVG | PNG |
|
||||
| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| <img width="500" src="example/anime-girl.svg"><br/>[CC-BY-SA 3.0](https://creativecommons.org/licenses/by/3.0) by [Niabot](https://commons.wikimedia.org/wiki/User:Niabot) | <img width="500" src="example/anime-girl.png"><br/>[CC-BY-SA 3.0](https://creativecommons.org/licenses/by/3.0) by [Niabot](https://commons.wikimedia.org/wiki/User:Niabot) |
|
||||
|
||||
# Building
|
||||
|
||||
## Build skia from source
|
||||
|
||||
You can build this project from source, the system requirements are here: https://skia.org/docs/user/build
|
||||
|
||||
```sh
|
||||
# Clone the code:
|
||||
$ git clone --recurse-submodules https://github.com/Brooooooklyn/canvas.git
|
||||
$ cd canvas
|
||||
|
||||
# Build Skia:
|
||||
$ node scripts/build-skia.js
|
||||
|
||||
# Install NPM packages, build the Node.js addon:
|
||||
$ npm install -g yarn
|
||||
$ yarn install --mode=skip-build # Here are modules that are used for benchmarking and are hard to install, you can skip it by specifying `--mode=skip-build`
|
||||
$ sudo dnf install clang # https://fedora.pkgs.org/34/fedora-x86_64/clang-12.0.0-0.3.rc1.fc34.x86_64.rpm.html
|
||||
$ yarn build
|
||||
|
||||
# All done! Run test cases or examples now:
|
||||
$ yarn test
|
||||
$ node example/tiger.js
|
||||
```
|
||||
|
||||
## Pull pre-build skia binary from GitHub
|
||||
|
||||
You can pull skia pre-build binaries if you just care the `Rust` part:
|
||||
|
||||
```sh
|
||||
# Clone the code:
|
||||
$ git clone --recurse-submodules https://github.com/Brooooooklyn/canvas.git
|
||||
$ cd canvas
|
||||
|
||||
# Download Skia binaries:
|
||||
# It will pull the binaries match the git hash in `./skia` submodule
|
||||
$ node scripts/release-skia-binary.mjs --download
|
||||
|
||||
# Install NPM packages, build the Node.js addon:
|
||||
$ npm install -g yarn
|
||||
$ yarn install --mode=skip-build
|
||||
$ sudo dnf install clang # https://fedora.pkgs.org/34/fedora-x86_64/clang-12.0.0-0.3.rc1.fc34.x86_64.rpm.html
|
||||
$ yarn build
|
||||
|
||||
# All done! Run test cases or examples now:
|
||||
$ yarn test
|
||||
$ node example/tiger.js
|
||||
```
|
||||
Generated
Vendored
+873
@@ -0,0 +1,873 @@
|
||||
const { inspect } = require('util')
|
||||
/*
|
||||
* vendored in order to fix its dependence on the window global [cds 2020/08/04]
|
||||
* otherwise unchanged from https://github.com/jarek-foksa/geometry-polyfill/tree/f36bbc8f4bc43539d980687904ce46c8e915543d
|
||||
*/
|
||||
|
||||
// @info
|
||||
// DOMPoint polyfill
|
||||
// @src
|
||||
// https://drafts.fxtf.org/geometry/#DOMPoint
|
||||
// https://github.com/chromium/chromium/blob/master/third_party/blink/renderer/core/geometry/dom_point_read_only.cc
|
||||
class DOMPoint {
|
||||
constructor(x = 0, y = 0, z = 0, w = 1) {
|
||||
this.x = x
|
||||
this.y = y
|
||||
this.z = z
|
||||
this.w = w
|
||||
}
|
||||
|
||||
static fromPoint(otherPoint) {
|
||||
return new DOMPoint(
|
||||
otherPoint.x,
|
||||
otherPoint.y,
|
||||
otherPoint.z !== undefined ? otherPoint.z : 0,
|
||||
otherPoint.w !== undefined ? otherPoint.w : 1,
|
||||
)
|
||||
}
|
||||
|
||||
matrixTransform(matrix) {
|
||||
if ((matrix.is2D || matrix instanceof SVGMatrix) && this.z === 0 && this.w === 1) {
|
||||
return new DOMPoint(
|
||||
this.x * matrix.a + this.y * matrix.c + matrix.e,
|
||||
this.x * matrix.b + this.y * matrix.d + matrix.f,
|
||||
0,
|
||||
1,
|
||||
)
|
||||
} else {
|
||||
return new DOMPoint(
|
||||
this.x * matrix.m11 + this.y * matrix.m21 + this.z * matrix.m31 + this.w * matrix.m41,
|
||||
this.x * matrix.m12 + this.y * matrix.m22 + this.z * matrix.m32 + this.w * matrix.m42,
|
||||
this.x * matrix.m13 + this.y * matrix.m23 + this.z * matrix.m33 + this.w * matrix.m43,
|
||||
this.x * matrix.m14 + this.y * matrix.m24 + this.z * matrix.m34 + this.w * matrix.m44,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
toJSON() {
|
||||
return {
|
||||
x: this.x,
|
||||
y: this.y,
|
||||
z: this.z,
|
||||
w: this.w,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// @info
|
||||
// DOMRect polyfill
|
||||
// @src
|
||||
// https://drafts.fxtf.org/geometry/#DOMRect
|
||||
// https://github.com/chromium/chromium/blob/master/third_party/blink/renderer/core/geometry/dom_rect_read_only.cc
|
||||
|
||||
class DOMRect {
|
||||
constructor(x = 0, y = 0, width = 0, height = 0) {
|
||||
this.x = x
|
||||
this.y = y
|
||||
this.width = width
|
||||
this.height = height
|
||||
}
|
||||
|
||||
static fromRect(otherRect) {
|
||||
return new DOMRect(otherRect.x, otherRect.y, otherRect.width, otherRect.height)
|
||||
}
|
||||
|
||||
get top() {
|
||||
return this.y
|
||||
}
|
||||
|
||||
get left() {
|
||||
return this.x
|
||||
}
|
||||
|
||||
get right() {
|
||||
return this.x + this.width
|
||||
}
|
||||
|
||||
get bottom() {
|
||||
return this.y + this.height
|
||||
}
|
||||
|
||||
toJSON() {
|
||||
return {
|
||||
x: this.x,
|
||||
y: this.y,
|
||||
width: this.width,
|
||||
height: this.height,
|
||||
top: this.top,
|
||||
left: this.left,
|
||||
right: this.right,
|
||||
bottom: this.bottom,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const propertyName of ['top', 'right', 'bottom', 'left']) {
|
||||
const propertyDescriptor = Object.getOwnPropertyDescriptor(DOMRect.prototype, propertyName)
|
||||
propertyDescriptor.enumerable = true
|
||||
Object.defineProperty(DOMRect.prototype, propertyName, propertyDescriptor)
|
||||
}
|
||||
|
||||
// @info
|
||||
// DOMMatrix polyfill (SVG 2)
|
||||
// @src
|
||||
// https://github.com/chromium/chromium/blob/master/third_party/blink/renderer/core/geometry/dom_matrix_read_only.cc
|
||||
// https://github.com/tocharomera/generativecanvas/blob/master/node-canvas/lib/DOMMatrix.js
|
||||
|
||||
const M11 = 0,
|
||||
M12 = 1,
|
||||
M13 = 2,
|
||||
M14 = 3
|
||||
const M21 = 4,
|
||||
M22 = 5,
|
||||
M23 = 6,
|
||||
M24 = 7
|
||||
const M31 = 8,
|
||||
M32 = 9,
|
||||
M33 = 10,
|
||||
M34 = 11
|
||||
const M41 = 12,
|
||||
M42 = 13,
|
||||
M43 = 14,
|
||||
M44 = 15
|
||||
|
||||
const A = M11,
|
||||
B = M12
|
||||
const C = M21,
|
||||
D = M22
|
||||
const E = M41,
|
||||
F = M42
|
||||
|
||||
const DEGREE_PER_RAD = 180 / Math.PI
|
||||
const RAD_PER_DEGREE = Math.PI / 180
|
||||
|
||||
const VALUES = Symbol('values')
|
||||
const IS_2D = Symbol('is2D')
|
||||
|
||||
function parseMatrix(init) {
|
||||
let parsed = init.replace(/matrix\(/, '').split(/,/, 7)
|
||||
|
||||
if (parsed.length !== 6) {
|
||||
throw new Error(`Failed to parse ${init}`)
|
||||
}
|
||||
|
||||
parsed = parsed.map(parseFloat)
|
||||
|
||||
return [parsed[0], parsed[1], 0, 0, parsed[2], parsed[3], 0, 0, 0, 0, 1, 0, parsed[4], parsed[5], 0, 1]
|
||||
}
|
||||
|
||||
function parseMatrix3d(init) {
|
||||
const parsed = init.replace(/matrix3d\(/, '').split(/,/, 17)
|
||||
|
||||
if (parsed.length !== 16) {
|
||||
throw new Error(`Failed to parse ${init}`)
|
||||
}
|
||||
|
||||
return parsed.map(parseFloat)
|
||||
}
|
||||
|
||||
function parseTransform(tform) {
|
||||
const type = tform.split(/\(/, 1)[0]
|
||||
|
||||
if (type === 'matrix') {
|
||||
return parseMatrix(tform)
|
||||
} else if (type === 'matrix3d') {
|
||||
return parseMatrix3d(tform)
|
||||
} else {
|
||||
throw new Error(`${type} parsing not implemented`)
|
||||
}
|
||||
}
|
||||
|
||||
const setNumber2D = (receiver, index, value) => {
|
||||
if (typeof value !== 'number') {
|
||||
throw new TypeError('Expected number')
|
||||
}
|
||||
|
||||
receiver[VALUES][index] = value
|
||||
}
|
||||
|
||||
const setNumber3D = (receiver, index, value) => {
|
||||
if (typeof value !== 'number') {
|
||||
throw new TypeError('Expected number')
|
||||
}
|
||||
|
||||
if (index === M33 || index === M44) {
|
||||
if (value !== 1) {
|
||||
receiver[IS_2D] = false
|
||||
}
|
||||
} else if (value !== 0) {
|
||||
receiver[IS_2D] = false
|
||||
}
|
||||
|
||||
receiver[VALUES][index] = value
|
||||
}
|
||||
|
||||
const newInstance = (values) => {
|
||||
const instance = Object.create(DOMMatrix.prototype)
|
||||
instance.constructor = DOMMatrix
|
||||
instance[IS_2D] = true
|
||||
instance[VALUES] = values
|
||||
|
||||
return instance
|
||||
}
|
||||
|
||||
const multiply = (first, second) => {
|
||||
const dest = new Float64Array(16)
|
||||
|
||||
for (let i = 0; i < 4; i++) {
|
||||
for (let j = 0; j < 4; j++) {
|
||||
let sum = 0
|
||||
|
||||
for (let k = 0; k < 4; k++) {
|
||||
sum += first[i * 4 + k] * second[k * 4 + j]
|
||||
}
|
||||
|
||||
dest[i * 4 + j] = sum
|
||||
}
|
||||
}
|
||||
|
||||
return dest
|
||||
}
|
||||
|
||||
class DOMMatrix {
|
||||
get m11() {
|
||||
return this[VALUES][M11]
|
||||
}
|
||||
set m11(value) {
|
||||
setNumber2D(this, M11, value)
|
||||
}
|
||||
get m12() {
|
||||
return this[VALUES][M12]
|
||||
}
|
||||
set m12(value) {
|
||||
setNumber2D(this, M12, value)
|
||||
}
|
||||
get m13() {
|
||||
return this[VALUES][M13]
|
||||
}
|
||||
set m13(value) {
|
||||
setNumber3D(this, M13, value)
|
||||
}
|
||||
get m14() {
|
||||
return this[VALUES][M14]
|
||||
}
|
||||
set m14(value) {
|
||||
setNumber3D(this, M14, value)
|
||||
}
|
||||
get m21() {
|
||||
return this[VALUES][M21]
|
||||
}
|
||||
set m21(value) {
|
||||
setNumber2D(this, M21, value)
|
||||
}
|
||||
get m22() {
|
||||
return this[VALUES][M22]
|
||||
}
|
||||
set m22(value) {
|
||||
setNumber2D(this, M22, value)
|
||||
}
|
||||
get m23() {
|
||||
return this[VALUES][M23]
|
||||
}
|
||||
set m23(value) {
|
||||
setNumber3D(this, M23, value)
|
||||
}
|
||||
get m24() {
|
||||
return this[VALUES][M24]
|
||||
}
|
||||
set m24(value) {
|
||||
setNumber3D(this, M24, value)
|
||||
}
|
||||
get m31() {
|
||||
return this[VALUES][M31]
|
||||
}
|
||||
set m31(value) {
|
||||
setNumber3D(this, M31, value)
|
||||
}
|
||||
get m32() {
|
||||
return this[VALUES][M32]
|
||||
}
|
||||
set m32(value) {
|
||||
setNumber3D(this, M32, value)
|
||||
}
|
||||
get m33() {
|
||||
return this[VALUES][M33]
|
||||
}
|
||||
set m33(value) {
|
||||
setNumber3D(this, M33, value)
|
||||
}
|
||||
get m34() {
|
||||
return this[VALUES][M34]
|
||||
}
|
||||
set m34(value) {
|
||||
setNumber3D(this, M34, value)
|
||||
}
|
||||
get m41() {
|
||||
return this[VALUES][M41]
|
||||
}
|
||||
set m41(value) {
|
||||
setNumber2D(this, M41, value)
|
||||
}
|
||||
get m42() {
|
||||
return this[VALUES][M42]
|
||||
}
|
||||
set m42(value) {
|
||||
setNumber2D(this, M42, value)
|
||||
}
|
||||
get m43() {
|
||||
return this[VALUES][M43]
|
||||
}
|
||||
set m43(value) {
|
||||
setNumber3D(this, M43, value)
|
||||
}
|
||||
get m44() {
|
||||
return this[VALUES][M44]
|
||||
}
|
||||
set m44(value) {
|
||||
setNumber3D(this, M44, value)
|
||||
}
|
||||
|
||||
get a() {
|
||||
return this[VALUES][A]
|
||||
}
|
||||
set a(value) {
|
||||
setNumber2D(this, A, value)
|
||||
}
|
||||
get b() {
|
||||
return this[VALUES][B]
|
||||
}
|
||||
set b(value) {
|
||||
setNumber2D(this, B, value)
|
||||
}
|
||||
get c() {
|
||||
return this[VALUES][C]
|
||||
}
|
||||
set c(value) {
|
||||
setNumber2D(this, C, value)
|
||||
}
|
||||
get d() {
|
||||
return this[VALUES][D]
|
||||
}
|
||||
set d(value) {
|
||||
setNumber2D(this, D, value)
|
||||
}
|
||||
get e() {
|
||||
return this[VALUES][E]
|
||||
}
|
||||
set e(value) {
|
||||
setNumber2D(this, E, value)
|
||||
}
|
||||
get f() {
|
||||
return this[VALUES][F]
|
||||
}
|
||||
set f(value) {
|
||||
setNumber2D(this, F, value)
|
||||
}
|
||||
|
||||
get is2D() {
|
||||
return this[IS_2D]
|
||||
}
|
||||
|
||||
get isIdentity() {
|
||||
const values = this[VALUES]
|
||||
|
||||
return (
|
||||
values[M11] === 1 &&
|
||||
values[M12] === 0 &&
|
||||
values[M13] === 0 &&
|
||||
values[M14] === 0 &&
|
||||
values[M21] === 0 &&
|
||||
values[M22] === 1 &&
|
||||
values[M23] === 0 &&
|
||||
values[M24] === 0 &&
|
||||
values[M31] === 0 &&
|
||||
values[M32] === 0 &&
|
||||
values[M33] === 1 &&
|
||||
values[M34] === 0 &&
|
||||
values[M41] === 0 &&
|
||||
values[M42] === 0 &&
|
||||
values[M43] === 0 &&
|
||||
values[M44] === 1
|
||||
)
|
||||
}
|
||||
|
||||
static fromMatrix(init) {
|
||||
if (init instanceof DOMMatrix) {
|
||||
return new DOMMatrix(init[VALUES])
|
||||
} else if (init instanceof SVGMatrix) {
|
||||
return new DOMMatrix([init.a, init.b, init.c, init.d, init.e, init.f])
|
||||
} else {
|
||||
throw new TypeError('Expected DOMMatrix')
|
||||
}
|
||||
}
|
||||
|
||||
static fromFloat32Array(init) {
|
||||
if (!(init instanceof Float32Array)) throw new TypeError('Expected Float32Array')
|
||||
return new DOMMatrix(init)
|
||||
}
|
||||
|
||||
static fromFloat64Array(init) {
|
||||
if (!(init instanceof Float64Array)) throw new TypeError('Expected Float64Array')
|
||||
return new DOMMatrix(init)
|
||||
}
|
||||
|
||||
// @type
|
||||
// (Float64Array) => void
|
||||
constructor(init) {
|
||||
this[IS_2D] = true
|
||||
|
||||
this[VALUES] = new Float64Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1])
|
||||
|
||||
// Parse CSS transformList
|
||||
if (typeof init === 'string') {
|
||||
if (init === '') {
|
||||
return
|
||||
} else {
|
||||
const tforms = init.split(/\)\s+/, 20).map(parseTransform)
|
||||
|
||||
if (tforms.length === 0) {
|
||||
return
|
||||
}
|
||||
|
||||
init = tforms[0]
|
||||
|
||||
for (let i = 1; i < tforms.length; i++) {
|
||||
init = multiply(tforms[i], init)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let i = 0
|
||||
|
||||
if (init && init.length === 6) {
|
||||
setNumber2D(this, A, init[i++])
|
||||
setNumber2D(this, B, init[i++])
|
||||
setNumber2D(this, C, init[i++])
|
||||
setNumber2D(this, D, init[i++])
|
||||
setNumber2D(this, E, init[i++])
|
||||
setNumber2D(this, F, init[i++])
|
||||
} else if (init && init.length === 16) {
|
||||
setNumber2D(this, M11, init[i++])
|
||||
setNumber2D(this, M12, init[i++])
|
||||
setNumber3D(this, M13, init[i++])
|
||||
setNumber3D(this, M14, init[i++])
|
||||
setNumber2D(this, M21, init[i++])
|
||||
setNumber2D(this, M22, init[i++])
|
||||
setNumber3D(this, M23, init[i++])
|
||||
setNumber3D(this, M24, init[i++])
|
||||
setNumber3D(this, M31, init[i++])
|
||||
setNumber3D(this, M32, init[i++])
|
||||
setNumber3D(this, M33, init[i++])
|
||||
setNumber3D(this, M34, init[i++])
|
||||
setNumber2D(this, M41, init[i++])
|
||||
setNumber2D(this, M42, init[i++])
|
||||
setNumber3D(this, M43, init[i++])
|
||||
setNumber3D(this, M44, init[i])
|
||||
} else if (init !== undefined) {
|
||||
throw new TypeError('Expected string or array.')
|
||||
}
|
||||
}
|
||||
|
||||
dump() {
|
||||
const mat = this[VALUES]
|
||||
console.info([mat.slice(0, 4), mat.slice(4, 8), mat.slice(8, 12), mat.slice(12, 16)])
|
||||
}
|
||||
|
||||
[inspect.custom](depth) {
|
||||
if (depth < 0) return '[DOMMatrix]'
|
||||
|
||||
const { a, b, c, d, e, f, is2D, isIdentity } = this
|
||||
if (this.is2D) {
|
||||
return `DOMMatrix ${inspect({ a, b, c, d, e, f, is2D, isIdentity }, { colors: true })}`
|
||||
} else {
|
||||
const { m11, m12, m13, m14, m21, m22, m23, m24, m31, m32, m33, m34, m41, m42, m43, m44, is2D, isIdentity } = this
|
||||
return `DOMMatrix ${inspect(
|
||||
{
|
||||
a,
|
||||
b,
|
||||
c,
|
||||
d,
|
||||
e,
|
||||
f,
|
||||
m11,
|
||||
m12,
|
||||
m13,
|
||||
m14,
|
||||
m21,
|
||||
m22,
|
||||
m23,
|
||||
m24,
|
||||
m31,
|
||||
m32,
|
||||
m33,
|
||||
m34,
|
||||
m41,
|
||||
m42,
|
||||
m43,
|
||||
m44,
|
||||
is2D,
|
||||
isIdentity,
|
||||
},
|
||||
{ colors: true },
|
||||
)}`
|
||||
}
|
||||
}
|
||||
|
||||
multiply(other) {
|
||||
return newInstance(this[VALUES]).multiplySelf(other)
|
||||
}
|
||||
|
||||
multiplySelf(other) {
|
||||
this[VALUES] = multiply(other[VALUES], this[VALUES])
|
||||
|
||||
if (!other.is2D) {
|
||||
this[IS_2D] = false
|
||||
}
|
||||
|
||||
return this
|
||||
}
|
||||
|
||||
preMultiplySelf(other) {
|
||||
this[VALUES] = multiply(this[VALUES], other[VALUES])
|
||||
|
||||
if (!other.is2D) {
|
||||
this[IS_2D] = false
|
||||
}
|
||||
|
||||
return this
|
||||
}
|
||||
|
||||
translate(tx, ty, tz) {
|
||||
return newInstance(this[VALUES]).translateSelf(tx, ty, tz)
|
||||
}
|
||||
|
||||
translateSelf(tx = 0, ty = 0, tz = 0) {
|
||||
this[VALUES] = multiply([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, tx, ty, tz, 1], this[VALUES])
|
||||
|
||||
if (tz !== 0) {
|
||||
this[IS_2D] = false
|
||||
}
|
||||
|
||||
return this
|
||||
}
|
||||
|
||||
scale(scaleX, scaleY, scaleZ, originX, originY, originZ) {
|
||||
return newInstance(this[VALUES]).scaleSelf(scaleX, scaleY, scaleZ, originX, originY, originZ)
|
||||
}
|
||||
|
||||
scale3d(scale, originX, originY, originZ) {
|
||||
return newInstance(this[VALUES]).scale3dSelf(scale, originX, originY, originZ)
|
||||
}
|
||||
|
||||
scale3dSelf(scale, originX, originY, originZ) {
|
||||
return this.scaleSelf(scale, scale, scale, originX, originY, originZ)
|
||||
}
|
||||
|
||||
scaleSelf(scaleX, scaleY, scaleZ, originX, originY, originZ) {
|
||||
// Not redundant with translate's checks because we need to negate the values later.
|
||||
if (typeof originX !== 'number') originX = 0
|
||||
if (typeof originY !== 'number') originY = 0
|
||||
if (typeof originZ !== 'number') originZ = 0
|
||||
|
||||
this.translateSelf(originX, originY, originZ)
|
||||
|
||||
if (typeof scaleX !== 'number') scaleX = 1
|
||||
if (typeof scaleY !== 'number') scaleY = scaleX
|
||||
if (typeof scaleZ !== 'number') scaleZ = 1
|
||||
|
||||
this[VALUES] = multiply([scaleX, 0, 0, 0, 0, scaleY, 0, 0, 0, 0, scaleZ, 0, 0, 0, 0, 1], this[VALUES])
|
||||
|
||||
this.translateSelf(-originX, -originY, -originZ)
|
||||
|
||||
if (scaleZ !== 1 || originZ !== 0) {
|
||||
this[IS_2D] = false
|
||||
}
|
||||
|
||||
return this
|
||||
}
|
||||
|
||||
rotateFromVector(x, y) {
|
||||
return newInstance(this[VALUES]).rotateFromVectorSelf(x, y)
|
||||
}
|
||||
|
||||
rotateFromVectorSelf(x = 0, y = 0) {
|
||||
const theta = x === 0 && y === 0 ? 0 : Math.atan2(y, x) * DEGREE_PER_RAD
|
||||
return this.rotateSelf(theta)
|
||||
}
|
||||
|
||||
rotate(rotX, rotY, rotZ) {
|
||||
return newInstance(this[VALUES]).rotateSelf(rotX, rotY, rotZ)
|
||||
}
|
||||
|
||||
rotateSelf(rotX, rotY, rotZ) {
|
||||
if (rotY === undefined && rotZ === undefined) {
|
||||
rotZ = rotX
|
||||
rotX = rotY = 0
|
||||
}
|
||||
|
||||
if (typeof rotY !== 'number') rotY = 0
|
||||
if (typeof rotZ !== 'number') rotZ = 0
|
||||
|
||||
if (rotX !== 0 || rotY !== 0) {
|
||||
this[IS_2D] = false
|
||||
}
|
||||
|
||||
rotX *= RAD_PER_DEGREE
|
||||
rotY *= RAD_PER_DEGREE
|
||||
rotZ *= RAD_PER_DEGREE
|
||||
|
||||
let c = Math.cos(rotZ)
|
||||
let s = Math.sin(rotZ)
|
||||
|
||||
this[VALUES] = multiply([c, s, 0, 0, -s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1], this[VALUES])
|
||||
|
||||
c = Math.cos(rotY)
|
||||
s = Math.sin(rotY)
|
||||
|
||||
this[VALUES] = multiply([c, 0, -s, 0, 0, 1, 0, 0, s, 0, c, 0, 0, 0, 0, 1], this[VALUES])
|
||||
|
||||
c = Math.cos(rotX)
|
||||
s = Math.sin(rotX)
|
||||
|
||||
this[VALUES] = multiply([1, 0, 0, 0, 0, c, s, 0, 0, -s, c, 0, 0, 0, 0, 1], this[VALUES])
|
||||
|
||||
return this
|
||||
}
|
||||
|
||||
rotateAxisAngle(x, y, z, angle) {
|
||||
return newInstance(this[VALUES]).rotateAxisAngleSelf(x, y, z, angle)
|
||||
}
|
||||
|
||||
rotateAxisAngleSelf(x = 0, y = 0, z = 0, angle = 0) {
|
||||
const length = Math.sqrt(x * x + y * y + z * z)
|
||||
|
||||
if (length === 0) {
|
||||
return this
|
||||
}
|
||||
|
||||
if (length !== 1) {
|
||||
x /= length
|
||||
y /= length
|
||||
z /= length
|
||||
}
|
||||
|
||||
angle *= RAD_PER_DEGREE
|
||||
|
||||
const c = Math.cos(angle)
|
||||
const s = Math.sin(angle)
|
||||
const t = 1 - c
|
||||
const tx = t * x
|
||||
const ty = t * y
|
||||
|
||||
this[VALUES] = multiply(
|
||||
[
|
||||
tx * x + c,
|
||||
tx * y + s * z,
|
||||
tx * z - s * y,
|
||||
0,
|
||||
tx * y - s * z,
|
||||
ty * y + c,
|
||||
ty * z + s * x,
|
||||
0,
|
||||
tx * z + s * y,
|
||||
ty * z - s * x,
|
||||
t * z * z + c,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
],
|
||||
this[VALUES],
|
||||
)
|
||||
|
||||
if (x !== 0 || y !== 0) {
|
||||
this[IS_2D] = false
|
||||
}
|
||||
|
||||
return this
|
||||
}
|
||||
|
||||
skewX(sx) {
|
||||
return newInstance(this[VALUES]).skewXSelf(sx)
|
||||
}
|
||||
|
||||
skewXSelf(sx) {
|
||||
if (typeof sx !== 'number') {
|
||||
return this
|
||||
}
|
||||
|
||||
const t = Math.tan(sx * RAD_PER_DEGREE)
|
||||
|
||||
this[VALUES] = multiply([1, 0, 0, 0, t, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1], this[VALUES])
|
||||
|
||||
return this
|
||||
}
|
||||
|
||||
skewY(sy) {
|
||||
return newInstance(this[VALUES]).skewYSelf(sy)
|
||||
}
|
||||
|
||||
skewYSelf(sy) {
|
||||
if (typeof sy !== 'number') {
|
||||
return this
|
||||
}
|
||||
|
||||
const t = Math.tan(sy * RAD_PER_DEGREE)
|
||||
|
||||
this[VALUES] = multiply([1, t, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1], this[VALUES])
|
||||
|
||||
return this
|
||||
}
|
||||
|
||||
flipX() {
|
||||
return newInstance(multiply([-1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1], this[VALUES]))
|
||||
}
|
||||
|
||||
flipY() {
|
||||
return newInstance(multiply([1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1], this[VALUES]))
|
||||
}
|
||||
|
||||
inverse() {
|
||||
return newInstance(this[VALUES].slice()).invertSelf()
|
||||
}
|
||||
|
||||
invertSelf() {
|
||||
if (this[IS_2D]) {
|
||||
const det = this[VALUES][A] * this[VALUES][D] - this[VALUES][B] * this[VALUES][C]
|
||||
|
||||
// Invertable
|
||||
if (det !== 0) {
|
||||
const newA = this[VALUES][D] / det
|
||||
const newB = -this[VALUES][B] / det
|
||||
const newC = -this[VALUES][C] / det
|
||||
const newD = this[VALUES][A] / det
|
||||
const newE = (this[VALUES][C] * this[VALUES][F] - this[VALUES][D] * this[VALUES][E]) / det
|
||||
const newF = (this[VALUES][B] * this[VALUES][E] - this[VALUES][A] * this[VALUES][F]) / det
|
||||
|
||||
this.a = newA
|
||||
this.b = newB
|
||||
this.c = newC
|
||||
this.d = newD
|
||||
this.e = newE
|
||||
this.f = newF
|
||||
|
||||
return this
|
||||
}
|
||||
|
||||
// Not invertable
|
||||
else {
|
||||
this[IS_2D] = false
|
||||
|
||||
this[VALUES] = [NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN]
|
||||
|
||||
return this
|
||||
}
|
||||
} else {
|
||||
throw new Error('3D matrix inversion is not implemented.')
|
||||
}
|
||||
}
|
||||
|
||||
setMatrixValue(transformList) {
|
||||
const temp = new DOMMatrix(transformList)
|
||||
|
||||
this[VALUES] = temp[VALUES]
|
||||
this[IS_2D] = temp[IS_2D]
|
||||
|
||||
return this
|
||||
}
|
||||
|
||||
transformPoint(point) {
|
||||
const x = point.x || 0
|
||||
const y = point.y || 0
|
||||
const z = point.z || 0
|
||||
const w = point.w || 1
|
||||
|
||||
const values = this[VALUES]
|
||||
|
||||
const nx = values[M11] * x + values[M21] * y + values[M31] * z + values[M41] * w
|
||||
const ny = values[M12] * x + values[M22] * y + values[M32] * z + values[M42] * w
|
||||
const nz = values[M13] * x + values[M23] * y + values[M33] * z + values[M43] * w
|
||||
const nw = values[M14] * x + values[M24] * y + values[M34] * z + values[M44] * w
|
||||
|
||||
return new DOMPoint(nx, ny, nz, nw)
|
||||
}
|
||||
|
||||
toFloat32Array() {
|
||||
return Float32Array.from(this[VALUES])
|
||||
}
|
||||
|
||||
toFloat64Array() {
|
||||
return this[VALUES].slice(0)
|
||||
}
|
||||
|
||||
toJSON() {
|
||||
return {
|
||||
a: this.a,
|
||||
b: this.b,
|
||||
c: this.c,
|
||||
d: this.d,
|
||||
e: this.e,
|
||||
f: this.f,
|
||||
m11: this.m11,
|
||||
m12: this.m12,
|
||||
m13: this.m13,
|
||||
m14: this.m14,
|
||||
m21: this.m21,
|
||||
m22: this.m22,
|
||||
m23: this.m23,
|
||||
m24: this.m24,
|
||||
m31: this.m31,
|
||||
m32: this.m32,
|
||||
m33: this.m33,
|
||||
m34: this.m34,
|
||||
m41: this.m41,
|
||||
m42: this.m42,
|
||||
m43: this.m43,
|
||||
m44: this.m44,
|
||||
is2D: this.is2D,
|
||||
isIdentity: this.isIdentity,
|
||||
}
|
||||
}
|
||||
|
||||
toString() {
|
||||
if (this.is2D) {
|
||||
return `matrix(${this.a}, ${this.b}, ${this.c}, ${this.d}, ${this.e}, ${this.f})`
|
||||
} else {
|
||||
return `matrix3d(${this[VALUES].join(', ')})`
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const propertyName of [
|
||||
'a',
|
||||
'b',
|
||||
'c',
|
||||
'd',
|
||||
'e',
|
||||
'f',
|
||||
'm11',
|
||||
'm12',
|
||||
'm13',
|
||||
'm14',
|
||||
'm21',
|
||||
'm22',
|
||||
'm23',
|
||||
'm24',
|
||||
'm31',
|
||||
'm32',
|
||||
'm33',
|
||||
'm34',
|
||||
'm41',
|
||||
'm42',
|
||||
'm43',
|
||||
'm44',
|
||||
'is2D',
|
||||
'isIdentity',
|
||||
]) {
|
||||
const propertyDescriptor = Object.getOwnPropertyDescriptor(DOMMatrix.prototype, propertyName)
|
||||
propertyDescriptor.enumerable = true
|
||||
Object.defineProperty(DOMMatrix.prototype, propertyName, propertyDescriptor)
|
||||
}
|
||||
|
||||
module.exports = { DOMPoint, DOMMatrix, DOMRect }
|
||||
+1097
File diff suppressed because it is too large
Load Diff
+196
@@ -0,0 +1,196 @@
|
||||
const { platform, homedir } = require('os')
|
||||
const { join } = require('path')
|
||||
|
||||
const {
|
||||
clearAllCache,
|
||||
CanvasRenderingContext2D,
|
||||
CanvasElement,
|
||||
SVGCanvas,
|
||||
Path: Path2D,
|
||||
ImageData,
|
||||
Image,
|
||||
FontKey,
|
||||
GlobalFonts,
|
||||
PathOp,
|
||||
FillType,
|
||||
StrokeJoin,
|
||||
StrokeCap,
|
||||
convertSVGTextToPath,
|
||||
PdfDocument,
|
||||
GifEncoder,
|
||||
GifDisposal,
|
||||
LottieAnimation,
|
||||
} = require('./js-binding')
|
||||
|
||||
const { DOMPoint, DOMMatrix, DOMRect } = require('./geometry')
|
||||
|
||||
const loadImage = require('./load-image')
|
||||
|
||||
// Add Symbol.dispose support for GifEncoder (ECMAScript 2024 Explicit Resource Management)
|
||||
if (GifEncoder && typeof Symbol.dispose !== 'undefined') {
|
||||
GifEncoder.prototype[Symbol.dispose] = function () {
|
||||
this.dispose()
|
||||
}
|
||||
}
|
||||
|
||||
const SvgExportFlag = {
|
||||
ConvertTextToPaths: 0x01,
|
||||
NoPrettyXML: 0x02,
|
||||
RelativePathEncoding: 0x04,
|
||||
}
|
||||
|
||||
if (!('families' in GlobalFonts)) {
|
||||
Object.defineProperty(GlobalFonts, 'families', {
|
||||
get: function () {
|
||||
return JSON.parse(GlobalFonts.getFamilies().toString())
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
if (!('has' in GlobalFonts)) {
|
||||
Object.defineProperty(GlobalFonts, 'has', {
|
||||
value: function has(name) {
|
||||
return !!JSON.parse(GlobalFonts.getFamilies().toString()).find(({ family }) => family === name)
|
||||
},
|
||||
configurable: false,
|
||||
enumerable: false,
|
||||
writable: false,
|
||||
})
|
||||
}
|
||||
|
||||
const _toBlob = CanvasElement.prototype.toBlob
|
||||
const _convertToBlob = CanvasElement.prototype.convertToBlob
|
||||
if ('Blob' in globalThis) {
|
||||
CanvasElement.prototype.toBlob = function toBlob(callback, mimeType, quality) {
|
||||
_toBlob.call(
|
||||
this,
|
||||
function (/** @type {Uint8Array} */ imageBuffer) {
|
||||
const blob = new Blob([imageBuffer.buffer], { type: mimeType })
|
||||
callback(blob)
|
||||
},
|
||||
mimeType,
|
||||
quality,
|
||||
)
|
||||
}
|
||||
CanvasElement.prototype.convertToBlob = function convertToBlob(options) {
|
||||
return _convertToBlob.call(this, options).then((/** @type {Uint8Array} */ imageBuffer) => {
|
||||
const blob = new Blob([imageBuffer.buffer], { type: options?.mime || 'image/png' })
|
||||
return blob
|
||||
})
|
||||
}
|
||||
} else {
|
||||
// oxlint-disable-next-line no-unused-vars
|
||||
CanvasElement.prototype.toBlob = function toBlob(callback, mimeType, quality) {
|
||||
callback(null)
|
||||
}
|
||||
// oxlint-disable-next-line no-unused-vars
|
||||
CanvasElement.prototype.convertToBlob = function convertToBlob(options) {
|
||||
return Promise.reject(new Error('Blob is not supported in this environment'))
|
||||
}
|
||||
}
|
||||
|
||||
const _getTransform = CanvasRenderingContext2D.prototype.getTransform
|
||||
|
||||
CanvasRenderingContext2D.prototype.getTransform = function getTransform() {
|
||||
const transform = _getTransform.apply(this, arguments)
|
||||
// monkey patched, skip
|
||||
if (transform instanceof DOMMatrix) {
|
||||
return transform
|
||||
}
|
||||
const { a, b, c, d, e, f } = transform
|
||||
return new DOMMatrix([a, b, c, d, e, f])
|
||||
}
|
||||
|
||||
// Workaround for webpack bundling issue with drawImage
|
||||
// Store the original drawImage method
|
||||
const _drawImage = CanvasRenderingContext2D.prototype.drawImage
|
||||
|
||||
// Override drawImage to ensure proper type recognition in bundled environments
|
||||
CanvasRenderingContext2D.prototype.drawImage = function drawImage(image, ...args) {
|
||||
// If the image is a Canvas-like object but not recognized due to bundling,
|
||||
// we need to ensure it's properly identified
|
||||
if (image && typeof image === 'object') {
|
||||
// First check if it's a wrapped canvas object
|
||||
if (image.canvas instanceof CanvasElement || image.canvas instanceof SVGCanvas) {
|
||||
image = image.canvas
|
||||
} else if (image._canvas instanceof CanvasElement || image._canvas instanceof SVGCanvas) {
|
||||
image = image._canvas
|
||||
}
|
||||
// Then check if it's a Canvas-like object by checking for getContext method
|
||||
else if (typeof image.getContext === 'function' && image.width && image.height) {
|
||||
// If it has canvas properties but isn't recognized as CanvasElement or SVGCanvas,
|
||||
// try to correct the prototype chain
|
||||
if (!(image instanceof CanvasElement) && !(image instanceof SVGCanvas)) {
|
||||
// Try to create a proper CanvasElement from the canvas-like object
|
||||
// This helps when webpack has transformed the prototype chain
|
||||
Object.setPrototypeOf(image, CanvasElement.prototype)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Call the original drawImage with the potentially corrected image
|
||||
return _drawImage.apply(this, [image, ...args])
|
||||
}
|
||||
|
||||
function createCanvas(width, height, flag) {
|
||||
const isSvgBackend = typeof flag !== 'undefined'
|
||||
return isSvgBackend ? new SVGCanvas(width, height, flag) : new CanvasElement(width, height)
|
||||
}
|
||||
|
||||
class Canvas {
|
||||
constructor(width, height, flag) {
|
||||
return createCanvas(width, height, flag)
|
||||
}
|
||||
|
||||
static [Symbol.hasInstance](instance) {
|
||||
return instance instanceof CanvasElement || instance instanceof SVGCanvas
|
||||
}
|
||||
}
|
||||
|
||||
if (!process.env.DISABLE_SYSTEM_FONTS_LOAD) {
|
||||
GlobalFonts.loadSystemFonts()
|
||||
const platformName = platform()
|
||||
const homedirPath = homedir()
|
||||
switch (platformName) {
|
||||
case 'win32':
|
||||
GlobalFonts.loadFontsFromDir(join(homedirPath, 'AppData', 'Local', 'Microsoft', 'Windows', 'Fonts'))
|
||||
break
|
||||
case 'darwin':
|
||||
GlobalFonts.loadFontsFromDir(join(homedirPath, 'Library', 'Fonts'))
|
||||
break
|
||||
case 'linux':
|
||||
GlobalFonts.loadFontsFromDir(join('usr', 'local', 'share', 'fonts'))
|
||||
GlobalFonts.loadFontsFromDir(join(homedirPath, '.fonts'))
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
clearAllCache,
|
||||
Canvas,
|
||||
createCanvas,
|
||||
Path2D,
|
||||
ImageData,
|
||||
Image,
|
||||
PathOp,
|
||||
FillType,
|
||||
StrokeCap,
|
||||
StrokeJoin,
|
||||
SvgExportFlag,
|
||||
GlobalFonts: GlobalFonts,
|
||||
convertSVGTextToPath,
|
||||
DOMPoint,
|
||||
DOMMatrix,
|
||||
DOMRect,
|
||||
loadImage,
|
||||
FontKey,
|
||||
// Export these for better webpack compatibility
|
||||
CanvasElement,
|
||||
SVGCanvas,
|
||||
PDFDocument: PdfDocument,
|
||||
// GIF encoding
|
||||
GifEncoder,
|
||||
GifDisposal,
|
||||
// Lottie animation
|
||||
LottieAnimation,
|
||||
}
|
||||
Generated
Vendored
+464
@@ -0,0 +1,464 @@
|
||||
// prettier-ignore
|
||||
/* eslint-disable */
|
||||
// @ts-nocheck
|
||||
/* auto-generated by NAPI-RS */
|
||||
|
||||
const { readFileSync } = require('fs')
|
||||
let nativeBinding = null
|
||||
const loadErrors = []
|
||||
|
||||
const isMusl = () => {
|
||||
let musl = false
|
||||
if (process.platform === 'linux') {
|
||||
musl = isMuslFromFilesystem()
|
||||
if (musl === null) {
|
||||
musl = isMuslFromReport()
|
||||
}
|
||||
if (musl === null) {
|
||||
musl = isMuslFromChildProcess()
|
||||
}
|
||||
}
|
||||
return musl
|
||||
}
|
||||
|
||||
const isFileMusl = (f) => f.includes('libc.musl-') || f.includes('ld-musl-')
|
||||
|
||||
const isMuslFromFilesystem = () => {
|
||||
try {
|
||||
return readFileSync('/usr/bin/ldd', 'utf-8').includes('musl')
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
const isMuslFromReport = () => {
|
||||
let report = null
|
||||
if (typeof process.report?.getReport === 'function') {
|
||||
process.report.excludeNetwork = true
|
||||
report = process.report.getReport()
|
||||
}
|
||||
if (!report) {
|
||||
return null
|
||||
}
|
||||
if (report.header && report.header.glibcVersionRuntime) {
|
||||
return false
|
||||
}
|
||||
if (Array.isArray(report.sharedObjects)) {
|
||||
if (report.sharedObjects.some(isFileMusl)) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
const isMuslFromChildProcess = () => {
|
||||
try {
|
||||
return require('child_process').execSync('ldd --version', { encoding: 'utf8' }).includes('musl')
|
||||
} catch (e) {
|
||||
// If we reach this case, we don't know if the system is musl or not, so is better to just fallback to false
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
function requireNative() {
|
||||
if (process.env.NAPI_RS_NATIVE_LIBRARY_PATH) {
|
||||
try {
|
||||
return require(process.env.NAPI_RS_NATIVE_LIBRARY_PATH)
|
||||
} catch (err) {
|
||||
loadErrors.push(err)
|
||||
}
|
||||
} else if (process.platform === 'android') {
|
||||
if (process.arch === 'arm64') {
|
||||
try {
|
||||
return require('./skia.android-arm64.node')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
try {
|
||||
return require('@napi-rs/canvas-android-arm64')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
} else if (process.arch === 'arm') {
|
||||
try {
|
||||
return require('./skia.android-arm-eabi.node')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
try {
|
||||
return require('@napi-rs/canvas-android-arm-eabi')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
} else {
|
||||
loadErrors.push(new Error(`Unsupported architecture on Android ${process.arch}`))
|
||||
}
|
||||
} else if (process.platform === 'win32') {
|
||||
if (process.arch === 'x64') {
|
||||
if (
|
||||
process.config?.variables?.shlib_suffix === 'dll.a' ||
|
||||
process.config?.variables?.node_target_type === 'shared_library'
|
||||
) {
|
||||
try {
|
||||
return require('./skia.win32-x64-gnu.node')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
try {
|
||||
return require('@napi-rs/canvas-win32-x64-gnu')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
return require('./skia.win32-x64-msvc.node')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
try {
|
||||
return require('@napi-rs/canvas-win32-x64-msvc')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
}
|
||||
} else if (process.arch === 'ia32') {
|
||||
try {
|
||||
return require('./skia.win32-ia32-msvc.node')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
try {
|
||||
return require('@napi-rs/canvas-win32-ia32-msvc')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
} else if (process.arch === 'arm64') {
|
||||
try {
|
||||
return require('./skia.win32-arm64-msvc.node')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
try {
|
||||
return require('@napi-rs/canvas-win32-arm64-msvc')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
} else {
|
||||
loadErrors.push(new Error(`Unsupported architecture on Windows: ${process.arch}`))
|
||||
}
|
||||
} else if (process.platform === 'darwin') {
|
||||
try {
|
||||
return require('./skia.darwin-universal.node')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
try {
|
||||
return require('@napi-rs/canvas-darwin-universal')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
if (process.arch === 'x64') {
|
||||
try {
|
||||
return require('./skia.darwin-x64.node')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
try {
|
||||
return require('@napi-rs/canvas-darwin-x64')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
} else if (process.arch === 'arm64') {
|
||||
try {
|
||||
return require('./skia.darwin-arm64.node')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
try {
|
||||
return require('@napi-rs/canvas-darwin-arm64')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
} else {
|
||||
loadErrors.push(new Error(`Unsupported architecture on macOS: ${process.arch}`))
|
||||
}
|
||||
} else if (process.platform === 'freebsd') {
|
||||
if (process.arch === 'x64') {
|
||||
try {
|
||||
return require('./skia.freebsd-x64.node')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
try {
|
||||
return require('@napi-rs/canvas-freebsd-x64')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
} else if (process.arch === 'arm64') {
|
||||
try {
|
||||
return require('./skia.freebsd-arm64.node')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
try {
|
||||
return require('@napi-rs/canvas-freebsd-arm64')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
} else {
|
||||
loadErrors.push(new Error(`Unsupported architecture on FreeBSD: ${process.arch}`))
|
||||
}
|
||||
} else if (process.platform === 'linux') {
|
||||
if (process.arch === 'x64') {
|
||||
if (isMusl()) {
|
||||
try {
|
||||
return require('./skia.linux-x64-musl.node')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
try {
|
||||
return require('@napi-rs/canvas-linux-x64-musl')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
return require('./skia.linux-x64-gnu.node')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
try {
|
||||
return require('@napi-rs/canvas-linux-x64-gnu')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
}
|
||||
} else if (process.arch === 'arm64') {
|
||||
if (isMusl()) {
|
||||
try {
|
||||
return require('./skia.linux-arm64-musl.node')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
try {
|
||||
return require('@napi-rs/canvas-linux-arm64-musl')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
return require('./skia.linux-arm64-gnu.node')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
try {
|
||||
return require('@napi-rs/canvas-linux-arm64-gnu')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
}
|
||||
} else if (process.arch === 'arm') {
|
||||
if (isMusl()) {
|
||||
try {
|
||||
return require('./skia.linux-arm-musleabihf.node')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
try {
|
||||
return require('@napi-rs/canvas-linux-arm-musleabihf')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
return require('./skia.linux-arm-gnueabihf.node')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
try {
|
||||
return require('@napi-rs/canvas-linux-arm-gnueabihf')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
}
|
||||
} else if (process.arch === 'loong64') {
|
||||
if (isMusl()) {
|
||||
try {
|
||||
return require('./skia.linux-loong64-musl.node')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
try {
|
||||
return require('@napi-rs/canvas-linux-loong64-musl')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
return require('./skia.linux-loong64-gnu.node')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
try {
|
||||
return require('@napi-rs/canvas-linux-loong64-gnu')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
}
|
||||
} else if (process.arch === 'riscv64') {
|
||||
if (isMusl()) {
|
||||
try {
|
||||
return require('./skia.linux-riscv64-musl.node')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
try {
|
||||
return require('@napi-rs/canvas-linux-riscv64-musl')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
return require('./skia.linux-riscv64-gnu.node')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
try {
|
||||
return require('@napi-rs/canvas-linux-riscv64-gnu')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
}
|
||||
} else if (process.arch === 'ppc64') {
|
||||
try {
|
||||
return require('./skia.linux-ppc64-gnu.node')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
try {
|
||||
return require('@napi-rs/canvas-linux-ppc64-gnu')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
} else if (process.arch === 's390x') {
|
||||
try {
|
||||
return require('./skia.linux-s390x-gnu.node')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
try {
|
||||
return require('@napi-rs/canvas-linux-s390x-gnu')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
} else {
|
||||
loadErrors.push(new Error(`Unsupported architecture on Linux: ${process.arch}`))
|
||||
}
|
||||
} else if (process.platform === 'openharmony') {
|
||||
if (process.arch === 'arm64') {
|
||||
try {
|
||||
return require('./skia.openharmony-arm64.node')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
try {
|
||||
return require('@napi-rs/canvas-openharmony-arm64')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
} else if (process.arch === 'x64') {
|
||||
try {
|
||||
return require('./skia.openharmony-x64.node')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
try {
|
||||
return require('@napi-rs/canvas-openharmony-x64')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
} else if (process.arch === 'arm') {
|
||||
try {
|
||||
return require('./skia.openharmony-arm.node')
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
try {
|
||||
const binding = require('@napi-rs/canvas-openharmony-arm')
|
||||
return binding
|
||||
} catch (e) {
|
||||
loadErrors.push(e)
|
||||
}
|
||||
} else {
|
||||
loadErrors.push(new Error(`Unsupported architecture on OpenHarmony: ${process.arch}`))
|
||||
}
|
||||
} else {
|
||||
loadErrors.push(new Error(`Unsupported OS: ${process.platform}, architecture: ${process.arch}`))
|
||||
}
|
||||
}
|
||||
|
||||
nativeBinding = requireNative()
|
||||
|
||||
if (!nativeBinding || process.env.NAPI_RS_FORCE_WASI) {
|
||||
let wasiBinding = null
|
||||
let wasiBindingError = null
|
||||
try {
|
||||
wasiBinding = require('./skia.wasi.cjs')
|
||||
nativeBinding = wasiBinding
|
||||
} catch (err) {
|
||||
if (process.env.NAPI_RS_FORCE_WASI) {
|
||||
wasiBindingError = err
|
||||
}
|
||||
}
|
||||
if (!nativeBinding) {
|
||||
try {
|
||||
wasiBinding = require('@napi-rs/canvas-wasm32-wasi')
|
||||
nativeBinding = wasiBinding
|
||||
} catch (err) {
|
||||
if (process.env.NAPI_RS_FORCE_WASI) {
|
||||
wasiBindingError.cause = err
|
||||
loadErrors.push(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!nativeBinding) {
|
||||
if (loadErrors.length > 0) {
|
||||
throw new Error(
|
||||
`Cannot find native binding. ` +
|
||||
`npm has a bug related to optional dependencies (https://github.com/npm/cli/issues/4828). ` +
|
||||
'Please try `npm i` again after removing both package-lock.json and node_modules directory.',
|
||||
{
|
||||
cause: loadErrors.reduce((err, cur) => {
|
||||
cur.cause = err
|
||||
return cur
|
||||
}),
|
||||
},
|
||||
)
|
||||
}
|
||||
throw new Error(`Failed to load native binding`)
|
||||
}
|
||||
|
||||
module.exports = nativeBinding
|
||||
module.exports.GlobalFonts = nativeBinding.GlobalFonts
|
||||
module.exports.CanvasElement = nativeBinding.CanvasElement
|
||||
module.exports.CanvasGradient = nativeBinding.CanvasGradient
|
||||
module.exports.CanvasPattern = nativeBinding.CanvasPattern
|
||||
module.exports.CanvasRenderingContext2D = nativeBinding.CanvasRenderingContext2D
|
||||
module.exports.FontKey = nativeBinding.FontKey
|
||||
module.exports.Image = nativeBinding.Image
|
||||
module.exports.ImageData = nativeBinding.ImageData
|
||||
module.exports.Path = nativeBinding.Path
|
||||
module.exports.PdfDocument = nativeBinding.PdfDocument
|
||||
module.exports.SVGCanvas = nativeBinding.SVGCanvas
|
||||
module.exports.ChromaSubsampling = nativeBinding.ChromaSubsampling
|
||||
module.exports.clearAllCache = nativeBinding.clearAllCache
|
||||
module.exports.convertSVGTextToPath = nativeBinding.convertSVGTextToPath
|
||||
module.exports.FillType = nativeBinding.FillType
|
||||
module.exports.PathOp = nativeBinding.PathOp
|
||||
module.exports.StrokeCap = nativeBinding.StrokeCap
|
||||
module.exports.StrokeJoin = nativeBinding.StrokeJoin
|
||||
module.exports.SvgExportFlag = nativeBinding.SvgExportFlag
|
||||
module.exports.GifEncoder = nativeBinding.GifEncoder
|
||||
module.exports.GifDisposal = nativeBinding.GifDisposal
|
||||
Generated
Vendored
+156
@@ -0,0 +1,156 @@
|
||||
const fs = require('fs')
|
||||
const { Readable } = require('stream')
|
||||
const { URL } = require('url')
|
||||
|
||||
const { Image } = require('./js-binding')
|
||||
|
||||
let http, https
|
||||
|
||||
const MAX_REDIRECTS = 20
|
||||
const REDIRECT_STATUSES = new Set([301, 302])
|
||||
|
||||
/**
|
||||
* Loads the given source into canvas Image
|
||||
* @param {string|URL|Image|Buffer} source The image source to be loaded
|
||||
* @param {object} options Options passed to the loader
|
||||
*/
|
||||
module.exports = async function loadImage(source, options = {}) {
|
||||
// use the same buffer without copying if the source is a buffer
|
||||
if (Buffer.isBuffer(source) || source instanceof Uint8Array) return createImage(source, options.alt)
|
||||
// load readable stream as image
|
||||
if (source instanceof Readable) return createImage(await consumeStream(source), options.alt)
|
||||
// construct a Uint8Array if the source is ArrayBuffer or SharedArrayBuffer
|
||||
if (source instanceof ArrayBuffer || source instanceof SharedArrayBuffer)
|
||||
return createImage(new Uint8Array(source), options.alt)
|
||||
// construct a buffer if the source is buffer-like
|
||||
if (isBufferLike(source)) return createImage(Buffer.from(source), options.alt)
|
||||
// if the source is Image instance, copy the image src to new image
|
||||
if (source instanceof Image) return createImage(source.src, options.alt)
|
||||
// if source is string and in data uri format, construct image using data uri
|
||||
if (typeof source === 'string' && source.trimStart().startsWith('data:')) {
|
||||
const commaIdx = source.indexOf(',')
|
||||
const encoding = source.lastIndexOf('base64', commaIdx) < 0 ? 'utf-8' : 'base64'
|
||||
const data = Buffer.from(source.slice(commaIdx + 1), encoding)
|
||||
// Empty payload would silently complete on Image (HTML spec) and the loadImage
|
||||
// promise would never settle; reject upfront instead.
|
||||
// See https://github.com/Brooooooklyn/canvas/issues/1255
|
||||
if (data.length === 0) throw new Error(`Invalid data URI: empty payload in ${source.slice(0, 64)}`)
|
||||
return createImage(data, options.alt)
|
||||
}
|
||||
// if source is a string or URL instance
|
||||
if (typeof source === 'string') {
|
||||
// if the source exists as a file, construct image from that file
|
||||
if (!source.startsWith('http') && !source.startsWith('https') && (await exists(source))) {
|
||||
return createImage(source, options.alt)
|
||||
} else {
|
||||
// the source is a remote url here
|
||||
source = new URL(source)
|
||||
// attempt to download the remote source and construct image
|
||||
const data = await new Promise((resolve, reject) =>
|
||||
makeRequest(
|
||||
source,
|
||||
resolve,
|
||||
reject,
|
||||
typeof options.maxRedirects === 'number' && options.maxRedirects >= 0 ? options.maxRedirects : MAX_REDIRECTS,
|
||||
options.requestOptions,
|
||||
),
|
||||
)
|
||||
return createImage(data, options.alt)
|
||||
}
|
||||
}
|
||||
|
||||
if (source instanceof URL) {
|
||||
if (source.protocol === 'file:') {
|
||||
// remove the leading slash on windows
|
||||
return createImage(process.platform === 'win32' ? source.pathname.substring(1) : source.pathname, options.alt)
|
||||
} else {
|
||||
const data = await new Promise((resolve, reject) =>
|
||||
makeRequest(
|
||||
source,
|
||||
resolve,
|
||||
reject,
|
||||
typeof options.maxRedirects === 'number' && options.maxRedirects >= 0 ? options.maxRedirects : MAX_REDIRECTS,
|
||||
options.requestOptions,
|
||||
),
|
||||
)
|
||||
return createImage(data, options.alt)
|
||||
}
|
||||
}
|
||||
|
||||
// throw error as don't support that source
|
||||
throw new TypeError('unsupported image source')
|
||||
}
|
||||
|
||||
function makeRequest(url, resolve, reject, redirectCount, requestOptions) {
|
||||
const isHttps = url.protocol === 'https:'
|
||||
// lazy load the lib
|
||||
const lib = isHttps ? (!https ? (https = require('https')) : https) : !http ? (http = require('http')) : http
|
||||
|
||||
lib
|
||||
.get(url.toString(), requestOptions || {}, (res) => {
|
||||
try {
|
||||
const shouldRedirect = REDIRECT_STATUSES.has(res.statusCode) && typeof res.headers.location === 'string'
|
||||
if (shouldRedirect && redirectCount > 0)
|
||||
return makeRequest(
|
||||
new URL(res.headers.location, url.origin),
|
||||
resolve,
|
||||
reject,
|
||||
redirectCount - 1,
|
||||
requestOptions,
|
||||
)
|
||||
if (typeof res.statusCode === 'number' && (res.statusCode < 200 || res.statusCode >= 300)) {
|
||||
return reject(new Error(`remote source rejected with status code ${res.statusCode}`))
|
||||
}
|
||||
|
||||
consumeStream(res).then(resolve, reject)
|
||||
} catch (err) {
|
||||
reject(err)
|
||||
}
|
||||
})
|
||||
.on('error', reject)
|
||||
}
|
||||
|
||||
// use stream/consumers in the future?
|
||||
function consumeStream(res) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const chunks = []
|
||||
|
||||
res.on('data', (chunk) => chunks.push(chunk))
|
||||
res.on('end', () => resolve(Buffer.concat(chunks)))
|
||||
res.on('error', reject)
|
||||
})
|
||||
}
|
||||
|
||||
async function createImage(src, alt) {
|
||||
// Empty Buffer / Uint8Array: Image follows the HTML spec (silent completion,
|
||||
// no events) so the promise below would hang. Reject upfront.
|
||||
// See https://github.com/Brooooooklyn/canvas/issues/1255
|
||||
if ((Buffer.isBuffer(src) || src instanceof Uint8Array) && src.length === 0) {
|
||||
throw new Error('loadImage: empty image data')
|
||||
}
|
||||
|
||||
const image = new Image()
|
||||
if (typeof alt === 'string') image.alt = alt
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
image.onload = () => {
|
||||
// Wait for bitmap decode before resolving
|
||||
image.decode().then(() => resolve(image), reject)
|
||||
}
|
||||
image.onerror = (e) => reject(e)
|
||||
image.src = src
|
||||
})
|
||||
}
|
||||
|
||||
function isBufferLike(src) {
|
||||
return (src && src.type === 'Buffer') || Array.isArray(src)
|
||||
}
|
||||
|
||||
async function exists(path) {
|
||||
try {
|
||||
await fs.promises.access(path, fs.constants.F_OK)
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
Generated
Vendored
+216
@@ -0,0 +1,216 @@
|
||||
/**
|
||||
* node-canvas compatibility layer for @napi-rs/canvas.
|
||||
*
|
||||
* Provides a drop-in replacement API matching the `canvas` (node-canvas) npm package.
|
||||
* Quality values for JPEG/WebP use the node-canvas 0-1 scale and are automatically
|
||||
* converted to @napi-rs/canvas's 0-100 scale internally.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* // Drop-in replacement: change this import
|
||||
* // import { createCanvas, registerFont, loadImage } from 'canvas'
|
||||
* // to this:
|
||||
* import { createCanvas, registerFont, loadImage } from '@napi-rs/canvas/node-canvas'
|
||||
* ```
|
||||
*/
|
||||
|
||||
import { Readable } from 'node:stream'
|
||||
|
||||
// Re-export types from @napi-rs/canvas that are API-compatible
|
||||
import {
|
||||
Image as NapiImage,
|
||||
ImageData as NapiImageData,
|
||||
Path2D as NapiPath2D,
|
||||
DOMPoint as NapiDOMPoint,
|
||||
DOMMatrix as NapiDOMMatrix,
|
||||
DOMRect as NapiDOMRect,
|
||||
SKRSContext2D,
|
||||
Canvas as NapiCanvas,
|
||||
SvgCanvas,
|
||||
SvgExportFlag,
|
||||
IGlobalFonts,
|
||||
PDFDocument,
|
||||
} from './index'
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Config interfaces (node-canvas conventions)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export interface PngConfig {
|
||||
/** ZLIB compression level (0-9). Accepted for compatibility; Skia uses its own encoder. */
|
||||
compressionLevel?: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
|
||||
/** PNG filter flags. Accepted for compatibility; Skia uses its own encoder. */
|
||||
filters?: number
|
||||
/** Palette for indexed PNGs. Not supported by Skia backend. */
|
||||
palette?: Uint8ClampedArray
|
||||
/** Background color index for indexed PNGs. Not supported by Skia backend. */
|
||||
backgroundIndex?: number
|
||||
/** Pixels per inch. Accepted for compatibility. */
|
||||
resolution?: number
|
||||
}
|
||||
|
||||
export interface JpegConfig {
|
||||
/** Quality between 0 and 1. Defaults to 0.75. Converted to 0-100 for Skia. */
|
||||
quality?: number
|
||||
/** Progressive encoding. Accepted for compatibility; not supported by Skia backend. */
|
||||
progressive?: boolean
|
||||
/** 2x2 chroma subsampling. Accepted for compatibility; not supported by Skia backend. */
|
||||
chromaSubsampling?: boolean
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Canvas class (with node-canvas compatible methods)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export interface Canvas extends Omit<NapiCanvas, 'toBuffer' | 'toDataURL'> {
|
||||
/**
|
||||
* Encode the canvas as a PNG and return a Node.js Readable stream.
|
||||
* @param config PNG encoding options (accepted for compatibility)
|
||||
*/
|
||||
createPNGStream(config?: PngConfig): PNGStream
|
||||
|
||||
/**
|
||||
* Encode the canvas as a JPEG and return a Node.js Readable stream.
|
||||
* @param config JPEG encoding options. Quality is 0-1 (default 0.75).
|
||||
*/
|
||||
createJPEGStream(config?: JpegConfig): JPEGStream
|
||||
|
||||
// --- toBuffer overloads (node-canvas conventions) ---
|
||||
|
||||
/** Encode as PNG (default). */
|
||||
toBuffer(): Buffer
|
||||
toBuffer(mimeType: 'image/png', config?: PngConfig): Buffer
|
||||
/** Encode as JPEG. Quality in config is 0-1 (default 0.75). */
|
||||
toBuffer(mimeType: 'image/jpeg', config?: JpegConfig): Buffer
|
||||
/** Get raw unencoded pixel data. */
|
||||
toBuffer(mimeType: 'raw'): Buffer
|
||||
|
||||
/** Async: encode as PNG (default) via callback. */
|
||||
toBuffer(cb: (err: Error | null, result: Buffer) => void): void
|
||||
toBuffer(cb: (err: Error | null, result: Buffer) => void, mimeType: 'image/png', config?: PngConfig): void
|
||||
/** Async: encode as JPEG via callback. Quality in config is 0-1 (default 0.75). */
|
||||
toBuffer(cb: (err: Error | null, result: Buffer) => void, mimeType: 'image/jpeg', config?: JpegConfig): void
|
||||
|
||||
// --- toDataURL overloads (node-canvas conventions) ---
|
||||
|
||||
/** Encode as PNG data URL (default). */
|
||||
toDataURL(): string
|
||||
toDataURL(mimeType: 'image/png'): string
|
||||
/** Encode as JPEG data URL. Quality is 0-1. */
|
||||
toDataURL(mimeType: 'image/jpeg', quality?: number): string
|
||||
/** Async: encode as data URL via callback. */
|
||||
toDataURL(cb: (err: Error | null, result: string) => void): void
|
||||
toDataURL(mimeType: 'image/png', cb: (err: Error | null, result: string) => void): void
|
||||
toDataURL(mimeType: 'image/jpeg', cb: (err: Error | null, result: string) => void): void
|
||||
toDataURL(mimeType: 'image/jpeg', quality: number, cb: (err: Error | null, result: string) => void): void
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Stream classes
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** Readable stream that emits PNG-encoded data. */
|
||||
export class PNGStream extends Readable {}
|
||||
|
||||
/** Readable stream that emits JPEG-encoded data. */
|
||||
export class JPEGStream extends Readable {}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Factory functions
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Create a new canvas with node-canvas compatible API.
|
||||
* Canvas instances created through this function have `createPNGStream()`,
|
||||
* `createJPEGStream()`, and node-canvas compatible `toBuffer()` overloads.
|
||||
*
|
||||
* When `type` is `'svg'`, returns a `SvgCanvas` which produces vector output
|
||||
* via `getContent()` instead of raster encoding methods.
|
||||
*
|
||||
* @param width Canvas width in pixels
|
||||
* @param height Canvas height in pixels
|
||||
* @param type Canvas type: 'image' (default) or 'svg'
|
||||
*/
|
||||
export function createCanvas(width: number, height: number, type: 'svg'): SvgCanvas
|
||||
export function createCanvas(width: number, height: number, type?: 'image'): Canvas
|
||||
|
||||
/**
|
||||
* Create an ImageData instance.
|
||||
* @param data Pixel data array
|
||||
* @param width Width in pixels
|
||||
* @param height Height in pixels (calculated from data length if omitted)
|
||||
*/
|
||||
export function createImageData(data: Uint8ClampedArray, width: number, height?: number): NapiImageData
|
||||
export function createImageData(width: number, height: number): NapiImageData
|
||||
|
||||
/**
|
||||
* Load an image from a file path, URL, Buffer, or other source.
|
||||
* Returns a Promise that resolves to an Image instance.
|
||||
*/
|
||||
export function loadImage(
|
||||
source: string | URL | Buffer | ArrayBufferLike | Uint8Array | NapiImage | import('stream').Readable,
|
||||
options?: { alt?: string; maxRedirects?: number; requestOptions?: import('http').RequestOptions },
|
||||
): Promise<NapiImage>
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Font registration (node-canvas convention)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Register a font file for use in canvas text rendering.
|
||||
* Compatible with node-canvas's `registerFont()`.
|
||||
*
|
||||
* Note: @napi-rs/canvas auto-detects weight and style from font file metadata
|
||||
* (matching browser behavior). The `weight` and `style` properties in fontFace
|
||||
* are accepted for API compatibility.
|
||||
*
|
||||
* @param path Absolute path to the font file (.ttf, .otf, etc.)
|
||||
* @param fontFace Font face properties matching CSS @font-face descriptors
|
||||
*/
|
||||
export function registerFont(path: string, fontFace: { family: string; weight?: string; style?: string }): void
|
||||
|
||||
/**
|
||||
* Deregister all previously registered fonts.
|
||||
* Compatible with node-canvas's `deregisterAllFonts()`.
|
||||
*/
|
||||
export function deregisterAllFonts(): void
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Re-exported classes & values
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// Canvas is exported both as a type (the compat interface above) and as a
|
||||
// value (constructor that returns compat Canvas instances at runtime).
|
||||
export declare const Canvas: {
|
||||
new (width: number, height: number): Canvas
|
||||
new (width: number, height: number, flag: SvgExportFlag): SvgCanvas
|
||||
prototype: NapiCanvas
|
||||
}
|
||||
|
||||
export { NapiImage as Image }
|
||||
export { NapiImageData as ImageData }
|
||||
export { NapiPath2D as Path2D }
|
||||
export { NapiDOMPoint as DOMPoint }
|
||||
export { NapiDOMMatrix as DOMMatrix }
|
||||
export { NapiDOMRect as DOMRect }
|
||||
|
||||
// SKRSContext2D is an interface in index.d.ts but a class value at runtime.
|
||||
// Declare as const to export the value for instanceof checks and re-export the type.
|
||||
export type CanvasRenderingContext2D = SKRSContext2D
|
||||
export declare const CanvasRenderingContext2D: { prototype: SKRSContext2D }
|
||||
/** Legacy alias for CanvasRenderingContext2D. */
|
||||
export type Context2d = SKRSContext2D
|
||||
export declare const Context2d: { prototype: SKRSContext2D }
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// @napi-rs/canvas extras (not part of node-canvas, but useful)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export { IGlobalFonts }
|
||||
export declare const GlobalFonts: IGlobalFonts & {
|
||||
/** Reload system fonts. Available at runtime but not declared in IGlobalFonts. */
|
||||
loadSystemFonts(): number
|
||||
}
|
||||
export { PDFDocument }
|
||||
export { NapiCanvas as CanvasElement }
|
||||
export { SvgCanvas as SVGCanvas }
|
||||
Generated
Vendored
+379
@@ -0,0 +1,379 @@
|
||||
'use strict'
|
||||
|
||||
const { Readable } = require('node:stream')
|
||||
|
||||
const {
|
||||
createCanvas: _createCanvas,
|
||||
Canvas,
|
||||
CanvasElement,
|
||||
SVGCanvas,
|
||||
GlobalFonts,
|
||||
Image,
|
||||
ImageData,
|
||||
Path2D,
|
||||
DOMPoint,
|
||||
DOMMatrix,
|
||||
DOMRect,
|
||||
loadImage,
|
||||
PDFDocument,
|
||||
SvgExportFlag,
|
||||
} = require('./index.js')
|
||||
|
||||
// CanvasRenderingContext2D is not re-exported by index.js, grab from native bindings
|
||||
const { CanvasRenderingContext2D } = require('./js-binding')
|
||||
|
||||
// node-canvas defaults JPEG quality to 0.75 across all paths.
|
||||
// @napi-rs/canvas native default is 0.92 (matching Blink/Chrome).
|
||||
const NODE_CANVAS_DEFAULT_QUALITY = 0.75
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Stream classes (node-canvas returns Node.js Readable streams)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
class PNGStream extends Readable {
|
||||
constructor(canvas, options) {
|
||||
super()
|
||||
this._canvas = canvas
|
||||
this._options = options || {}
|
||||
this._done = false
|
||||
}
|
||||
|
||||
_read() {
|
||||
if (this._done) return
|
||||
this._done = true
|
||||
this._canvas
|
||||
.encode('png')
|
||||
.then((buf) => {
|
||||
this.push(buf)
|
||||
this.push(null)
|
||||
})
|
||||
.catch((err) => {
|
||||
this.destroy(err)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
class JPEGStream extends Readable {
|
||||
constructor(canvas, options) {
|
||||
super()
|
||||
this._canvas = canvas
|
||||
const opts = options || {}
|
||||
// node-canvas quality: 0-1 (default 0.75), encode() expects 0-100
|
||||
this._quality = Math.round((opts.quality != null ? opts.quality : NODE_CANVAS_DEFAULT_QUALITY) * 100)
|
||||
this._done = false
|
||||
}
|
||||
|
||||
_read() {
|
||||
if (this._done) return
|
||||
this._done = true
|
||||
this._canvas
|
||||
.encode('jpeg', this._quality)
|
||||
.then((buf) => {
|
||||
this.push(buf)
|
||||
this.push(null)
|
||||
})
|
||||
.catch((err) => {
|
||||
this.destroy(err)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Quality normalization helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const MIME_FORMAT_MAP = {
|
||||
'image/png': 'png',
|
||||
'image/jpeg': 'jpeg',
|
||||
'image/webp': 'webp',
|
||||
'image/avif': 'avif',
|
||||
'image/gif': 'gif',
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract quality from a node-canvas config object or number.
|
||||
* Returns the raw 0-1 quality value, defaulting to NODE_CANVAS_DEFAULT_QUALITY
|
||||
* for JPEG/WebP when not specified.
|
||||
*
|
||||
* @param {string} mime
|
||||
* @param {number|object|undefined} configOrQuality
|
||||
* @returns {number|undefined} 0-1 scale for JPEG/WebP, undefined for other mimes
|
||||
*/
|
||||
function _extractQuality(mime, configOrQuality) {
|
||||
if (mime !== 'image/jpeg' && mime !== 'image/webp') return undefined
|
||||
if (configOrQuality == null) return NODE_CANVAS_DEFAULT_QUALITY
|
||||
if (typeof configOrQuality === 'number') return configOrQuality
|
||||
if (typeof configOrQuality === 'object' && configOrQuality.quality != null) {
|
||||
return configOrQuality.quality
|
||||
}
|
||||
return NODE_CANVAS_DEFAULT_QUALITY
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Compat methods added to each canvas instance created via this module
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// Keep references to the original prototype methods
|
||||
const _origToBuffer = CanvasElement.prototype.toBuffer
|
||||
const _origToDataURL = CanvasElement.prototype.toDataURL
|
||||
|
||||
function _compatCreatePNGStream(options) {
|
||||
return new PNGStream(this, options)
|
||||
}
|
||||
|
||||
function _compatCreateJPEGStream(options) {
|
||||
return new JPEGStream(this, options)
|
||||
}
|
||||
|
||||
/**
|
||||
* node-canvas compatible toBuffer:
|
||||
* - toBuffer() → PNG (sync)
|
||||
* - toBuffer('image/png', config?) → PNG (sync)
|
||||
* - toBuffer('image/jpeg', config?) → JPEG (sync, quality 0-1)
|
||||
* - toBuffer('raw') → raw pixel data (sync)
|
||||
* - toBuffer(callback) → PNG (async)
|
||||
* - toBuffer(callback, mime, config?) → specified format (async)
|
||||
*/
|
||||
function _compatToBuffer(mimeOrCallback, configOrQuality) {
|
||||
// Callback form: toBuffer(callback) or toBuffer(callback, mime, config)
|
||||
if (typeof mimeOrCallback === 'function') {
|
||||
const callback = mimeOrCallback
|
||||
const mime = typeof configOrQuality === 'string' ? configOrQuality : 'image/png'
|
||||
const config = arguments[2]
|
||||
|
||||
if (mime === 'raw') {
|
||||
let buf
|
||||
try {
|
||||
buf = this.data()
|
||||
} catch (err) {
|
||||
callback(err)
|
||||
return
|
||||
}
|
||||
callback(null, buf)
|
||||
return
|
||||
}
|
||||
|
||||
const format = MIME_FORMAT_MAP[mime]
|
||||
if (!format) {
|
||||
callback(new TypeError(`Unsupported MIME type "${mime}". Supported: ${Object.keys(MIME_FORMAT_MAP).join(', ')}`))
|
||||
return
|
||||
}
|
||||
const q = _extractQuality(mime, config)
|
||||
this.encode(format, q != null ? Math.round(q * 100) : undefined).then(
|
||||
(buf) => callback(null, buf),
|
||||
(err) => callback(err),
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
// Sync: no args → PNG
|
||||
if (mimeOrCallback === undefined) {
|
||||
return _origToBuffer.call(this, 'image/png')
|
||||
}
|
||||
|
||||
// Sync: raw pixel data
|
||||
if (mimeOrCallback === 'raw') {
|
||||
return this.data()
|
||||
}
|
||||
|
||||
// Sync: extract quality (0-1) and scale to 0-100 for native toBuffer
|
||||
const q = _extractQuality(mimeOrCallback, configOrQuality)
|
||||
return _origToBuffer.call(this, mimeOrCallback, q != null ? Math.round(q * 100) : undefined)
|
||||
}
|
||||
|
||||
/**
|
||||
* node-canvas compatible toDataURL:
|
||||
* - toDataURL() → PNG data URL (sync)
|
||||
* - toDataURL('image/jpeg', quality) → JPEG data URL, quality 0-1 (sync)
|
||||
* - toDataURL(callback) → PNG data URL (async)
|
||||
* - toDataURL(mime, callback) → data URL (async)
|
||||
* - toDataURL(mime, quality, callback) → data URL with quality (async)
|
||||
*/
|
||||
function _compatToDataURL(mimeOrCallback, qualityOrCallback) {
|
||||
// toDataURL(callback)
|
||||
if (typeof mimeOrCallback === 'function') {
|
||||
this.toDataURLAsync('image/png').then(
|
||||
(url) => mimeOrCallback(null, url),
|
||||
(err) => mimeOrCallback(err),
|
||||
)
|
||||
return
|
||||
}
|
||||
// toDataURL(mime, callback)
|
||||
if (typeof qualityOrCallback === 'function') {
|
||||
this.toDataURLAsync(mimeOrCallback, _extractQuality(mimeOrCallback, undefined)).then(
|
||||
(url) => qualityOrCallback(null, url),
|
||||
(err) => qualityOrCallback(err),
|
||||
)
|
||||
return
|
||||
}
|
||||
// toDataURL(mime, quality, callback)
|
||||
const cb = arguments[2]
|
||||
if (typeof cb === 'function') {
|
||||
// Native toDataURLAsync expects 0-1 (f64) — pass quality through as-is
|
||||
const quality = _extractQuality(mimeOrCallback, qualityOrCallback)
|
||||
this.toDataURLAsync(mimeOrCallback, quality).then(
|
||||
(url) => cb(null, url),
|
||||
(err) => cb(err),
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
// Sync form: native toDataURL expects 0-1 (f64) — pass quality through as-is
|
||||
const quality = _extractQuality(mimeOrCallback, qualityOrCallback)
|
||||
return _origToDataURL.call(this, mimeOrCallback, quality)
|
||||
}
|
||||
|
||||
/**
|
||||
* Attach node-canvas compatible methods to a CanvasElement instance.
|
||||
*/
|
||||
function _addCompatMethods(canvas) {
|
||||
canvas.createPNGStream = _compatCreatePNGStream
|
||||
canvas.createJPEGStream = _compatCreateJPEGStream
|
||||
canvas.toBuffer = _compatToBuffer
|
||||
canvas.toDataURL = _compatToDataURL
|
||||
return canvas
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Public API: registerFont / deregisterAllFonts
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// Track FontKeys from registerFont() so deregisterAllFonts() can remove
|
||||
// only user-registered fonts (matching node-canvas behavior which leaves
|
||||
// system fonts untouched).
|
||||
const _registeredFontKeys = []
|
||||
|
||||
/**
|
||||
* Register a font file with the specified font face properties.
|
||||
* Compatible with node-canvas's registerFont(path, { family, weight?, style? }).
|
||||
*
|
||||
* Note: @napi-rs/canvas auto-detects weight and style from font file metadata
|
||||
* (matching browser behavior). The weight and style properties in fontFace are
|
||||
* accepted for API compatibility but the actual values are read from the font.
|
||||
*
|
||||
* @param {string} path Absolute path to the font file (.ttf, .otf, etc.)
|
||||
* @param {{ family: string, weight?: string, style?: string }} fontFace
|
||||
*/
|
||||
function registerFont(path, fontFace) {
|
||||
if (!fontFace || typeof fontFace.family !== 'string') {
|
||||
throw new TypeError('registerFont requires a fontFace with a "family" property')
|
||||
}
|
||||
const key = GlobalFonts.registerFromPath(path, fontFace.family)
|
||||
if (!key) {
|
||||
throw new Error(`Failed to register font from "${path}" with family "${fontFace.family}"`)
|
||||
}
|
||||
_registeredFontKeys.push(key)
|
||||
}
|
||||
|
||||
/**
|
||||
* Deregister all fonts previously registered via registerFont().
|
||||
* Compatible with node-canvas's deregisterAllFonts() which only removes
|
||||
* user-registered fonts and leaves system fonts untouched.
|
||||
*/
|
||||
function deregisterAllFonts() {
|
||||
if (_registeredFontKeys.length > 0) {
|
||||
GlobalFonts.removeBatch(_registeredFontKeys)
|
||||
_registeredFontKeys.length = 0
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Public API: createCanvas / createImageData
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Create a new canvas instance with node-canvas compatible API.
|
||||
*
|
||||
* @param {number} width
|
||||
* @param {number} height
|
||||
* @param {'image'|'svg'} [type='image']
|
||||
* @returns {Canvas}
|
||||
*/
|
||||
function createCanvas(width, height, type) {
|
||||
if (type === 'svg') {
|
||||
// SvgExportFlag enum requires a valid variant; NoPrettyXML (0x02) is the
|
||||
// least impactful on rendering behavior (only affects XML whitespace).
|
||||
return _createCanvas(width, height, SvgExportFlag.NoPrettyXML)
|
||||
}
|
||||
if (type === 'pdf') {
|
||||
throw new Error(
|
||||
'createCanvas with type "pdf" is not supported. Use the PDFDocument class from @napi-rs/canvas directly.',
|
||||
)
|
||||
}
|
||||
if (type != null && type !== 'image') {
|
||||
throw new TypeError(`createCanvas: unknown type "${type}". Supported types: "image", "svg".`)
|
||||
}
|
||||
return _addCompatMethods(_createCanvas(width, height))
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an ImageData instance.
|
||||
* Compatible with node-canvas's createImageData().
|
||||
*
|
||||
* @param {Uint8ClampedArray|number} dataOrWidth
|
||||
* @param {number} widthOrHeight
|
||||
* @param {number} [height]
|
||||
* @returns {ImageData}
|
||||
*/
|
||||
function createImageData(dataOrWidth, widthOrHeight, height) {
|
||||
if (typeof dataOrWidth === 'number') {
|
||||
return new ImageData(dataOrWidth, widthOrHeight)
|
||||
}
|
||||
if (height != null) {
|
||||
return new ImageData(dataOrWidth, widthOrHeight, height)
|
||||
}
|
||||
return new ImageData(dataOrWidth, widthOrHeight)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Canvas constructor wrapper
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// In node-canvas, `new Canvas(w, h)` and `createCanvas(w, h)` produce
|
||||
// equivalent canvases. Wrap the native Canvas constructor so that
|
||||
// `new Canvas(w, h)` also gets compat methods, without polluting the
|
||||
// prototype (which would affect @napi-rs/canvas users who don't use
|
||||
// this compat layer).
|
||||
const CompatCanvas = new Proxy(Canvas, {
|
||||
construct(target, args) {
|
||||
const canvas = new target(...args)
|
||||
if (canvas instanceof CanvasElement) {
|
||||
return _addCompatMethods(canvas)
|
||||
}
|
||||
return canvas
|
||||
},
|
||||
})
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Exports (matches node-canvas export shape)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
module.exports = {
|
||||
// Factory functions
|
||||
Canvas: CompatCanvas,
|
||||
createCanvas,
|
||||
createImageData,
|
||||
loadImage,
|
||||
registerFont,
|
||||
deregisterAllFonts,
|
||||
|
||||
// Classes
|
||||
Image,
|
||||
ImageData,
|
||||
CanvasRenderingContext2D,
|
||||
Context2d: CanvasRenderingContext2D,
|
||||
PNGStream,
|
||||
JPEGStream,
|
||||
Path2D,
|
||||
|
||||
// Geometry
|
||||
DOMPoint,
|
||||
DOMMatrix,
|
||||
DOMRect,
|
||||
|
||||
// @napi-rs/canvas extras (available but not part of node-canvas)
|
||||
GlobalFonts,
|
||||
PDFDocument,
|
||||
CanvasElement,
|
||||
SVGCanvas,
|
||||
}
|
||||
Generated
Vendored
+176
@@ -0,0 +1,176 @@
|
||||
{
|
||||
"name": "@napi-rs/canvas",
|
||||
"version": "0.1.100",
|
||||
"description": "Canvas for Node.js with skia backend",
|
||||
"main": "index.js",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/Brooooooklyn/canvas.git"
|
||||
},
|
||||
"workspaces": [
|
||||
"e2e/*"
|
||||
],
|
||||
"license": "MIT",
|
||||
"keywords": [
|
||||
"napi-rs",
|
||||
"NAPI",
|
||||
"N-API",
|
||||
"Rust",
|
||||
"node-addon",
|
||||
"node-addon-api",
|
||||
"canvas",
|
||||
"image",
|
||||
"pdf",
|
||||
"svg",
|
||||
"skia"
|
||||
],
|
||||
"files": [
|
||||
"index.d.ts",
|
||||
"index.js",
|
||||
"geometry.js",
|
||||
"js-binding.js",
|
||||
"load-image.js",
|
||||
"node-canvas.js",
|
||||
"node-canvas.d.ts"
|
||||
],
|
||||
"napi": {
|
||||
"binaryName": "skia",
|
||||
"targets": [
|
||||
"x86_64-unknown-linux-gnu",
|
||||
"x86_64-apple-darwin",
|
||||
"x86_64-pc-windows-msvc",
|
||||
"aarch64-pc-windows-msvc",
|
||||
"armv7-unknown-linux-gnueabihf",
|
||||
"x86_64-unknown-linux-musl",
|
||||
"aarch64-unknown-linux-gnu",
|
||||
"aarch64-unknown-linux-musl",
|
||||
"aarch64-apple-darwin",
|
||||
"aarch64-linux-android",
|
||||
"riscv64-unknown-linux-gnu"
|
||||
]
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 10"
|
||||
},
|
||||
"publishConfig": {
|
||||
"registry": "https://registry.npmjs.org/",
|
||||
"access": "public"
|
||||
},
|
||||
"scripts": {
|
||||
"artifacts": "napi artifacts",
|
||||
"bench": "node --import @oxc-node/core/register benchmark/bench.ts",
|
||||
"build": "napi build --platform --release --js js-binding.js",
|
||||
"build:debug": "napi build --platform --js js-binding.js",
|
||||
"example-lottie": "yarn oxnode ./example/lottie-to-video.ts",
|
||||
"format": "run-p format:source format:rs format:toml",
|
||||
"format:rs": "cargo fmt",
|
||||
"format:source": "prettier . -w",
|
||||
"format:toml": "taplo format",
|
||||
"lint": "oxlint",
|
||||
"prepublishOnly": "pinst --disable && napi prepublish -t npm",
|
||||
"postpublish": "pinst --enable",
|
||||
"test:ci": "ava -c 1",
|
||||
"test": "ava",
|
||||
"e2e": "yarn workspace @napi-rs/canvas-e2e-webpack test",
|
||||
"version": "napi version && conventional-changelog -p angular -i CHANGELOG.md -s && git add ."
|
||||
},
|
||||
"devDependencies": {
|
||||
"@jimp/core": "^1.6.0",
|
||||
"@jimp/custom": "^0.22.12",
|
||||
"@jimp/jpeg": "^0.22.12",
|
||||
"@jimp/png": "^0.22.12",
|
||||
"@napi-rs/cli": "^3.5.0",
|
||||
"@napi-rs/webcodecs": "^1.1.1",
|
||||
"@octokit/rest": "^22.0.1",
|
||||
"@oxc-node/cli": "^0.1.0",
|
||||
"@oxc-node/core": "^0.1.0",
|
||||
"@taplo/cli": "^0.7.0",
|
||||
"@types/lodash": "^4.17.21",
|
||||
"@types/node": "^25.0.3",
|
||||
"@types/semver": "^7",
|
||||
"ava": "^7.0.0",
|
||||
"canvas": "^3.2.0",
|
||||
"canvaskit-wasm": "^0.41.0",
|
||||
"colorette": "^2.0.20",
|
||||
"conventional-changelog-cli": "^5.0.0",
|
||||
"core-js": "^3.47.0",
|
||||
"echarts": "^6.0.0",
|
||||
"electron": "^41.0.0",
|
||||
"husky": "^9.1.7",
|
||||
"lint-staged": "^16.2.7",
|
||||
"lodash": "^4.17.21",
|
||||
"npm-run-all2": "^8.0.4",
|
||||
"oxlint": "^1.34.0",
|
||||
"oxlint-tsgolint": "^0.22.0",
|
||||
"pinst": "^3.0.0",
|
||||
"png.js": "^0.2.1",
|
||||
"prettier": "^3.7.4",
|
||||
"pretty-bytes": "^7.1.0",
|
||||
"semver": "^7.7.3",
|
||||
"skia-canvas": "^3.0.8",
|
||||
"table": "^6.9.0",
|
||||
"tinybench": "^6.0.0",
|
||||
"typescript": "^6.0.0"
|
||||
},
|
||||
"lint-staged": {
|
||||
"*.@(js|ts|tsx|yml|yaml|md|json|html)": [
|
||||
"prettier --write"
|
||||
],
|
||||
"*.@(js|ts|tsx)": [
|
||||
"oxlint --fix"
|
||||
]
|
||||
},
|
||||
"ava": {
|
||||
"nodeArguments": [
|
||||
"--import=@oxc-node/core/register",
|
||||
"--import=core-js/proposals/promise-with-resolvers.js"
|
||||
],
|
||||
"extensions": {
|
||||
"ts": "module"
|
||||
},
|
||||
"files": [
|
||||
"__test__/**/*.spec.ts",
|
||||
"scripts/__test__/**/*.spec.ts"
|
||||
],
|
||||
"workerThreads": false,
|
||||
"cache": false,
|
||||
"timeout": "3m",
|
||||
"environmentVariables": {
|
||||
"SWC_NODE_PROJECT": "./tsconfig.json",
|
||||
"NODE_ENV": "ava"
|
||||
}
|
||||
},
|
||||
"prettier": {
|
||||
"printWidth": 120,
|
||||
"semi": false,
|
||||
"trailingComma": "all",
|
||||
"singleQuote": true,
|
||||
"arrowParens": "always"
|
||||
},
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/Brooooooklyn"
|
||||
},
|
||||
"packageManager": "yarn@4.14.1",
|
||||
"dependenciesMeta": {
|
||||
"canvas": {
|
||||
"built": true
|
||||
},
|
||||
"skia-canvas": {
|
||||
"built": true
|
||||
}
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"@napi-rs/canvas-linux-x64-gnu": "0.1.100",
|
||||
"@napi-rs/canvas-darwin-x64": "0.1.100",
|
||||
"@napi-rs/canvas-win32-x64-msvc": "0.1.100",
|
||||
"@napi-rs/canvas-win32-arm64-msvc": "0.1.100",
|
||||
"@napi-rs/canvas-linux-arm-gnueabihf": "0.1.100",
|
||||
"@napi-rs/canvas-linux-x64-musl": "0.1.100",
|
||||
"@napi-rs/canvas-linux-arm64-gnu": "0.1.100",
|
||||
"@napi-rs/canvas-linux-arm64-musl": "0.1.100",
|
||||
"@napi-rs/canvas-darwin-arm64": "0.1.100",
|
||||
"@napi-rs/canvas-android-arm64": "0.1.100",
|
||||
"@napi-rs/canvas-linux-riscv64-gnu": "0.1.100"
|
||||
}
|
||||
}
|
||||
Generated
Vendored
+18
@@ -0,0 +1,18 @@
|
||||
PROPRIETARY AND CONFIDENTIAL
|
||||
|
||||
Copyright © 2026 OpenAI, L.L.C.
|
||||
All rights reserved.
|
||||
|
||||
This software and any associated materials (the "Software") are proprietary and confidential information of OpenAI, L.L.C.
|
||||
|
||||
Subject to your compliance with this license, OpenAI, L.L.C. grants you a non-exclusive, non-transferable, revocable, limited license to use the Software solely for internal evaluation and testing purposes.
|
||||
|
||||
You may not, without prior written permission from OpenAI, L.L.C.:
|
||||
- Copy, modify, distribute, sublicense, sell, lease, or otherwise make the Software available to any third party
|
||||
- Use the Software for production, commercial, or benchmarking purposes
|
||||
- Reverse engineer, decompile, disassemble, or otherwise attempt to derive the source code, underlying ideas, algorithms, or models of the Software
|
||||
- Remove or obscure any proprietary notices
|
||||
|
||||
The Software is provided "AS IS", without warranty of any kind, express or implied, including but not limited to warranties of merchantability, fitness for a particular purpose, or non-infringement.
|
||||
|
||||
This license is effective until terminated. OpenAI, L.L.C. may terminate this license at any time, with or without notice. Upon termination, you must immediately cease all use of the Software and destroy all copies in your possession or control.
|
||||
Generated
Vendored
+8
File diff suppressed because one or more lines are too long
Generated
Vendored
+4
@@ -0,0 +1,4 @@
|
||||
#!/usr/bin/env node
|
||||
import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);
|
||||
import{randomUUID as T}from"node:crypto";var b=19e5;var _=2e6;var w=4e3;var v="omitted_for_size";var C="omitted_for_output_error";var S=T();var A=process;var k=A._send?.bind(process);var h=process.send?.bind(process);var y=A.reallyExit?.bind(process)??process.exit.bind(process);var J=performance.now();var P=import("@oai/artifact-tool");var l;var g=false;P.then(()=>{l=performance.now()-J;E({type:"ready",workerInstanceId:S,runtimeImportMs:l},n=>{if(n)y(1)})},n=>{p({type:"startup-error",error:{message:O(n instanceof Error?n.message:String(n))}})});process.once("message",n=>{if(!M(n)){p({type:"startup-error",error:{message:"Artifact session worker received an invalid request."}});return}void N(n.requestId,n.args)});process.on("disconnect",()=>{y(0)});function E(n,e){try{if(k){k(n,void 0,{swallowErrors:false},e);return}if(h){h(n,e);return}}catch(t){e(t instanceof Error?t:new Error(String(t)));return}e(new Error("Artifact session worker IPC is unavailable."))}function p(n){if(g)return;g=true;E(n,e=>{y(e?1:0)})}function M(n){if(!n||typeof n!=="object")return false;const e=n;return e.type==="run"&&typeof e.requestId==="string"&&!!e.args&&typeof e.args==="object"}async function N(n,e){let t=false;let o=null;try{const i=await P;const s=e.artifactType==="presentation"?i.Presentation:i.Workbook;if(!s||typeof s.run!=="function"){throw new Error(`The bundled Artifact Tool runtime does not expose ${e.artifactType==="presentation"?"Presentation":"Workbook"}.run.`)}const r=j(e.code);const c=performance.now();const u=await s.run(e.target,async f=>{const I=x(f);const m=await r(f,I,e.input,e.artifactType==="spreadsheet"?f:void 0,e.artifactType==="presentation"?f:void 0);o=V(m,b,"Artifact session callback result");t=true;return m},F({create:e.create,sessionRoot:e.sessionRoot,snapshotPath:e.snapshotPath,title:e.title,sourcePath:e.sourcePath,outputDirectory:e.outputDirectory,summary:e.summary,authorClientId:e.authorClientId}));const a=B(u.outputs);if(!a){$(o,u.outputs)}const d=L(e.artifactType,u,o,a,{target:e.target,runMs:performance.now()-c});p({type:"result",requestId:n,ok:true,value:d})}catch(i){p({type:"result",requestId:n,ok:false,outcome:t?"unknown":"not_committed",error:{message:O(i instanceof Error?i.message:String(i))}})}}function j(n){const e=Object.getPrototypeOf(async function(){}).constructor;return new e("artifact","session","input","workbook","presentation",`"use strict";
|
||||
${n}`)}function x(n){const e=n.session;const t=e?.info??{};const o={...t,info:t,viewState:e?.viewState??t.viewState};if(Array.isArray(e?.selectedElementAids)){o["selectedElementAids"]=[...e.selectedElementAids]}if(Array.isArray(e?.selectedRanges)){o["selectedRanges"]=[...e.selectedRanges]}for(const i of["inspect","resolve","help"]){const s=n[i];if(typeof s==="function"){o[i]=s.bind(n)}}return Object.freeze(o)}function F(n){return Object.fromEntries(Object.entries(n).filter(([,e])=>e!==void 0))}function L(n,e,t,o,i){const s=o?void 0:R(t,b);const r={status:o?C:v};const c={ok:true,committed:e.response!==void 0,artifactType:n,target:i.target,sessionId:e.info.sessionId,stateVersion:e.info.stateVersion,snapshotPath:e.info.snapshotPath,sourcePath:e.info.sourcePath,viewState:e.info.viewState,outputDirectory:e.info.outputDirectory,timing:{runMs:i.runMs,runtimeImportMs:l},workerInstanceId:S,workerPid:process.pid};const u=[...s===void 0?[]:[{...c,outputs:e.outputs,result:s}],{...c,outputs:e.outputs,result:r,resultOmitted:true},{...c,outputs:[],outputsOmitted:true,outputCount:e.outputs.length,result:r,resultOmitted:true}];for(const a of u){const d=R(a,_);if(d!==void 0)return d}return{ok:true,committed:e.response!==void 0,artifactType:n,sessionId:D(e.info.sessionId),stateVersion:q(e.info.stateVersion),metadataOmitted:true,outputs:[],outputsOmitted:true,outputCount:e.outputs.length,result:r,resultOmitted:true}}function D(n){if(n===void 0||n===null)return n;if(typeof n!=="string")return void 0;if(n.length<=1e3)return n;return`${n.slice(0,999)}\u2026`}function q(n){return typeof n==="number"&&Number.isFinite(n)?n:void 0}function V(n,e,t){if(n===void 0)return null;const o=JSON.stringify(n);if(o===void 0)return null;if(Buffer.byteLength(o)>e){throw new Error(`${t} exceeds the ${e}-byte limit.`)}return JSON.parse(o)}function $(n,e){try{const t=new Map;for(const s of e){const r=U(s);if(r===void 0)continue;t.set(r.path,t.has(r.path)?void 0:r)}if(t.size===0)return;const o=[n];const i=new Set;while(o.length>0){const s=o.pop();if(!s||typeof s!=="object"||i.has(s))continue;i.add(s);if(Array.isArray(s)){for(let u=0;u<s.length;u+=1){o.push(s[u])}continue}const r=s;const c=r["path"];if(typeof c==="string"){const u=t.get(c);if(u!==void 0&&W(r,u)){r["status"]="saved";delete r["message"]}}for(const u of Object.values(r)){o.push(u)}}}catch{}}function B(n){for(const e of n){if(!e||typeof e!=="object"||Array.isArray(e))continue;const t=e["status"];if(t==="error"||t==="conflict")return true}return false}function U(n){if(!n||typeof n!=="object"||Array.isArray(n)){return void 0}const e=n;if(e["kind"]!=="render"&&e["kind"]!=="export"&&e["kind"]!=="inspect"||typeof e["fileName"]!=="string"||typeof e["contentType"]!=="string"||typeof e["byteLength"]!=="number"||!Number.isFinite(e["byteLength"])||e["status"]!=="saved"||typeof e["path"]!=="string"){return void 0}return{kind:e["kind"],fileName:e["fileName"],contentType:e["contentType"],byteLength:e["byteLength"],path:e["path"]}}function W(n,e){if(n["status"]!=="pending"||typeof n["path"]!=="string"){return false}if(n["path"]!==e.path){return false}return e.kind==="inspect"?typeof n["recordCount"]==="number"&&Number.isFinite(n["recordCount"])&&n["recordCount"]>=0&&typeof n["truncated"]==="boolean"&&!!n["metadata"]&&typeof n["metadata"]==="object"&&!Array.isArray(n["metadata"]):n["fileName"]===e.fileName&&n["contentType"]===e.contentType&&n["byteLength"]===e.byteLength}function R(n,e){let t;try{t=JSON.stringify(n)}catch{return void 0}if(t===void 0||Buffer.byteLength(t)>e){return void 0}return JSON.parse(t)}function O(n){if(n.length<=w)return n;return`${n.slice(0,w-1)}\u2026`}
|
||||
Generated
Vendored
+2
File diff suppressed because one or more lines are too long
Generated
Vendored
+3000
File diff suppressed because one or more lines are too long
Generated
Vendored
+2994
File diff suppressed because one or more lines are too long
Generated
Vendored
+2993
File diff suppressed because one or more lines are too long
Generated
Vendored
+54
File diff suppressed because one or more lines are too long
Generated
Vendored
+3365
File diff suppressed because one or more lines are too long
Generated
Vendored
BIN
Binary file not shown.
Generated
Vendored
+2
File diff suppressed because one or more lines are too long
Generated
Vendored
+2
@@ -0,0 +1,2 @@
|
||||
import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);
|
||||
var s=Symbol.for("@oai/granola/presentation-jsx.element");var r=Symbol.for("@oai/granola/presentation-jsx.fragment");function o(e,t,...a){return n(e,t)}function n(e,t){if(typeof e==="function"){return e(t)}return{$$type:s,type:e,props:t}}export{r as Fragment,o as jsxDEV};
|
||||
Generated
Vendored
+2
@@ -0,0 +1,2 @@
|
||||
import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);
|
||||
var s=Symbol.for("@oai/granola/presentation-jsx.element");var r=Symbol.for("@oai/granola/presentation-jsx.fragment");function o(e,t){return n(e,t)}function a(e,t){return n(e,t)}function n(e,t){if(typeof e==="function"){return e(t)}return{$$type:s,type:e,props:t}}export{r as Fragment,o as jsx,a as jsxs};
|
||||
Generated
Vendored
+274
@@ -0,0 +1,274 @@
|
||||
# Presentation Quick Start (TypeScript)
|
||||
|
||||
## API Docs
|
||||
|
||||
API docs: `api/API_DOCS.md`
|
||||
|
||||
`Presentation` is the in-memory API object. A deck is the exported presentation
|
||||
file. A slide is one page in the deck.
|
||||
|
||||
## Imports
|
||||
|
||||
```ts
|
||||
import fs from "node:fs/promises";
|
||||
import { FileBlob, Presentation, PresentationFile } from "@oai/artifact-tool";
|
||||
```
|
||||
|
||||
## Create, Render, Export
|
||||
|
||||
This script creates an editable deck, renders each slide PNG, and exports PPTX.
|
||||
|
||||
```ts
|
||||
import fs from "node:fs/promises";
|
||||
import { Presentation, PresentationFile } from "@oai/artifact-tool";
|
||||
|
||||
async function writeBlob(path: string, blob: Blob): Promise<void> {
|
||||
await fs.writeFile(path, new Uint8Array(await blob.arrayBuffer()));
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
await fs.mkdir("output", { recursive: true });
|
||||
|
||||
const presentation = Presentation.create({
|
||||
slideSize: { width: 1280, height: 720 },
|
||||
});
|
||||
|
||||
const slide = presentation.slides.add();
|
||||
slide.background.fill = "slate-50";
|
||||
|
||||
const page = { left: 72, top: 64, width: 1136, height: 592 };
|
||||
const gutter = 28;
|
||||
const leftCol = 430;
|
||||
const rightCol = page.width - leftCol - gutter;
|
||||
|
||||
const eyebrow = slide.shapes.add({
|
||||
geometry: "textbox",
|
||||
position: { left: page.left, top: page.top, width: 280, height: 28 },
|
||||
fill: "none",
|
||||
line: { style: "solid", fill: "none", width: 0 },
|
||||
});
|
||||
eyebrow.text = "EDITABLE PRESENTATION";
|
||||
eyebrow.text.style = { fontSize: 12, bold: true, color: "slate-500" };
|
||||
|
||||
const title = slide.shapes.add({
|
||||
geometry: "textbox",
|
||||
position: {
|
||||
left: page.left,
|
||||
top: page.top + 92,
|
||||
width: leftCol,
|
||||
height: 184,
|
||||
},
|
||||
fill: "none",
|
||||
line: { style: "solid", fill: "none", width: 0 },
|
||||
});
|
||||
title.text = "Build decks with editable objects";
|
||||
title.text.style = { fontSize: 42, bold: true, color: "slate-950" };
|
||||
|
||||
const subtitle = slide.shapes.add({
|
||||
geometry: "textbox",
|
||||
position: {
|
||||
left: page.left,
|
||||
top: page.top + 292,
|
||||
width: leftCol,
|
||||
height: 96,
|
||||
},
|
||||
fill: "none",
|
||||
line: { style: "solid", fill: "none", width: 0 },
|
||||
});
|
||||
subtitle.text =
|
||||
"Rows, columns, grids, charts, tables, images, and text remain editable.";
|
||||
subtitle.text.style = { fontSize: 20, color: "slate-600" };
|
||||
|
||||
const chartFrame = slide.shapes.add({
|
||||
geometry: "roundRect",
|
||||
name: "chart-frame",
|
||||
position: {
|
||||
left: page.left + leftCol + gutter,
|
||||
top: page.top + 92,
|
||||
width: rightCol,
|
||||
height: 388,
|
||||
},
|
||||
fill: "white",
|
||||
line: { style: "solid", fill: "slate-200", width: 1 },
|
||||
borderRadius: "rounded-2xl",
|
||||
shadow: "shadow-sm",
|
||||
});
|
||||
|
||||
slide.charts.add("bar", {
|
||||
position: {
|
||||
left: chartFrame.position.left + 36,
|
||||
top: chartFrame.position.top + 52,
|
||||
width: chartFrame.position.width - 72,
|
||||
height: 280,
|
||||
},
|
||||
categories: ["Rows", "Grid", "Tokens"],
|
||||
series: [{ name: "Coverage", values: [3, 4, 5], fill: "accent1" }],
|
||||
hasLegend: false,
|
||||
dataLabels: { showValue: true, position: "outEnd" },
|
||||
yAxis: {
|
||||
majorGridlines: { style: "solid", fill: "slate-200", width: 1 },
|
||||
},
|
||||
});
|
||||
|
||||
for (const [index, slide] of presentation.slides.items.entries()) {
|
||||
const stem = `slide-${String(index + 1).padStart(2, "0")}`;
|
||||
const png = await presentation.export({ slide, format: "png", scale: 1 });
|
||||
await writeBlob(`output/${stem}.png`, png);
|
||||
}
|
||||
|
||||
const pptx = await PresentationFile.exportPptx(presentation);
|
||||
await pptx.save("output/deck.pptx");
|
||||
}
|
||||
|
||||
main().catch((error) => {
|
||||
console.error(error);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
```
|
||||
|
||||
Inspect every final slide at full size before delivery. After repairs, refresh
|
||||
the affected slide previews, including slides affected by inherited changes.
|
||||
Add the [optional inspection exports](#optional-inspection-exports) when needed.
|
||||
|
||||
## JSX Compose Equivalent
|
||||
|
||||
Use JSX when the slide is naturally rows, columns, grids, or overlays.
|
||||
|
||||
```tsx
|
||||
/** @jsxRuntime automatic */
|
||||
/** @jsxImportSource @oai/artifact-tool/presentation-jsx */
|
||||
|
||||
const frame = { left: 72, top: 64, width: 1136, height: 592 };
|
||||
|
||||
slide.compose(
|
||||
<column name="content-frame" width="fill" height="fill" gap={28}>
|
||||
<row width="fill" height={72} align="center" justify="between">
|
||||
<paragraph name="eyebrow" className="text-slate-500 text-sm font-bold">
|
||||
EDITABLE PRESENTATION
|
||||
</paragraph>
|
||||
<paragraph className="text-slate-400 text-sm">Q2 planning</paragraph>
|
||||
</row>
|
||||
<row width="fill" height="fill" gap={28} align="stretch">
|
||||
<column width={430} height="fill" gap={18}>
|
||||
<paragraph
|
||||
name="primary-heading"
|
||||
className="text-slate-950 text-5xl font-bold leading-tight"
|
||||
>
|
||||
Build decks with editable objects
|
||||
</paragraph>
|
||||
<paragraph className="text-slate-600 text-xl leading-relaxed">
|
||||
Rows, columns, grids, charts, tables, images, and text remain
|
||||
editable.
|
||||
</paragraph>
|
||||
</column>
|
||||
<box
|
||||
name="chart-frame"
|
||||
width="fill"
|
||||
height="fill"
|
||||
className="bg-white rounded-2xl shadow-sm"
|
||||
line={{ style: "solid", fill: "slate-200", width: 1 }}
|
||||
>
|
||||
<chart
|
||||
name="coverage-chart"
|
||||
chartType="bar"
|
||||
categories={["Rows", "Grid", "Tokens"]}
|
||||
series={[{ name: "Coverage", values: [3, 4, 5], fill: "accent1" }]}
|
||||
hasLegend={false}
|
||||
width="fill"
|
||||
height="fill"
|
||||
/>
|
||||
</box>
|
||||
</row>
|
||||
</column>,
|
||||
{ frame, baseUnit: 8 },
|
||||
);
|
||||
```
|
||||
|
||||
## Import And Edit PPTX
|
||||
|
||||
Load a PPTX, inspect for stable ids, render the affected slide before and after
|
||||
a focused edit, re-inspect, and export the edited PPTX.
|
||||
|
||||
```ts
|
||||
const presentation = await PresentationFile.importPptx(
|
||||
await FileBlob.load("input.pptx"),
|
||||
);
|
||||
|
||||
const before = await presentation.inspect({
|
||||
kind: "slide,textbox,shape,image,table,chart,notes,thread,layout",
|
||||
search: "Revenue",
|
||||
maxChars: 8000,
|
||||
});
|
||||
console.log(before.ndjson);
|
||||
|
||||
const slide = presentation.resolve(slideIdFromInspect);
|
||||
await writeBlob(
|
||||
"output/before-slide.png",
|
||||
await presentation.export({ slide, format: "png", scale: 1 }),
|
||||
);
|
||||
|
||||
const target = presentation.resolve(anchorIdFromInspect);
|
||||
target.text.replace("Revenue", "Updated revenue outlook");
|
||||
|
||||
await writeBlob(
|
||||
"output/after-slide.png",
|
||||
await presentation.export({ slide, format: "png", scale: 1 }),
|
||||
);
|
||||
|
||||
const after = await presentation.inspect({
|
||||
target: { id: anchorIdFromInspect, beforeLines: 2, afterLines: 2 },
|
||||
kind: "textbox,shape,image,table,chart",
|
||||
maxChars: 3000,
|
||||
});
|
||||
console.log(after.ndjson);
|
||||
|
||||
const pptx = await PresentationFile.exportPptx(presentation);
|
||||
await pptx.save("output/edited-deck.pptx");
|
||||
```
|
||||
|
||||
## Optional Inspection Exports
|
||||
|
||||
When investigating placement, export layout evidence for the affected slide
|
||||
in the authoring process. Capture it before and after a change when comparison
|
||||
is useful.
|
||||
|
||||
```ts
|
||||
const layout = await slide.export({ format: "layout" });
|
||||
await fs.writeFile("output/slide.layout.json", await layout.text());
|
||||
```
|
||||
|
||||
For deck flow or changes affecting multiple slides, add an overview montage.
|
||||
Continue to inspect individual slide PNGs at full size.
|
||||
|
||||
```ts
|
||||
const montage = await presentation.export({
|
||||
format: "webp",
|
||||
montage: true,
|
||||
});
|
||||
await writeBlob("output/deck-montage.webp", montage);
|
||||
```
|
||||
|
||||
## Local Image Bytes
|
||||
|
||||
Use byte-backed images for embedded PPTX assets.
|
||||
|
||||
```ts
|
||||
async function readImageBlob(imagePath: string): Promise<ArrayBuffer> {
|
||||
const bytes = await fs.readFile(imagePath);
|
||||
return bytes.buffer.slice(
|
||||
bytes.byteOffset,
|
||||
bytes.byteOffset + bytes.byteLength,
|
||||
);
|
||||
}
|
||||
|
||||
const imageBytes = await readImageBlob("assets/product.png");
|
||||
slide.images.add({
|
||||
blob: imageBytes,
|
||||
contentType: "image/png",
|
||||
alt: "Product screenshot",
|
||||
fit: "cover",
|
||||
position: { left: 720, top: 96, width: 420, height: 280 },
|
||||
geometry: "roundRect",
|
||||
borderRadius: "rounded-xl",
|
||||
});
|
||||
```
|
||||
Generated
Vendored
+270
@@ -0,0 +1,270 @@
|
||||
# Presentation API Docs
|
||||
|
||||
Use the presentation facades to create PowerPoint-style decks in TypeScript.
|
||||
|
||||
## Conventions (units + presets)
|
||||
|
||||
- **Pixels everywhere**: all slide geometry uses CSS pixels (`px`) at 96 DPI: `position.{left,top,width,height}`, line widths, and text `fontSize`.
|
||||
- **Default canvas for examples**: use `1280 x 720` unless the task or source deck says otherwise. A useful full-slide content frame is `{ left: 72, top: 64, width: 1136, height: 592 }`.
|
||||
- **Angles**: rotations use degrees.
|
||||
- **Preset geometry**: `geometry` uses preset shape-name strings. Use standard shape presets and `geometry: "custom"` for bespoke paths.
|
||||
- **Gradients**: stop `offset` ranges from `0` to `100000`.
|
||||
- **Config-first authoring**: pass config objects into create/add APIs and grouped setters when the API provides them.
|
||||
- **String values**: options such as geometry, fit, alignment, chart type, line style, and connector kind are strings; reference pages list exact small unions and grep targets for huge catalogs.
|
||||
- **Inline docs types**: reference pages include illustrative `type ... = { ... }` blocks. Treat them as schema-shaped authoring guidance, not imports.
|
||||
- **Authoring surfaces**: `slide.compose(...)` covers rows, columns, grids, layers, and token strings. Config-first facade APIs cover exact positions, fixed chrome, native charts/tables/images, and imported deck edits.
|
||||
|
||||
## Common Routes
|
||||
|
||||
- Rows, columns, grids, overlays, and 12-column spans: [`references/cookbook/layout.md`](./references/cookbook/layout.md).
|
||||
- JSX node props and sizing mechanics: [`references/jsx.md`](./references/jsx.md).
|
||||
- Tailwind-like visual strings: [`references/tokens.md`](./references/tokens.md).
|
||||
- Inspect, resolve, edit, preview, and re-inspect loops: [`references/cookbook/imported-deck.md`](./references/cookbook/imported-deck.md).
|
||||
|
||||
## Quick start
|
||||
|
||||
```ts
|
||||
const presentation = Presentation.create({
|
||||
slideSize: { width: 1280, height: 720 },
|
||||
});
|
||||
|
||||
const slide = presentation.slides.add();
|
||||
slide.background.fill = "slate-50";
|
||||
|
||||
const headline = slide.shapes.add({
|
||||
geometry: "textbox",
|
||||
name: "headline",
|
||||
position: { left: 72, top: 64, width: 720, height: 96 },
|
||||
fill: "none",
|
||||
line: { style: "solid", fill: "none", width: 0 },
|
||||
});
|
||||
headline.text = "Editable headline";
|
||||
headline.text.style = { fontSize: 44, bold: true, color: "slate-950" };
|
||||
|
||||
const shape = slide.shapes.add({
|
||||
geometry: "roundRect",
|
||||
name: "summary-surface",
|
||||
position: { left: 72, top: 188, width: 520, height: 300 },
|
||||
fill: "white",
|
||||
line: { style: "solid", fill: "slate-200", width: 1 },
|
||||
borderRadius: "rounded-2xl",
|
||||
});
|
||||
|
||||
const previewBlob = await presentation.export({
|
||||
slide,
|
||||
format: "png",
|
||||
scale: 2,
|
||||
});
|
||||
const deckPdfBlob = await presentation.export({ format: "pdf" });
|
||||
const slidePdfBlob = await presentation.export({ slide, format: "pdf" });
|
||||
const snapshot = await presentation.inspect({
|
||||
kind: "slide,textbox,shape",
|
||||
maxChars: 4000,
|
||||
});
|
||||
const help = presentation.help("*", {
|
||||
search: "chart axis labels",
|
||||
include: ["index", "notes"],
|
||||
maxChars: 4000,
|
||||
});
|
||||
const proto = presentation.toProto();
|
||||
```
|
||||
|
||||
Inspect every final slide PNG at full size. After repairs, refresh previews for
|
||||
the affected slides, including those affected by inherited changes.
|
||||
|
||||
## Optional Inspection Exports
|
||||
|
||||
When investigating placement, export layout evidence for the affected slide:
|
||||
|
||||
```ts
|
||||
const layoutBlob = await slide.export({ format: "layout" });
|
||||
```
|
||||
|
||||
For deck flow or changes affecting multiple slides, export an overview montage:
|
||||
|
||||
```ts
|
||||
const montageBlob = await presentation.export({
|
||||
format: "webp",
|
||||
montage: true,
|
||||
});
|
||||
```
|
||||
|
||||
Capture these before and after edits when comparison is useful. A montage
|
||||
supports deck-level review; use individual PNGs for full-size slide inspection.
|
||||
|
||||
## Load Existing Presentation Data
|
||||
|
||||
Load a PPTX from a local path:
|
||||
|
||||
```ts
|
||||
const presentation = await Presentation.load("input.pptx");
|
||||
```
|
||||
|
||||
Load serialized presentation data with `Presentation.load(proto)`:
|
||||
|
||||
```ts
|
||||
const presentation = Presentation.load(proto);
|
||||
|
||||
const before = await presentation.inspect({
|
||||
kind: "slide,textbox,shape,image,table,chart,notes,thread,layout",
|
||||
search: "Revenue",
|
||||
maxChars: 8000,
|
||||
});
|
||||
|
||||
const slide = presentation.resolve(slideAnchorIdFromInspect);
|
||||
const previewBefore = await presentation.export({
|
||||
slide,
|
||||
format: "png",
|
||||
scale: 1,
|
||||
});
|
||||
|
||||
const target = presentation.resolve(anchorIdFromInspect);
|
||||
target.text.replace("Revenue", "Revenue outlook");
|
||||
target.text.style = { fontSize: 24, color: "slate-950", bold: true };
|
||||
|
||||
const previewAfter = await presentation.export({
|
||||
slide,
|
||||
format: "png",
|
||||
scale: 1,
|
||||
});
|
||||
const after = await presentation.inspect({
|
||||
target: { id: anchorIdFromInspect, beforeLines: 2, afterLines: 2 },
|
||||
kind: "textbox,shape,image,table,chart",
|
||||
maxChars: 3000,
|
||||
});
|
||||
const nextProto = presentation.toProto();
|
||||
```
|
||||
|
||||
## Compose-first layout
|
||||
|
||||
```tsx
|
||||
/** @jsxRuntime automatic */
|
||||
|
||||
const presentation = Presentation.create();
|
||||
const slide = presentation.slides.add();
|
||||
|
||||
slide.compose(
|
||||
<column width="fill" height="fill" gap={16}>
|
||||
<paragraph
|
||||
name="headline"
|
||||
className="text-slate-950 text-3xl leading-tight"
|
||||
>
|
||||
<run textStyle={{ bold: true }}>Quarterly</run>
|
||||
<run> readiness</run>
|
||||
</paragraph>
|
||||
<rule stroke="#0f172a" width={160} weight={2} />
|
||||
</column>,
|
||||
{
|
||||
frame: { left: 48, top: 40, width: 864, height: 460 },
|
||||
baseUnit: 8,
|
||||
},
|
||||
);
|
||||
```
|
||||
|
||||
Use `name` for stable inspect and layout-export targeting. JSX materializing
|
||||
tags default `width` to `"fill"` when you omit it.
|
||||
|
||||
## Core API Sequence
|
||||
|
||||
- Create presentations with `Presentation.create({ slideSize })` to control default slide dimensions.
|
||||
- Add slides with `presentation.slides.add({ layout, layoutId })` or `presentation.slides.insert({ after, ... })`.
|
||||
- Use `slide.compose(nodeOrJsx, { frame, baseUnit })` for compose-first layouts. JSX lowers into the same compose runtime as the helper-based API.
|
||||
- Author content with config-first calls: `slide.shapes.add({ geometry, position, fill, line })`, `slide.images.add({ ... })`, `slide.tables.add({ ... })`, and `slide.charts.add(chartType, { ... })`.
|
||||
- Format whole-shape text with grouped configs such as `shape.text.style = { fontSize, bold, color, alignment }`.
|
||||
- Edit imported decks with `presentation.inspect({ kind, search, maxChars })`, `presentation.resolve(anchorId)`, and focused facade edits.
|
||||
- Export previews with `presentation.export({ slide, format, scale })`.
|
||||
- Export all slides as one PDF with `presentation.export({ format: "pdf" })`.
|
||||
- Export deck montages for overview review with `presentation.export({ format: "webp", montage: true })`.
|
||||
- Export layout JSON for placement investigations with `slide.export({ format: "layout" })`.
|
||||
- Control editor gridlines and imported guides with `presentation.view`.
|
||||
- Search API help with `presentation.help(query, { search, include, maxChars })`.
|
||||
- Run high-level edits with `presentation.scripts.run(kind, options)`; see [`references/presentation.spec.md`](./references/presentation.spec.md) for the script surface.
|
||||
|
||||
## Output Map
|
||||
|
||||
| Output | API | Result |
|
||||
| ------------------- | --------------------------------------------------------------- | ------------------------------------------------------------------ |
|
||||
| All slide previews | `presentation.render()` | PNG blobs in deck order, named `slide-1.png`, `slide-2.png`, and so on |
|
||||
| Selected previews | `presentation.render({ slide: [0, 2] })` | PNG blobs for zero-based indexes, in requested order |
|
||||
| Raster preview | `presentation.render({ slide, format: "png", scale })` | One raster blob for a `Slide` or a single zero-based index |
|
||||
| Slide PNG | `presentation.export({ slide, format: "png", scale })` | One preview image for one slide |
|
||||
| Deck PDF | `presentation.export({ format: "pdf" })` | One PDF `Blob` with one page per slide |
|
||||
| Slide PDF | `presentation.export({ slide, format: "pdf" })` | One PDF `Blob` for one slide |
|
||||
| Editable PPTX | `presentation.export({ format: "pptx" })` | Editable presentation `Blob` |
|
||||
| Deck montage | `presentation.export({ format: "webp", montage: true, scale })` | One overview image containing the deck slides |
|
||||
| Layout JSON | `slide.export({ format: "layout" })` | Structural JSON with bounds, ids, text, names, and object metadata |
|
||||
| Searchable snapshot | `presentation.inspect({ kind, search, maxChars })` | NDJSON records for locating and resolving objects |
|
||||
| Runtime handoff | `presentation.toProto()` | Serializable presentation data for host adapters |
|
||||
|
||||
## Minimal Patterns
|
||||
|
||||
Use these as the first API patterns to reach for:
|
||||
|
||||
```ts
|
||||
// Create, preview, inspect, then serialize.
|
||||
const presentation = Presentation.create({
|
||||
slideSize: { width: 1280, height: 720 },
|
||||
});
|
||||
const slide = presentation.slides.add();
|
||||
const preview = await presentation.export({ slide, format: "png", scale: 1 });
|
||||
const snapshot = await presentation.inspect({
|
||||
kind: "slide,textbox,shape,image,chart,table",
|
||||
maxChars: 4000,
|
||||
});
|
||||
const proto = presentation.toProto();
|
||||
```
|
||||
|
||||
```tsx
|
||||
// Compose structure with first-principles rows/columns.
|
||||
slide.compose(
|
||||
<row width="fill" height="fill" gap={28}>
|
||||
<column width={420} height="fill" gap={16}>
|
||||
<paragraph className="text-slate-950 text-5xl font-bold leading-tight">
|
||||
Title
|
||||
</paragraph>
|
||||
<paragraph className="text-slate-600 text-xl leading-relaxed">
|
||||
Editable copy in a fixed text column.
|
||||
</paragraph>
|
||||
</column>
|
||||
<box
|
||||
width="fill"
|
||||
height="fill"
|
||||
className="bg-slate-50 rounded-2xl shadow-sm"
|
||||
/>
|
||||
</row>,
|
||||
{ frame: { left: 56, top: 56, width: 1168, height: 608 }, baseUnit: 8 },
|
||||
);
|
||||
```
|
||||
|
||||
For 3-column and 12-column layouts, use [`references/cookbook/layout.md`](./references/cookbook/layout.md); keep spans local with `{ mode: "fr", value: 1 }` track objects.
|
||||
|
||||
Use `className` only for visual/text tokens such as `bg-*`, `rounded-*`,
|
||||
`shadow-*`, `text-*`, `font-*`, and `leading-*`. Use layout props for
|
||||
`width`, `height`, `gap`, `padding`, `align`, and `justify`.
|
||||
|
||||
## Reference Map
|
||||
|
||||
Open these references as needed:
|
||||
|
||||
- [`references/jsx.md`](./references/jsx.md) — compact JSX node surface and layout mechanics.
|
||||
- [`references/tokens.md`](./references/tokens.md) — Tailwind-like token reference for colors, text, radius, shadows, and `className`.
|
||||
- [`references/cookbook/layout.md`](./references/cookbook/layout.md) — first-principles layout recipes for rows, columns, 12-column grids, alignment, masks, and overlays.
|
||||
- [`references/cookbook/imported-deck.md`](./references/cookbook/imported-deck.md) — safe inspect, resolve, edit, preview, and re-inspect loops for existing decks.
|
||||
- [`references/presentation.spec.md`](./references/presentation.spec.md) — `Presentation` facade, slide collection, view controls, export/toProto, scripts.
|
||||
- [`references/slide.spec.md`](./references/slide.spec.md) — `Slide` API, backgrounds, placeholders, notes, export, auto-layout.
|
||||
- [`references/inspect.md`](./references/inspect.md) — grep-first snapshot (`inspect → rg → resolve/edit → re-inspect`) for loaded presentation data and templates.
|
||||
- [`references/help.md`](./references/help.md) — grep-first API and template lookup (`help → build/edit → inspect`) for presentation JS workflows.
|
||||
- [`references/layout.spec.md`](./references/layout.spec.md) — layouts, placeholders, and slide layout assignment.
|
||||
- [`references/master.spec.md`](./references/master.spec.md) — masters, layout linking, background refs, color maps.
|
||||
- [`references/theme.spec.md`](./references/theme.spec.md) — theme color schemes and hex maps.
|
||||
- [`references/styles.spec.md`](./references/styles.spec.md) — named text styles and flow through text.
|
||||
- [`references/rich-text.spec.md`](./references/rich-text.spec.md) — text blocks, ranges, links, list presets.
|
||||
- [`references/shapes.spec.md`](./references/shapes.spec.md) — shape geometry, custom Bézier curves, fills, strokes, rounded corners, shadows, and z-ordering.
|
||||
- [`references/connectors.md`](./references/connectors.md) — connected lines, arrows, side anchors, direct connection sites, and rerouting behavior.
|
||||
- [`references/fill.spec.md`](./references/fill.spec.md) — fill/stroke config shapes and color shorthands, solid, gradient, pattern.
|
||||
- [`references/images.spec.md`](./references/images.spec.md) — images, cropping, contain/cover framing, prompt placeholders.
|
||||
- [`references/tables.spec.md`](./references/tables.spec.md) — tables, merges, and cell text.
|
||||
- [`references/charts.spec.md`](./references/charts.spec.md) — charts, series, axes, legends, mini-chart YAML.
|
||||
- [`references/comments.md`](./references/comments.md) — comment authors, threads, replies, reactions, and resolving imported review threads.
|
||||
- [`references/auto-layout.spec.md`](./references/auto-layout.spec.md) — deterministic layout helpers for arranging shapes within frames.
|
||||
- [`references/speaker-notes.spec.md`](./references/speaker-notes.spec.md) — speaker notes surface and visibility toggles.
|
||||
Generated
Vendored
+100
@@ -0,0 +1,100 @@
|
||||
# Auto Layout
|
||||
|
||||
`slide.autoLayout(...)` places shapes within a frame using deterministic spacing.
|
||||
Use `slide.compose(<row>/<column>/<grid>)` for new structured JSX layouts. Use
|
||||
`slide.autoLayout(...)` when repositioning existing facade shapes, especially
|
||||
imported or generated shapes.
|
||||
|
||||
## Pattern
|
||||
|
||||
```ts
|
||||
slide.autoLayout(shapes, {
|
||||
direction,
|
||||
frame,
|
||||
align,
|
||||
horizontalGap,
|
||||
verticalGap,
|
||||
horizontalPadding,
|
||||
verticalPadding,
|
||||
});
|
||||
```
|
||||
|
||||
## Inputs
|
||||
|
||||
- `direction`: horizontal or vertical flow.
|
||||
- `frame`: `"slide"`, container `Shape`, or explicit `{ left, top, width, height }`.
|
||||
- `align`: 3x3 group alignment within the frame.
|
||||
- Gap and padding values use pixels.
|
||||
|
||||
## Inline Types
|
||||
|
||||
```ts
|
||||
type AutoLayoutOptions = {
|
||||
direction?: "horizontal" | "vertical";
|
||||
frame?:
|
||||
| "slide"
|
||||
| Shape
|
||||
| { left: number; top: number; width: number; height: number };
|
||||
align?:
|
||||
| "center"
|
||||
| "topLeft"
|
||||
| "topCenter"
|
||||
| "topRight"
|
||||
| "left"
|
||||
| "right"
|
||||
| "bottomLeft"
|
||||
| "bottomCenter"
|
||||
| "bottomRight";
|
||||
horizontalGap?: number | "auto";
|
||||
verticalGap?: number | "auto";
|
||||
horizontalPadding?: number;
|
||||
verticalPadding?: number;
|
||||
};
|
||||
```
|
||||
|
||||
## Shape Prep
|
||||
|
||||
```ts
|
||||
for (const shape of shapes) {
|
||||
shape.position = {
|
||||
width: shapeWidthPx,
|
||||
height: shapeHeightPx,
|
||||
};
|
||||
}
|
||||
|
||||
slide.autoLayout(shapes, layoutConfig);
|
||||
```
|
||||
|
||||
## Cookbook
|
||||
|
||||
```ts
|
||||
// Equal KPI row.
|
||||
const kpiShapes = metrics.map((metric) =>
|
||||
slide.shapes.add({
|
||||
geometry: "roundRect",
|
||||
position: { width: 240, height: 132 },
|
||||
fill: "white",
|
||||
line: { style: "solid", fill: "slate-200", width: 1 },
|
||||
borderRadius: "rounded-xl",
|
||||
}),
|
||||
);
|
||||
|
||||
slide.autoLayout(kpiShapes, {
|
||||
direction: "horizontal",
|
||||
frame: { left: 80, top: 160, width: 1120, height: 160 },
|
||||
horizontalGap: "auto",
|
||||
align: "center",
|
||||
});
|
||||
```
|
||||
|
||||
```ts
|
||||
// Vertical callout stack inside an existing shape frame.
|
||||
slide.autoLayout(callouts, {
|
||||
direction: "vertical",
|
||||
frame: frameShape,
|
||||
verticalGap: 14,
|
||||
horizontalPadding: 24,
|
||||
verticalPadding: 24,
|
||||
align: "topLeft",
|
||||
});
|
||||
```
|
||||
Generated
Vendored
+330
@@ -0,0 +1,330 @@
|
||||
# Charts
|
||||
|
||||
`slide.charts` creates chart elements with slide placement and chart configuration.
|
||||
|
||||
## Resolved From Inspect
|
||||
|
||||
```ts
|
||||
const chart = presentation.resolve("ch/b2c3d4e5");
|
||||
chart.title = "Updated chart title";
|
||||
chart.yAxis = { numberFormatCode: "$#,##0M" };
|
||||
chart.series.getItemAt(0).values = [3.1, 3.7, 4.2, 4.8];
|
||||
```
|
||||
|
||||
Use `presentation.inspect({ kind: "chart", search })` to find the `ch/...`
|
||||
anchor id. If an imported chart resolves as an image, preserve it as an image or
|
||||
rebuild it as a native chart intentionally.
|
||||
|
||||
## Add Chart
|
||||
|
||||
```ts
|
||||
const chart = slide.charts.add(chartType, {
|
||||
position,
|
||||
title,
|
||||
titleTextStyle,
|
||||
categories,
|
||||
series,
|
||||
hasLegend,
|
||||
legend,
|
||||
barOptions,
|
||||
lineOptions,
|
||||
areaOptions,
|
||||
pieOptions,
|
||||
doughnutOptions,
|
||||
treemapOptions,
|
||||
mapOptions,
|
||||
funnelOptions,
|
||||
boxWhiskerOptions,
|
||||
histogramOptions,
|
||||
view3d,
|
||||
scatterOptions,
|
||||
radarOptions,
|
||||
bubbleOptions,
|
||||
xAxis,
|
||||
yAxis,
|
||||
dataLabels,
|
||||
dataTable,
|
||||
chartFill,
|
||||
chartLine,
|
||||
plotAreaFill,
|
||||
plotAreaLine,
|
||||
});
|
||||
```
|
||||
|
||||
Small chart option enums are listed below.
|
||||
|
||||
## Chart Inline Types
|
||||
|
||||
```ts
|
||||
type ChartTypeName =
|
||||
| "line" | "pie" | "bar" | "doughnut" | "scatter" | "bubble" | "radar"
|
||||
| "treemap" | "sunburst" | "map" | "waterfall" | "line3D" | "pie3D"
|
||||
| "area3D" | "bar3D" | "funnel" | "histogram" | "boxWhisker" | "stock"
|
||||
| "surface3D" | "ofPie" | "surface" | "pareto" | "combo" | "area";
|
||||
|
||||
type ChartConfig = {
|
||||
position?: { left?: number; top?: number; width?: number; height?: number };
|
||||
title?: string;
|
||||
roundedCorners?: boolean | null;
|
||||
titlePlacement?: "none" | "aboveChart" | "centeredOverlay";
|
||||
titleTextStyle?: ChartTextStyleConfig;
|
||||
categories?: string[];
|
||||
series?: ChartSeriesConfig[];
|
||||
hasLegend?: boolean;
|
||||
legend?: ChartLegendConfig;
|
||||
barOptions?: { direction?: "bar" | "column"; grouping?: "clustered" | "stacked" | "percentStacked"; varyColors?: boolean; gapWidth?: number; gapDepth?: number; overlap?: number; bar3dShape?: number };
|
||||
lineOptions?: { grouping?: "standard" | "stacked" | "percentStacked"; smooth?: boolean; varyColors?: boolean };
|
||||
areaOptions?: { grouping?: "standard" | "stacked" | "percentStacked"; varyColors?: boolean };
|
||||
pieOptions?: { firstSliceAngle?: number };
|
||||
doughnutOptions?: { holeSize?: number; firstSliceAngle?: number };
|
||||
treemapOptions?: { parentLabelLayout?: "none" | "overlapping" | "banner" };
|
||||
mapOptions?: { mapArea?: "world" | "auto" | "dataOnly" | "region"; projection?: "mercator" | "auto" | "miller" | "albers"; labelLayout?: "none" | "bestFit" | "showAll"; dataLevel?: "auto" | "county" | "postalCode" | "countryOrRegion" | "stateOrProvince" | "stateCode" | "countyCode" | "countryOrRegionCode"; showUnknown?: boolean; onlyRegionsWithData?: boolean };
|
||||
funnelOptions?: { gapWidth?: number };
|
||||
boxWhiskerOptions?: { showMeanLine?: boolean; showMeanMarker?: boolean; showNonOutliers?: boolean; showOutliers?: boolean; quartileMethod?: "inclusive" | "exclusive" };
|
||||
histogramOptions?: { binWidth?: number | null; binCount?: number | null; underflow?: number | null; overflow?: number | null; intervalClosed?: number; aggregated?: boolean };
|
||||
view3d?: { rotX?: number; rotY?: number; perspective?: number; rightAngleAxes?: boolean };
|
||||
scatterOptions?: { style?: "line" | "lineWithMarkers" | "marker" | "smooth" | "smoothWithMarkers"; varyColors?: boolean };
|
||||
radarOptions?: { style?: "standard" | "marker" | "filled"; varyColors?: boolean };
|
||||
bubbleOptions?: { scale?: number | null; sizeRepresents?: "area" | "width" | null; showNegative?: boolean | null };
|
||||
xAxis?: ChartAxisConfig;
|
||||
yAxis?: ChartAxisConfig;
|
||||
dataLabels?: ChartDataLabelsConfig;
|
||||
dataTable?: ChartDataTableConfig;
|
||||
chartFill?: FillConfig;
|
||||
chartLine?: LineConfig;
|
||||
plotAreaFill?: FillConfig;
|
||||
plotAreaLine?: LineConfig;
|
||||
displayBlanksAs?: "zero" | "gap" | "span" | null;
|
||||
styleIndex?: number;
|
||||
};
|
||||
```
|
||||
|
||||
## Chart Family Options
|
||||
|
||||
```ts
|
||||
histogram.histogramOptions = { binWidth: 5 };
|
||||
histogram.histogramOptions = { binCount: 8, underflow: 0, overflow: 30 };
|
||||
histogram.histogramOptions = { binWidth: null, binCount: null };
|
||||
histogram.histogramOptions = { underflow: null, overflow: null };
|
||||
bubble.bubbleOptions = { scale: 150, sizeRepresents: "area" };
|
||||
bubble.bubbleOptions = { scale: null, sizeRepresents: null };
|
||||
bubble.bubbleOptions = { showNegative: true };
|
||||
```
|
||||
|
||||
## Grouped Edits
|
||||
|
||||
```ts
|
||||
chart.xAxis = axisConfig;
|
||||
chart.yAxis = axisConfig;
|
||||
chart.legend = legendConfig;
|
||||
chart.dataLabels = dataLabelsConfig;
|
||||
chart.dataTable = dataTableConfig;
|
||||
```
|
||||
|
||||
### Data Labels
|
||||
|
||||
```ts
|
||||
chart.dataLabels = { showValue: true, position: "outEnd" };
|
||||
chart.dataLabels = { textStyle: { fontSize: 14 } };
|
||||
chart.dataLabels.showCategoryName = true;
|
||||
|
||||
const series = chart.series.getItemAt(seriesIndex);
|
||||
series.dataLabels = { showValue: false, showSeriesName: true };
|
||||
series.dataLabels.showSeriesName = false;
|
||||
```
|
||||
|
||||
Config assignments update supplied fields and preserve omitted values. New label
|
||||
collections initialize all seven `show*` flags to `false`. A series without its
|
||||
own label collection inherits chart labels; omitted point flags inherit series
|
||||
or chart labels.
|
||||
|
||||
### Axis Placement
|
||||
|
||||
```ts
|
||||
chart.xAxis = { crossesAt: 2 }; // The value axis crosses at category 2.
|
||||
chart.yAxis = { crossesAt: 25 }; // The category axis crosses at value 25.
|
||||
chart.yAxis = { tickLabelPosition: "high" };
|
||||
```
|
||||
|
||||
## Series
|
||||
|
||||
```ts
|
||||
const chart = slide.charts.add(chartType, {
|
||||
categories,
|
||||
series: [
|
||||
{
|
||||
name: seriesName,
|
||||
categories,
|
||||
values,
|
||||
xValues,
|
||||
categoryPaths,
|
||||
fill: fillConfig,
|
||||
line: lineConfig,
|
||||
marker: markerConfig,
|
||||
points,
|
||||
dataLabels: dataLabelsConfig,
|
||||
dataLabelOverrides,
|
||||
trendlines,
|
||||
errorBars,
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
## Series Inline Type
|
||||
|
||||
```ts
|
||||
type ChartSeriesConfig = {
|
||||
name: string;
|
||||
categories?: string[];
|
||||
values?: Array<number | null>;
|
||||
xValues?: Array<number | null>;
|
||||
categoryPaths?: string[][];
|
||||
bubbleSizes?: Array<number | null>;
|
||||
bubbleSizeFormula?: string;
|
||||
bubbleSizesFormatCode?: string;
|
||||
explosion?: number;
|
||||
smooth?: boolean;
|
||||
fill?: FillConfig;
|
||||
line?: LineConfig;
|
||||
stroke?: LineConfig;
|
||||
// Scatter outline color defaults to the marker's solid fill; explicit stroke fills take precedence.
|
||||
marker?: { symbol?: "circle" | "diamond" | "dot" | "none" | "plus" | "square" | "star" | "triangle" | "x"; size?: number; fill?: FillConfig };
|
||||
points?: Array<{ idx: number; fill?: FillConfig; line?: LineConfig; stroke?: LineConfig }>;
|
||||
dataLabels?: ChartDataLabelsConfig;
|
||||
dataLabelOverrides?: Array<{ idx: number; text?: string; separator?: string; position?: string; fill?: FillConfig; line?: LineConfig; stroke?: LineConfig; showValue?: boolean; showSeriesName?: boolean; showCategoryName?: boolean; showPercent?: boolean; textStyle?: ChartTextStyleConfig }>;
|
||||
trendlines?: Array<{
|
||||
type?: "linear" | "exponential" | "logarithmic" | "polynomial" | "power" | "movingAverage";
|
||||
name?: string;
|
||||
polynomialOrder?: number;
|
||||
movingAveragePeriod?: number;
|
||||
forecastForward?: number;
|
||||
forecastBackward?: number;
|
||||
intercept?: number;
|
||||
displayEquation?: boolean;
|
||||
displayRSquared?: boolean;
|
||||
line?: LineConfig;
|
||||
label?: { text?: string; textStyle?: ChartTextStyleConfig; fill?: FillConfig; line?: LineConfig };
|
||||
}>;
|
||||
errorBars?: { type?: "standardError" | "percentage" | "standardDeviation" | "none"; value?: number; endStyle?: "cap" | "noCap"; line?: LineConfig };
|
||||
valuesFormatCode?: string;
|
||||
xValuesFormatCode?: string;
|
||||
};
|
||||
```
|
||||
|
||||
## Data Label Overrides
|
||||
|
||||
```ts
|
||||
const override = chart.series
|
||||
.getItemAt(seriesIndex)
|
||||
.dataLabelOverrides.add(dataPointIdx);
|
||||
override.text = labelText;
|
||||
override.position = labelPosition;
|
||||
override.textStyle.fontSize = fontSizePx;
|
||||
override.textStyle.fill = textFill;
|
||||
override.fill = fillConfig;
|
||||
override.stroke = lineConfig;
|
||||
```
|
||||
|
||||
## Chart Areas
|
||||
|
||||
```ts
|
||||
const chart = slide.charts.add(chartType, {
|
||||
chartFill,
|
||||
plotAreaFill,
|
||||
});
|
||||
```
|
||||
|
||||
## Axis, Legend, Label Inline Types
|
||||
|
||||
```ts
|
||||
type ChartTextStyleConfig = {
|
||||
fontSize?: number;
|
||||
fill?: FillConfig;
|
||||
bold?: boolean;
|
||||
italic?: boolean;
|
||||
underline?: string;
|
||||
alignment?: "left" | "center" | "right" | "justify";
|
||||
};
|
||||
|
||||
type ChartLegendConfig = {
|
||||
position?: "left" | "top" | "topRight" | "right" | "bottom";
|
||||
overlay?: boolean;
|
||||
fill?: FillConfig;
|
||||
line?: LineConfig;
|
||||
textStyle?: ChartTextStyleConfig;
|
||||
};
|
||||
|
||||
type ChartDataLabelsConfig = {
|
||||
visible?: boolean;
|
||||
deleted?: boolean;
|
||||
position?: "center" | "inEnd" | "outEnd" | "left" | "right" | "top" | "bottom" | "insideBase" | "bestFit" | "dataCallout";
|
||||
showValue?: boolean;
|
||||
showSeriesName?: boolean;
|
||||
showCategoryName?: boolean;
|
||||
showLegendKey?: boolean;
|
||||
showPercent?: boolean;
|
||||
showBubbleSize?: boolean;
|
||||
showLeaderLines?: boolean;
|
||||
numberFormatCode?: string;
|
||||
numberFormatSourceLinked?: boolean;
|
||||
separator?: string;
|
||||
textStyle?: ChartTextStyleConfig;
|
||||
fill?: FillConfig;
|
||||
line?: LineConfig;
|
||||
};
|
||||
|
||||
type ChartAxisConfig = {
|
||||
visible?: boolean;
|
||||
title?: string | { text?: string; textStyle?: ChartTextStyleConfig };
|
||||
numberFormatCode?: string;
|
||||
min?: number;
|
||||
max?: number;
|
||||
majorUnit?: number;
|
||||
minorUnit?: number;
|
||||
position?: "bottom" | "left" | "right" | "top";
|
||||
tickLabelPosition?: "nextTo" | "high" | "low" | "none" | string;
|
||||
labelOffsetPercent?: number; // Category-axis font-size percentage; 0–1000, default 100.
|
||||
textStyle?: ChartTextStyleConfig;
|
||||
line?: LineConfig;
|
||||
majorGridlines?: LineConfig | null;
|
||||
minorGridlines?: LineConfig | null;
|
||||
};
|
||||
```
|
||||
|
||||
## Cookbook
|
||||
|
||||
```ts
|
||||
// Executive horizontal bar chart.
|
||||
slide.charts.add("bar", {
|
||||
position: { left: 96, top: 160, width: 720, height: 360 },
|
||||
categories: ["Enterprise", "Mid-market", "SMB"],
|
||||
series: [{ name: "ARR", values: [42, 28, 17], fill: "#2563eb" }],
|
||||
barOptions: { direction: "bar", grouping: "clustered", gapWidth: 44 },
|
||||
hasLegend: false,
|
||||
xAxis: { visible: false, majorGridlines: null },
|
||||
yAxis: { textStyle: { fill: "#475569", fontSize: 13 }, line: { style: "solid", fill: "#e2e8f0", width: 1 } },
|
||||
dataLabels: { showValue: true, position: "outEnd", textStyle: { fill: "#0f172a", fontSize: 13, bold: true } },
|
||||
});
|
||||
```
|
||||
|
||||
```ts
|
||||
// Compact trend line with muted grid.
|
||||
slide.charts.add("line", {
|
||||
position: { left: 96, top: 150, width: 880, height: 280 },
|
||||
categories: ["Jan", "Feb", "Mar", "Apr"],
|
||||
series: [{ name: "Conversion", values: [31, 34, 37, 43], line: { style: "solid", fill: "#0f766e", width: 3 } }],
|
||||
legend: { position: "bottom", overlay: false },
|
||||
yAxis: { numberFormatCode: "0%", majorGridlines: { style: "solid", fill: "#e2e8f0", width: 1 } },
|
||||
});
|
||||
```
|
||||
|
||||
```ts
|
||||
// Doughnut chart with labels outside.
|
||||
slide.charts.add("doughnut", {
|
||||
categories: ["Product", "Sales", "Support"],
|
||||
series: [{ name: "Share", values: [52, 31, 17] }],
|
||||
dataLabels: { showPercent: true, showCategoryName: true, position: "outEnd" },
|
||||
legend: { position: "right" },
|
||||
});
|
||||
```
|
||||
Generated
Vendored
+103
@@ -0,0 +1,103 @@
|
||||
# Comments
|
||||
|
||||
Presentation comments use people, threads, replies, reactions, and thread state.
|
||||
|
||||
## Current Author
|
||||
|
||||
```ts
|
||||
presentation.comments.setSelf({
|
||||
displayName,
|
||||
initials,
|
||||
email,
|
||||
});
|
||||
```
|
||||
|
||||
## Person Inline Type
|
||||
|
||||
```ts
|
||||
type PersonConfig = {
|
||||
id?: string;
|
||||
displayName: string;
|
||||
initials?: string;
|
||||
email?: string;
|
||||
avatarUrl?: string;
|
||||
userId?: string;
|
||||
providerId?: string;
|
||||
};
|
||||
```
|
||||
|
||||
## Element Thread
|
||||
|
||||
```ts
|
||||
const thread = presentation.comments.addThread({ element }, bodyText, {
|
||||
position,
|
||||
});
|
||||
|
||||
const reply = thread.addReply(replyText);
|
||||
reply.toggleReaction(reactionText);
|
||||
thread.resolve();
|
||||
thread.reopen();
|
||||
```
|
||||
|
||||
## Thread Inline Types
|
||||
|
||||
```ts
|
||||
type CommentTarget =
|
||||
| { slide: Slide }
|
||||
| { element: Shape | ImageElement | Table | ChartElement }
|
||||
| { textRange: TextRange }
|
||||
| { textMatch: { element: Shape; query: string; occurrence?: number } };
|
||||
|
||||
type ThreadAddOptions = {
|
||||
author?: Person | PersonConfig | { id: string };
|
||||
createdAt?: string;
|
||||
position?: { x: number; y: number; unit?: "px" | "emu" };
|
||||
};
|
||||
```
|
||||
|
||||
## Slide And Text Threads
|
||||
|
||||
```ts
|
||||
presentation.comments.addThread({ slide }, bodyText, { position });
|
||||
|
||||
presentation.comments.addThread(
|
||||
{ textMatch: { element, query, occurrence } },
|
||||
bodyText,
|
||||
);
|
||||
```
|
||||
|
||||
## Cookbook
|
||||
|
||||
```ts
|
||||
// Add a review comment to exact text.
|
||||
presentation.comments.setSelf({
|
||||
displayName: "Presentation Reviewer",
|
||||
initials: "PR",
|
||||
email: "reviewer@example.com",
|
||||
});
|
||||
|
||||
const thread = presentation.comments.addThread(
|
||||
{ textMatch: { element: titleShape, query: "Q4", occurrence: 0 } },
|
||||
"Check whether this should be FY2026 Q1.",
|
||||
);
|
||||
thread.addReply("Leaving this unresolved for owner review.");
|
||||
```
|
||||
|
||||
```ts
|
||||
// Resolve an imported thread after an edit.
|
||||
const self = presentation.comments.setSelf({
|
||||
displayName: "Presentation Editor",
|
||||
initials: "PE",
|
||||
email: "editor@example.com",
|
||||
});
|
||||
|
||||
const thread = presentation.resolve(threadAnchorId);
|
||||
thread.addReply("Updated the chart title and source note.", { author: self });
|
||||
thread.resolve(self);
|
||||
|
||||
const verified = await presentation.inspect({
|
||||
kind: "thread",
|
||||
target: { id: threadAnchorId, beforeLines: 0, afterLines: 2 },
|
||||
maxChars: 2000,
|
||||
});
|
||||
```
|
||||
Generated
Vendored
+225
@@ -0,0 +1,225 @@
|
||||
# Connectors
|
||||
|
||||
`slide.shapes.connect` creates connector lines that stay attached to slide
|
||||
shapes. Use it for arrows, flow links, callouts, dependency lines, and other
|
||||
relationships between positioned shapes.
|
||||
|
||||
Use direct `geometry: "connector"` creation only when you need exact connection
|
||||
site indexes.
|
||||
|
||||
## Connect Shapes
|
||||
|
||||
```ts
|
||||
const connector = slide.shapes.connect(sourceShape, targetShape, {
|
||||
kind: "elbow",
|
||||
fromSide: "right",
|
||||
toSide: "left",
|
||||
line: { style: "solid", fill: "slate-500", width: 2 },
|
||||
head: { type: "arrow", width: "med", length: "med" },
|
||||
});
|
||||
```
|
||||
|
||||
Endpoints accept shape facades or shape ids. `fromSide` and `toSide` accept
|
||||
`"top"`, `"left"`, `"bottom"`, or `"right"` and resolve to the nearest
|
||||
connection site for that shape geometry. When you omit side and index options,
|
||||
the API chooses a connection pair from the relative shape positions.
|
||||
|
||||
`kind` defaults to `"elbow"` for `slide.shapes.connect(...)`.
|
||||
|
||||
## Connect Inline Types
|
||||
|
||||
```ts
|
||||
type ConnectorSide = "top" | "left" | "bottom" | "right";
|
||||
|
||||
type ShapeConnectOptions = {
|
||||
kind?:
|
||||
| "straight"
|
||||
| "elbow"
|
||||
| "elbow2"
|
||||
| "elbow3"
|
||||
| "elbow4"
|
||||
| "elbow5"
|
||||
| "curved";
|
||||
fromSide?: ConnectorSide;
|
||||
toSide?: ConnectorSide;
|
||||
fromIdx?: number;
|
||||
toIdx?: number;
|
||||
line?: LineConfig;
|
||||
head?: LineEndConfig;
|
||||
tail?: LineEndConfig;
|
||||
cap?: "flat" | "round" | "square";
|
||||
join?: "round" | "bevel" | "miter";
|
||||
};
|
||||
|
||||
type LineEndConfig = {
|
||||
type?: "none" | "triangle" | "stealth" | "diamond" | "oval" | "arrow";
|
||||
width?: "sm" | "med" | "lg";
|
||||
length?: "sm" | "med" | "lg";
|
||||
};
|
||||
```
|
||||
|
||||
## Anchor Choice
|
||||
|
||||
Use side anchors for readable authoring:
|
||||
|
||||
```ts
|
||||
slide.shapes.connect(sourceShape, targetShape, {
|
||||
fromSide: "bottom",
|
||||
toSide: "top",
|
||||
kind: "elbow",
|
||||
line: { style: "dashed", fill: "accent1", width: 2 },
|
||||
});
|
||||
```
|
||||
|
||||
Use explicit connection site indexes when you need an exact preset-geometry site:
|
||||
|
||||
```ts
|
||||
const fromIdx = slide.shapes.getConnectionSiteIndex(sourceShape, "right");
|
||||
const toIdx = slide.shapes.getConnectionSiteIndex(targetShape, "left");
|
||||
|
||||
slide.shapes.connect(sourceShape.id, targetShape.id, {
|
||||
fromIdx,
|
||||
toIdx,
|
||||
kind: "straight",
|
||||
line: { style: "solid", fill: "slate-700", width: 2 },
|
||||
});
|
||||
```
|
||||
|
||||
Connection site indexes are PowerPoint preset geometry connection points. Side
|
||||
anchors map to the closest useful preset site for rectangles, ellipses, and
|
||||
other shapes.
|
||||
|
||||
## Direct Connector Shape
|
||||
|
||||
```ts
|
||||
const connector = slide.shapes.add({
|
||||
geometry: "connector",
|
||||
kind: "curved",
|
||||
from: sourceShape,
|
||||
fromIdx: 3,
|
||||
to: targetShape,
|
||||
toIdx: 1,
|
||||
line: { style: "solid", fill: "accent1", width: 2 },
|
||||
tail: { type: "triangle", width: "med", length: "med" },
|
||||
});
|
||||
```
|
||||
|
||||
## Unattached Connector
|
||||
|
||||
```ts
|
||||
const arrow = slide.shapes.add({
|
||||
geometry: "connector",
|
||||
kind: "straight",
|
||||
position: { left: 40, top: 160, width: 240, height: 0 },
|
||||
line: { fill: "accent1", width: 2 },
|
||||
tail: { type: "arrow" },
|
||||
});
|
||||
```
|
||||
|
||||
## One Attached Endpoint
|
||||
|
||||
```ts
|
||||
const connector = slide.shapes.add({
|
||||
geometry: "connector",
|
||||
kind: "straight",
|
||||
from: sourceShape,
|
||||
fromIdx: slide.shapes.getConnectionSiteIndex(sourceShape, "right"),
|
||||
position: { left: 40, top: 160, width: 240, height: 0 },
|
||||
line: { fill: "accent1", width: 2 },
|
||||
tail: { type: "arrow" },
|
||||
});
|
||||
```
|
||||
|
||||
## Direct Connector Inline Type
|
||||
|
||||
```ts
|
||||
type ConnectorConfig = {
|
||||
geometry: "connector";
|
||||
from?: Shape | string;
|
||||
fromIdx?: number;
|
||||
to?: Shape | string;
|
||||
toIdx?: number;
|
||||
position?: PositionConfig;
|
||||
kind?:
|
||||
| "straight"
|
||||
| "elbow"
|
||||
| "elbow2"
|
||||
| "elbow3"
|
||||
| "elbow4"
|
||||
| "elbow5"
|
||||
| "curved";
|
||||
line?: LineConfig;
|
||||
head?: LineEndConfig;
|
||||
tail?: LineEndConfig;
|
||||
cap?: "flat" | "round" | "square";
|
||||
join?: "round" | "bevel" | "miter";
|
||||
};
|
||||
```
|
||||
|
||||
Connectors support line styling and line ends, but not `borderRadius` or
|
||||
`shadow`.
|
||||
|
||||
## Edit Existing Connectors
|
||||
|
||||
```ts
|
||||
const connector = presentation.resolve(connectorAnchorId);
|
||||
const nextFromIdx = slide.shapes.getConnectionSiteIndex(
|
||||
nextSourceShape,
|
||||
"right",
|
||||
);
|
||||
const nextToIdx = slide.shapes.getConnectionSiteIndex(nextTargetShape, "left");
|
||||
|
||||
connector.setConnectorFrom(nextSourceShape, nextFromIdx);
|
||||
connector.setConnectorTo(nextTargetShape.id, nextToIdx);
|
||||
connector.line = { style: "solid", fill: "slate-800", width: 2 };
|
||||
connector.bringToFront();
|
||||
```
|
||||
|
||||
Use `presentation.inspect({ kind: "shape", search })` to find connector anchor
|
||||
ids. Connector facades expose `connector`, `connectorLineStyle`,
|
||||
`connectorHead`, and `connectorTail` for readback.
|
||||
|
||||
## Routing And Ordering
|
||||
|
||||
New connectors are sent behind shapes by default so boxes and labels remain
|
||||
readable. Call `connector.bringToFront()` when the connector should sit above
|
||||
other elements.
|
||||
|
||||
## Cookbook
|
||||
|
||||
```ts
|
||||
// Arrow from one card to another.
|
||||
slide.shapes.connect(sourceCard, targetCard, {
|
||||
kind: "elbow",
|
||||
fromSide: "right",
|
||||
toSide: "left",
|
||||
line: { style: "solid", fill: "slate-500", width: 2 },
|
||||
head: { type: "arrow", width: "med", length: "med" },
|
||||
});
|
||||
```
|
||||
|
||||
```ts
|
||||
// Bidirectional relationship line.
|
||||
slide.shapes.connect(leftShape, rightShape, {
|
||||
kind: "straight",
|
||||
fromSide: "right",
|
||||
toSide: "left",
|
||||
line: { style: "dashed", fill: "accent2", width: 2 },
|
||||
head: { type: "arrow", width: "sm", length: "sm" },
|
||||
tail: { type: "arrow", width: "sm", length: "sm" },
|
||||
});
|
||||
```
|
||||
|
||||
```ts
|
||||
// Curved connector with explicit preset connection sites.
|
||||
slide.shapes.add({
|
||||
geometry: "connector",
|
||||
kind: "curved",
|
||||
from: sourceShape,
|
||||
fromIdx: slide.shapes.getConnectionSiteIndex(sourceShape, "bottom"),
|
||||
to: targetShape,
|
||||
toIdx: slide.shapes.getConnectionSiteIndex(targetShape, "top"),
|
||||
line: { style: "solid", fill: "accent1", width: 2 },
|
||||
tail: { type: "triangle", width: "med", length: "med" },
|
||||
});
|
||||
```
|
||||
Generated
Vendored
+187
@@ -0,0 +1,187 @@
|
||||
# Imported Deck Cookbook
|
||||
|
||||
Use these recipes when editing an existing presentation. The goal is targeted,
|
||||
type-aware edits with a preview and a small verification snapshot.
|
||||
|
||||
For imported decks, render the affected slide before and after focused edits,
|
||||
export layout JSON before and after when object placement matters, and use a
|
||||
deck montage before/after when a change may affect multiple slides.
|
||||
|
||||
## Load A PPTX
|
||||
|
||||
```ts
|
||||
const presentation = await Presentation.load("input.pptx");
|
||||
```
|
||||
|
||||
## Edit Loop
|
||||
|
||||
```ts
|
||||
const before = await presentation.inspect({
|
||||
kind: "slide,textbox,shape,image,table,chart,notes,thread,layout",
|
||||
search: "Revenue",
|
||||
maxChars: 8000,
|
||||
});
|
||||
|
||||
// Pick an exact anchor id from `before`; use inspect ids instead of slide indexes.
|
||||
const target = presentation.resolve(anchorId);
|
||||
|
||||
// slideAnchorId is the `sl/...` id from inspect for the affected slide.
|
||||
const slide = presentation.resolve(slideAnchorId);
|
||||
const previewBefore = await slide.export({ format: "png", scale: 2 });
|
||||
const layoutBefore = await slide.export({ format: "layout" });
|
||||
const montageBefore = await presentation.export({
|
||||
format: "webp",
|
||||
montage: true,
|
||||
scale: 1,
|
||||
});
|
||||
|
||||
target.text.replace("Revenue", "Revenue outlook");
|
||||
|
||||
const previewAfter = await slide.export({ format: "png", scale: 2 });
|
||||
const layoutAfter = await slide.export({ format: "layout" });
|
||||
const montageAfter = await presentation.export({
|
||||
format: "webp",
|
||||
montage: true,
|
||||
scale: 1,
|
||||
});
|
||||
|
||||
const after = await presentation.inspect({
|
||||
target: { id: anchorId, beforeLines: 2, afterLines: 2 },
|
||||
kind: "textbox,shape",
|
||||
maxChars: 2000,
|
||||
});
|
||||
```
|
||||
|
||||
## Placeholder Edit
|
||||
|
||||
```ts
|
||||
const layoutSnapshot = await presentation.inspect({
|
||||
kind: "slide,layout,textbox,shape",
|
||||
search: "Click to add title",
|
||||
maxChars: 6000,
|
||||
});
|
||||
|
||||
// slideAnchorId is the `sl/...` id from inspect for this slide.
|
||||
const slide = presentation.resolve(slideAnchorId);
|
||||
const title = slide.placeholders.getItem("title");
|
||||
title.text = "Updated executive summary";
|
||||
```
|
||||
|
||||
Edit a slide placeholder for a local content change. Edit a layout or master
|
||||
only when the intended change is global.
|
||||
Inspect records use 1-based `slide` numbers for display; `slides.getItem(index)`
|
||||
is 0-based. Prefer resolving the `sl/...` anchor from inspect.
|
||||
|
||||
## Master/Layout Blast Radius
|
||||
|
||||
```ts
|
||||
// layoutId comes from inspect/layout export metadata; use it for search and comparison.
|
||||
const affected = await presentation.inspect({
|
||||
kind: "slide,layout",
|
||||
search: layoutId,
|
||||
maxChars: 6000,
|
||||
});
|
||||
```
|
||||
|
||||
Inspect affected layouts and slides before changing a master, layout, theme
|
||||
color, or placeholder geometry. Use layout ids for comparison/search, then
|
||||
resolve affected slides through their `sl/...` ids before editing. These edits
|
||||
can update many slides.
|
||||
|
||||
## Preserve Imported Image Placement
|
||||
|
||||
```ts
|
||||
const image = presentation.resolve(imageAnchorId);
|
||||
const oldFrame = image.frame;
|
||||
const oldCrop = image.crop;
|
||||
const oldFit = image.fit;
|
||||
const oldAlt = image.alt;
|
||||
const oldPrompt = image.prompt;
|
||||
const oldGeometry = image.geometry;
|
||||
const oldBorderRadius = image.borderRadius;
|
||||
const oldRotation = image.rotation;
|
||||
const oldFlipHorizontal = image.flipHorizontal;
|
||||
const oldFlipVertical = image.flipVertical;
|
||||
const oldLockAspectRatio = image.lockAspectRatio;
|
||||
|
||||
image.replace({
|
||||
blob: replacementBytes,
|
||||
contentType: "image/png",
|
||||
alt: oldAlt ?? "Updated product screenshot",
|
||||
...(oldFit ? { fit: oldFit } : {}),
|
||||
...(oldPrompt ? { prompt: oldPrompt } : {}),
|
||||
});
|
||||
image.frame = oldFrame;
|
||||
image.crop = oldCrop;
|
||||
image.geometry = oldGeometry;
|
||||
image.borderRadius = oldBorderRadius;
|
||||
image.rotation = oldRotation;
|
||||
image.flipHorizontal = oldFlipHorizontal;
|
||||
image.flipVertical = oldFlipVertical;
|
||||
image.lockAspectRatio = oldLockAspectRatio;
|
||||
```
|
||||
|
||||
Render the slide after replacement and verify subject crop, aspect ratio,
|
||||
rounded mask, and legibility. Preserve placement-affecting properties unless the
|
||||
edit explicitly changes them. Concrete source replacements produce concrete
|
||||
images; pass `prompt` when it should remain available as regeneration metadata.
|
||||
|
||||
## Existing Table And Chart Edits
|
||||
|
||||
```ts
|
||||
const table = presentation.resolve(tableAnchorId);
|
||||
table.cells.set(1, 2, "$4.2M");
|
||||
table.getCell(1, 2).text.style = "Body Small";
|
||||
|
||||
const chart = presentation.resolve(chartAnchorId);
|
||||
chart.xAxis = { title: "Quarter" };
|
||||
chart.yAxis = { numberFormatCode: "$#,##0M" };
|
||||
chart.series.getItemAt(0).values = [3.1, 3.7, 4.2, 4.8];
|
||||
|
||||
await presentation.inspect({
|
||||
kind: "table,chart",
|
||||
target: { id: chartAnchorId, beforeLines: 3, afterLines: 3 },
|
||||
maxChars: 3000,
|
||||
});
|
||||
```
|
||||
|
||||
If an imported chart or table resolves as an image, preserve it as an image or
|
||||
rebuild it as a native chart/table intentionally.
|
||||
|
||||
## Comments And Speaker Notes
|
||||
|
||||
```ts
|
||||
const review = await presentation.inspect({
|
||||
kind: "thread,notes,slide,textbox",
|
||||
search: "TODO",
|
||||
maxChars: 8000,
|
||||
});
|
||||
|
||||
const self = presentation.comments.setSelf({
|
||||
displayName: "Presentation Editor",
|
||||
initials: "PE",
|
||||
email: "presentation@example.com",
|
||||
});
|
||||
|
||||
const thread = presentation.resolve(commentThreadAnchorId);
|
||||
thread.addReply("Addressed in this revision.", { author: self });
|
||||
thread.resolve(self);
|
||||
|
||||
const notes = presentation.resolve(notesAnchorId);
|
||||
const existing = notes.text.trim();
|
||||
notes.text = [
|
||||
existing,
|
||||
"Opening: summarize the revised revenue outlook.",
|
||||
"Call out risk on enterprise timing.",
|
||||
].filter(Boolean).join("\n");
|
||||
notes.setVisible(true);
|
||||
|
||||
const verified = await presentation.inspect({
|
||||
kind: "thread,notes",
|
||||
target: { id: slideAnchorId, beforeLines: 1, afterLines: 4 },
|
||||
maxChars: 3000,
|
||||
});
|
||||
```
|
||||
|
||||
Keep unrelated threads and speaker notes intact unless the task explicitly asks
|
||||
to clear them.
|
||||
Generated
Vendored
+419
@@ -0,0 +1,419 @@
|
||||
# Presentation Layout Cookbook
|
||||
|
||||
First-principles recipes for arranging editable presentation JSX. These are
|
||||
layout mechanics, not deck archetypes.
|
||||
|
||||
Examples start after `presentation` and `slide` exist. Prefer string sizing
|
||||
(`"fill"`, `"hug"`) and local track values over helper imports.
|
||||
|
||||
Use `1280 x 720` as the default canvas unless the task or source deck requires
|
||||
another size:
|
||||
|
||||
```ts
|
||||
const SLIDE_W = 1280;
|
||||
const SLIDE_H = 720;
|
||||
const PAGE = { left: 72, top: 64, width: 1136, height: 592 };
|
||||
```
|
||||
|
||||
## Choose The Primitive
|
||||
|
||||
| Need | Use |
|
||||
| --- | --- |
|
||||
| Horizontal flow | `row` |
|
||||
| Vertical flow | `column` |
|
||||
| Column/row spans | `grid` |
|
||||
| Overlays or background plates | `layers` |
|
||||
| Surface plus child content | `box` |
|
||||
| Fixed placement on a slide | `slide.compose(node, { frame })` or facade `position` |
|
||||
|
||||
Use `frame` for the outer composed region. Inside the region, use `row`,
|
||||
`column`, `grid`, and `layers` so content stays resizable and inspectable. Use
|
||||
`layers` plus image `geometry`/`borderRadius` for overlays, scrims, and masked
|
||||
image compositions inside a region.
|
||||
|
||||
## Sizing Vocabulary
|
||||
|
||||
```tsx
|
||||
<box width="fill" height="fill" /> // claim available space
|
||||
<box width="hug" height="hug" /> // fit its children
|
||||
<box width={320} height={180} /> // fixed pixels
|
||||
```
|
||||
|
||||
Equal siblings fill equally:
|
||||
|
||||
```tsx
|
||||
<row width="fill" height={160} gap={24} align="stretch">
|
||||
<box width="fill" height="fill" className="bg-slate-50 rounded-xl" />
|
||||
<box width="fill" height="fill" className="bg-slate-50 rounded-xl" />
|
||||
<box width="fill" height="fill" className="bg-slate-50 rounded-xl" />
|
||||
</row>
|
||||
```
|
||||
|
||||
One fixed sibling plus one flexible sibling:
|
||||
|
||||
```tsx
|
||||
<row width="fill" height="fill" gap={32} align="stretch">
|
||||
<column width={360} height="fill" gap={16}>
|
||||
<paragraph className="text-slate-950 text-4xl font-bold">Fixed rail</paragraph>
|
||||
<paragraph className="text-slate-600 text-lg">This column stays 360px wide.</paragraph>
|
||||
</column>
|
||||
<box width="fill" height="fill" className="bg-slate-100 rounded-2xl" />
|
||||
</row>
|
||||
```
|
||||
|
||||
## Padding And Gutters
|
||||
|
||||
Use object padding for asymmetric page gutters. Use numeric padding for all
|
||||
sides.
|
||||
|
||||
Use an 8px spacing scale unless matching a source deck: common gaps are `16`,
|
||||
`24`, `28`, and `32`. Common page gutters use `PAGE`; pass `baseUnit: 8` to
|
||||
`slide.compose` when examples rely on this scale.
|
||||
|
||||
```tsx
|
||||
<column
|
||||
width="fill"
|
||||
height="fill"
|
||||
padding={{ top: 64, right: 80, bottom: 56, left: 80 }}
|
||||
gap={28}
|
||||
>
|
||||
<paragraph className="text-slate-950 text-5xl font-bold">Page title</paragraph>
|
||||
<box width="fill" height="fill" className="bg-white rounded-xl" />
|
||||
</column>
|
||||
```
|
||||
|
||||
```tsx
|
||||
<box width="fill" height="hug" padding={{ x: 28, y: 18 }} className="bg-sky-50 rounded-xl">
|
||||
<paragraph className="text-sky-950 text-xl font-bold">Compact padded box</paragraph>
|
||||
</box>
|
||||
```
|
||||
|
||||
## Rows
|
||||
|
||||
`row` lays out children left to right. `justify` distributes along the
|
||||
horizontal axis. `align` controls vertical alignment.
|
||||
|
||||
```tsx
|
||||
<row width="fill" height={72} align="center" justify="between">
|
||||
<paragraph className="text-slate-950 text-2xl font-bold">Left</paragraph>
|
||||
<paragraph className="text-slate-500 text-sm">Right</paragraph>
|
||||
</row>
|
||||
```
|
||||
|
||||
Center a child:
|
||||
|
||||
```tsx
|
||||
<row width="fill" height={220} align="center" justify="center">
|
||||
<box width={360} height={120} className="bg-white rounded-xl shadow-sm" />
|
||||
</row>
|
||||
```
|
||||
|
||||
Stretch all children to the row height:
|
||||
|
||||
```tsx
|
||||
<row width="fill" height={240} gap={20} align="stretch">
|
||||
<box width="fill" height="fill" className="bg-slate-50 rounded-xl" />
|
||||
<box width="fill" height="fill" className="bg-slate-50 rounded-xl" />
|
||||
</row>
|
||||
```
|
||||
|
||||
## Columns
|
||||
|
||||
`column` lays out children top to bottom. `justify` distributes along the
|
||||
vertical axis. `align` controls horizontal alignment.
|
||||
|
||||
```tsx
|
||||
<column width="fill" height="fill" justify="between" gap={24}>
|
||||
<paragraph className="text-slate-950 text-4xl font-bold">Top block</paragraph>
|
||||
<paragraph className="text-slate-600 text-lg">Bottom block</paragraph>
|
||||
</column>
|
||||
```
|
||||
|
||||
Metadata row, content region, and closing rule:
|
||||
|
||||
```tsx
|
||||
<column width="fill" height="fill" gap={24}>
|
||||
<row width="fill" height={72} align="center" justify="between">
|
||||
<paragraph className="text-slate-500 text-sm font-bold">HEADER</paragraph>
|
||||
<paragraph className="text-slate-400 text-sm">Source</paragraph>
|
||||
</row>
|
||||
<box width="fill" height="fill" className="bg-slate-50 rounded-xl" />
|
||||
<rule stroke="slate-200" weight={1} />
|
||||
</column>
|
||||
```
|
||||
|
||||
## Three Columns
|
||||
|
||||
Use a `row` when all columns are equal or only one side is fixed.
|
||||
|
||||
```tsx
|
||||
slide.compose(
|
||||
<row name="three-column-layout" width="fill" height="fill" gap={24} align="stretch">
|
||||
<column name="column-a" width="fill" height="fill" gap={12}>
|
||||
<paragraph className="text-slate-950 text-2xl font-bold">Column A</paragraph>
|
||||
<paragraph className="text-slate-600 text-base">Editable body copy.</paragraph>
|
||||
</column>
|
||||
<column name="column-b" width="fill" height="fill" gap={12}>
|
||||
<paragraph className="text-slate-950 text-2xl font-bold">Column B</paragraph>
|
||||
<paragraph className="text-slate-600 text-base">Editable body copy.</paragraph>
|
||||
</column>
|
||||
<column name="column-c" width="fill" height="fill" gap={12}>
|
||||
<paragraph className="text-slate-950 text-2xl font-bold">Column C</paragraph>
|
||||
<paragraph className="text-slate-600 text-base">Editable body copy.</paragraph>
|
||||
</column>
|
||||
</row>,
|
||||
{ frame: PAGE, baseUnit: 8 },
|
||||
);
|
||||
```
|
||||
|
||||
Use fixed rails when the center should absorb resize:
|
||||
|
||||
```tsx
|
||||
<row width="fill" height="fill" gap={24} align="stretch">
|
||||
<box width={240} height="fill" className="bg-slate-50 rounded-xl" />
|
||||
<box width="fill" height="fill" className="bg-white rounded-xl" />
|
||||
<box width={240} height="fill" className="bg-slate-50 rounded-xl" />
|
||||
</row>
|
||||
```
|
||||
|
||||
## Twelve-Column Grid
|
||||
|
||||
Use `grid` when child spans matter. Keep `fr` and fixed track objects local and
|
||||
obvious; use the literal `"auto"` for auto tracks:
|
||||
|
||||
```tsx
|
||||
const GRID_12 = Array.from(
|
||||
{ length: 12 },
|
||||
() => ({ mode: "fr", value: 1 }) as const,
|
||||
);
|
||||
```
|
||||
|
||||
Use a 12-column grid when spans communicate structure. Spans in a row usually
|
||||
add to 12, such as `4/4/4`, `3/6/3`, or `4/8`. Put vertical content inside
|
||||
`column` children and surfaces inside `box` children. Use a simple `row` when
|
||||
every column is equal and no span semantics are needed.
|
||||
|
||||
Full-width heading plus three equal columns:
|
||||
|
||||
```tsx
|
||||
<grid
|
||||
width="fill"
|
||||
height="fill"
|
||||
columns={GRID_12}
|
||||
rows={["auto", { mode: "fr", value: 1 }]}
|
||||
columnGap={24}
|
||||
rowGap={28}
|
||||
>
|
||||
<paragraph columnSpan={12} className="text-slate-950 text-5xl font-bold">
|
||||
Full-width heading
|
||||
</paragraph>
|
||||
<box columnSpan={4} width="fill" height="fill" className="bg-slate-50 rounded-xl" />
|
||||
<box columnSpan={4} width="fill" height="fill" className="bg-slate-50 rounded-xl" />
|
||||
<box columnSpan={4} width="fill" height="fill" className="bg-slate-50 rounded-xl" />
|
||||
</grid>
|
||||
```
|
||||
|
||||
Four/eight split:
|
||||
|
||||
```tsx
|
||||
<grid width="fill" height="fill" columns={GRID_12} columnGap={28}>
|
||||
<column columnSpan={4} width="fill" height="fill" gap={16}>
|
||||
<paragraph className="text-slate-950 text-4xl font-bold">Left span</paragraph>
|
||||
<paragraph className="text-slate-600 text-lg">Uses 4 of 12 columns.</paragraph>
|
||||
</column>
|
||||
<box columnSpan={8} width="fill" height="fill" className="bg-sky-50 rounded-2xl" />
|
||||
</grid>
|
||||
```
|
||||
|
||||
Three/six/three split:
|
||||
|
||||
```tsx
|
||||
<grid width="fill" height="fill" columns={GRID_12} columnGap={20}>
|
||||
<box columnSpan={3} width="fill" height="fill" className="bg-slate-50 rounded-xl" />
|
||||
<box columnSpan={6} width="fill" height="fill" className="bg-white rounded-xl shadow-sm" />
|
||||
<box columnSpan={3} width="fill" height="fill" className="bg-slate-50 rounded-xl" />
|
||||
</grid>
|
||||
```
|
||||
|
||||
Rows plus row spans:
|
||||
|
||||
```tsx
|
||||
<grid
|
||||
width="fill"
|
||||
height="fill"
|
||||
columns={GRID_12}
|
||||
rows={["auto", { mode: "fr", value: 1 }, { mode: "fr", value: 1 }]}
|
||||
columnGap={24}
|
||||
rowGap={24}
|
||||
>
|
||||
<paragraph columnSpan={12} className="text-slate-950 text-4xl font-bold">
|
||||
Heading
|
||||
</paragraph>
|
||||
<box columnSpan={8} rowSpan={2} width="fill" height="fill" className="bg-slate-50 rounded-xl" />
|
||||
<box columnSpan={4} width="fill" height="fill" className="bg-sky-50 rounded-xl" />
|
||||
<box columnSpan={4} width="fill" height="fill" className="bg-emerald-50 rounded-xl" />
|
||||
</grid>
|
||||
```
|
||||
|
||||
Mixed fixed and flexible tracks:
|
||||
|
||||
```tsx
|
||||
<grid
|
||||
width="fill"
|
||||
height="fill"
|
||||
columns={[
|
||||
{ mode: "fixed", value: 280 },
|
||||
{ mode: "fr", value: 1 },
|
||||
{ mode: "fixed", value: 220 },
|
||||
]}
|
||||
columnGap={24}
|
||||
>
|
||||
<box width="fill" height="fill" className="bg-slate-50 rounded-xl" />
|
||||
<box width="fill" height="fill" className="bg-white rounded-xl shadow-sm" />
|
||||
<box width="fill" height="fill" className="bg-slate-50 rounded-xl" />
|
||||
</grid>
|
||||
```
|
||||
|
||||
## Grid Alignment
|
||||
|
||||
Use `alignItems` and `justifyItems` for grid child alignment. If one child
|
||||
needs different alignment, wrap it in a `row`, `column`, or `box`.
|
||||
|
||||
| Node | Main axis | Cross axis | Distribution prop | Cross-axis prop | Defaults |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| `row` | horizontal | vertical | `justify`: `start`, `center`, `end`, `between` | `align`: `start`, `center`, `end`, `stretch` | `start` / `start` |
|
||||
| `column` | vertical | horizontal | `justify`: `start`, `center`, `end`, `between` | `align`: `start`, `center`, `end`, `stretch` | `start` / `start` |
|
||||
| `grid` | tracks | cells | `justifyItems`: `start`, `center`, `end`, `stretch` | `alignItems`: `start`, `center`, `end`, `stretch` | `stretch` / `stretch` |
|
||||
| `layers` | shared frame | shared frame | `justifyItems`: `start`, `center`, `end`, `stretch` | `alignItems`: `start`, `center`, `end`, `stretch` | `stretch` / `stretch` |
|
||||
|
||||
```tsx
|
||||
<grid
|
||||
width="fill"
|
||||
height={260}
|
||||
columns={[{ mode: "fr", value: 1 }, { mode: "fr", value: 1 }]}
|
||||
rows={[{ mode: "fr", value: 1 }]}
|
||||
columnGap={24}
|
||||
alignItems="center"
|
||||
justifyItems="stretch"
|
||||
>
|
||||
<box height={120} className="bg-slate-50 rounded-xl" />
|
||||
<box height="fill" className="bg-sky-50 rounded-xl" />
|
||||
</grid>
|
||||
```
|
||||
|
||||
## Layers
|
||||
|
||||
`layers` gives every child the same parent frame. Put visual backgrounds first,
|
||||
then overlays, then editable text.
|
||||
|
||||
```tsx
|
||||
<layers width="fill" height="fill">
|
||||
<image
|
||||
blob={backgroundBytes}
|
||||
contentType="image/jpeg"
|
||||
fit="cover"
|
||||
alt="Background"
|
||||
width="fill"
|
||||
height="fill"
|
||||
/>
|
||||
<shape geometry="rect" width="fill" height="fill" fill="black/45" />
|
||||
<column width={620} height="fill" padding={64} justify="end" gap={18}>
|
||||
<paragraph className="text-white text-5xl font-bold leading-tight">
|
||||
Editable headline
|
||||
</paragraph>
|
||||
<paragraph className="text-white/80 text-xl leading-relaxed">
|
||||
Editable supporting copy.
|
||||
</paragraph>
|
||||
</column>
|
||||
</layers>
|
||||
```
|
||||
|
||||
## Image Masks
|
||||
|
||||
Use image `geometry` for real clipping. Use `crop` plus `fit="cover"` when the
|
||||
subject should fill the mask.
|
||||
|
||||
Quick reference:
|
||||
|
||||
| Need | Use |
|
||||
| --- | --- |
|
||||
| Preserve the full image | `fit="contain"` |
|
||||
| Fill the frame and allow crop | `fit="cover"` |
|
||||
| Clip to a shape | `geometry="ellipse"` or `geometry="roundRect"` |
|
||||
| Rounded rectangle mask | `borderRadius="rounded-2xl"` |
|
||||
| Manual crop | `crop={{ left, top, right, bottom }}` with normalized `0..1` insets |
|
||||
|
||||
`crop` values are fractions removed from each source-image edge and are clamped.
|
||||
Overlays do not clip images; use image `geometry` or `borderRadius` for masks.
|
||||
|
||||
```tsx
|
||||
<image
|
||||
blob={portraitBytes}
|
||||
contentType="image/jpeg"
|
||||
alt="Portrait"
|
||||
geometry="ellipse"
|
||||
fit="cover"
|
||||
crop={{ left: 0.1, top: 0, right: 0.08, bottom: 0 }}
|
||||
width={240}
|
||||
height={240}
|
||||
/>
|
||||
```
|
||||
|
||||
Rounded rectangle image:
|
||||
|
||||
```tsx
|
||||
<image
|
||||
blob={photoBytes}
|
||||
contentType="image/jpeg"
|
||||
alt="Photo"
|
||||
fit="cover"
|
||||
width="fill"
|
||||
height={320}
|
||||
borderRadius="rounded-2xl"
|
||||
/>
|
||||
```
|
||||
|
||||
## Flow Versus Absolute Placement
|
||||
|
||||
Use flow for related content:
|
||||
|
||||
```tsx
|
||||
slide.compose(
|
||||
<column width="fill" height="fill" gap={20}>
|
||||
<paragraph className="text-slate-950 text-4xl font-bold">Title</paragraph>
|
||||
<row width="fill" height="fill" gap={24} align="stretch">
|
||||
<box width="fill" className="bg-slate-50 rounded-xl" />
|
||||
<box width="fill" className="bg-slate-50 rounded-xl" />
|
||||
</row>
|
||||
</column>,
|
||||
{ frame: PAGE, baseUnit: 8 },
|
||||
);
|
||||
```
|
||||
|
||||
Use absolute positions for elements that must land at exact slide coordinates:
|
||||
|
||||
```ts
|
||||
slide.shapes.add({
|
||||
geometry: "rect",
|
||||
name: "fixed-accent-bar",
|
||||
position: { left: 0, top: 0, width: 12, height: 720 },
|
||||
fill: "accent1",
|
||||
line: { style: "solid", fill: "none", width: 0 },
|
||||
});
|
||||
```
|
||||
|
||||
## Verify Layout
|
||||
|
||||
Inspect the layout tree when spans or wrapping matter:
|
||||
|
||||
```ts
|
||||
const layout = await slide.export({ format: "layout" });
|
||||
const png = await slide.export({ format: "png", scale: 1 });
|
||||
const snapshot = await presentation.inspect({
|
||||
kind: "slide,textbox,shape,image,table,chart",
|
||||
maxChars: 8000,
|
||||
});
|
||||
```
|
||||
|
||||
Check the rendered PNG for clipping, overlap, broken image crops, and text
|
||||
that should have stayed editable.
|
||||
Generated
Vendored
+201
@@ -0,0 +1,201 @@
|
||||
# Fill And Line Configs
|
||||
|
||||
Fill configs style shapes, chart regions, table cells, slide backgrounds, lines,
|
||||
and text fills. Text outlines use `LineConfig`, so their `fill`/`color` fields
|
||||
accept the same fill forms.
|
||||
|
||||
## Fill Forms
|
||||
|
||||
```ts
|
||||
shape.fill = fillConfig;
|
||||
shape.line = lineConfig;
|
||||
```
|
||||
|
||||
Supported fill forms:
|
||||
|
||||
- Theme, hex, RGB/RGBA, Tailwind-like color, and transformed color strings.
|
||||
- `"none"` and `"transparent"`.
|
||||
- Gradient strings such as `linear(...)` and `radial(...)`.
|
||||
- `{ type: "none" }`.
|
||||
- `{ type: "solid", color, pattern }`.
|
||||
- `{ type: "gradient", gradientKind, angleDeg, stops }`.
|
||||
- `{ type: "image", imageReference, srcRect, fillRect, stretchFillRect }`.
|
||||
|
||||
## String Fill Shortcuts
|
||||
|
||||
Use string fills for compact JSX and facade setters:
|
||||
|
||||
```tsx
|
||||
<shape geometry="rect" fill="none" line={{ style: "solid", fill: "slate-300", width: 1 }} />
|
||||
<box fill="black/45" />
|
||||
<box fill="transparent" />
|
||||
<box fill="accent1+18/90" />
|
||||
<box fill="linear(135deg, #ffffff 0%, sky-100 58%, #ffffff/0 100%)" />
|
||||
<shape geometry="ellipse" fill="radial(white/80 0%, emerald-200/45 48%, emerald-700/0 100%)" />
|
||||
```
|
||||
|
||||
Use `fill="none"` when the object should have no fill. Use
|
||||
`fill="transparent"` when the object should keep an editable transparent solid
|
||||
fill.
|
||||
|
||||
`+` lightens theme/RGB colors, `-` darkens, and `/` sets opacity. Tailwind-like
|
||||
color tokens, theme aliases, gradients, shadows, and text style strings are
|
||||
summarized in `tokens.md`.
|
||||
|
||||
## Fill Inline Types
|
||||
|
||||
```ts
|
||||
type ThemeColorName =
|
||||
| "accent1" | "accent2" | "accent3" | "accent4" | "accent5" | "accent6"
|
||||
| "bg1" | "bg2" | "tx1" | "tx2" | "dk1" | "lt1" | "dk2" | "lt2"
|
||||
| "hlink" | "folHlink";
|
||||
|
||||
type ColorConfig =
|
||||
| string
|
||||
| { type: "rgb"; value: string; transform?: ColorTransform }
|
||||
| { type: "theme"; value: ThemeColorName; transform?: ColorTransform };
|
||||
|
||||
type ColorTransform = {
|
||||
opacity?: number; // 0..1 or 0..100
|
||||
lighten?: number; // 0..1 or 0..100
|
||||
darken?: number; // 0..1 or 0..100
|
||||
};
|
||||
|
||||
type FillConfig =
|
||||
| string
|
||||
| { type: "none" }
|
||||
| { type: "solid"; color: ColorConfig; pattern?: PatternConfig }
|
||||
| {
|
||||
type: "gradient";
|
||||
stops: Array<{ offset: number; color: ColorConfig }>; // offset 0..100000
|
||||
offsetScale?: 1 | 100000;
|
||||
angleDeg?: number;
|
||||
gradientKind?: "linear" | "path";
|
||||
}
|
||||
| {
|
||||
type: "image";
|
||||
imageReference: { id: string };
|
||||
alphaModFix?: number;
|
||||
stretchFillRect?: { l?: number; t?: number; r?: number; b?: number };
|
||||
fillRect?: { l?: number; t?: number; r?: number; b?: number };
|
||||
srcRect?: { l?: number; t?: number; r?: number; b?: number };
|
||||
};
|
||||
```
|
||||
|
||||
## Gradient
|
||||
|
||||
```ts
|
||||
const fillConfig = {
|
||||
type: "gradient",
|
||||
gradientKind,
|
||||
angleDeg,
|
||||
stops: [
|
||||
{ offset: startOffset, color: startColor },
|
||||
{ offset: endOffset, color: endColor },
|
||||
],
|
||||
};
|
||||
```
|
||||
|
||||
Gradient offsets use `0` to `100000`.
|
||||
|
||||
## Pattern Fills
|
||||
|
||||
Patterns are available through object fill configs:
|
||||
|
||||
```ts
|
||||
shape.fill = {
|
||||
type: "solid",
|
||||
color: "white",
|
||||
pattern: { type: "diagonalCross", color: "slate-300/70" },
|
||||
};
|
||||
```
|
||||
|
||||
Common compact pattern names:
|
||||
|
||||
```text
|
||||
percent10, percent20, lightHorizontal, lightVertical, smallGrid, dotGrid,
|
||||
diagonalCross, narrowVertical, wave, smallCheck
|
||||
```
|
||||
|
||||
Supported pattern names:
|
||||
|
||||
```text
|
||||
none, solid, mediumGray, darkGray, lightGray, darkHorizontal, darkVertical,
|
||||
darkDown, darkUp, darkGrid, darkTrellis, lightHorizontal, lightVertical,
|
||||
lightDown, lightUp, lightGrid, lightTrellis, gray125, gray0625, percent5,
|
||||
percent10, percent20, percent25, percent30, percent40, percent50, percent60,
|
||||
percent70, percent75, percent80, percent90, horizontal, vertical,
|
||||
narrowHorizontal, narrowVertical, dashedHorizontal, dashedVertical, cross,
|
||||
largeGrid, smallGrid, dotGrid, downwardDiagonal, upwardDiagonal,
|
||||
wideDownwardDiagonal, wideUpwardDiagonal, dashedDownwardDiagonal,
|
||||
dashedUpwardDiagonal, diagonalCross, smallCheck, largeCheck, smallConfetti,
|
||||
largeConfetti, horizontalBrick, diagonalBrick, solidDiamond, openDiamond,
|
||||
dottedDiamond, plaid, sphere, weave, divot, shingle, wave, trellis, zigZag
|
||||
```
|
||||
|
||||
## Line
|
||||
|
||||
```ts
|
||||
const lineConfig = {
|
||||
style: lineStyle,
|
||||
fill: lineFill,
|
||||
width: lineWidthPx,
|
||||
};
|
||||
```
|
||||
|
||||
## Line Inline Type
|
||||
|
||||
```ts
|
||||
type LineConfig = {
|
||||
style: "solid" | "dashed" | "dotted" | "dash-dot" | "dash-dot-dot" | string;
|
||||
fill?: FillConfig;
|
||||
width?: number;
|
||||
color?: FillConfig; // alias for fill
|
||||
weight?: number; // alias for width
|
||||
};
|
||||
```
|
||||
|
||||
## Cookbook
|
||||
|
||||
```ts
|
||||
// Linear background wash.
|
||||
slide.background.fill = "linear(0deg, #020617 0%, #2563eb 100%)";
|
||||
```
|
||||
|
||||
```ts
|
||||
// Soft radial spotlight behind a chart.
|
||||
chart.plotAreaFill = "radial(#dbeafe/90 0%, #ffffff/0 100%)";
|
||||
```
|
||||
|
||||
```ts
|
||||
// Exact gradient object.
|
||||
shape.fill = {
|
||||
type: "gradient",
|
||||
gradientKind: "linear",
|
||||
angleDeg: 35,
|
||||
offsetScale: 100000,
|
||||
stops: [
|
||||
{ offset: 0, color: "#ffffff" },
|
||||
{ offset: 100000, color: "sky-100" },
|
||||
],
|
||||
};
|
||||
```
|
||||
|
||||
```ts
|
||||
// Normalized gradient offsets.
|
||||
shape.fill = {
|
||||
type: "gradient",
|
||||
gradientKind: "linear",
|
||||
offsetScale: 1,
|
||||
stops: [
|
||||
{ offset: 0, color: "#ffffff" },
|
||||
{ offset: 1, color: "sky-100" },
|
||||
],
|
||||
};
|
||||
```
|
||||
|
||||
```ts
|
||||
// Hairline rule and muted border.
|
||||
shape.line = { style: "solid", fill: "slate-200", width: 1 };
|
||||
ruleShape.line = { style: "dashed", fill: "#94a3b8", width: 1 };
|
||||
```
|
||||
Generated
Vendored
+223
@@ -0,0 +1,223 @@
|
||||
# Help
|
||||
|
||||
Use `presentation.help(...)` to search the presentation JS API and template
|
||||
catalog. Help emits bounded NDJSON records for quick lookup during create, edit,
|
||||
and review workflows.
|
||||
|
||||
## Query
|
||||
|
||||
```ts
|
||||
const result = presentation.help(query, {
|
||||
search,
|
||||
include,
|
||||
maxChars,
|
||||
});
|
||||
console.log(result.ndjson);
|
||||
```
|
||||
|
||||
Example output for `query = "*"` with `include = ["index", "examples"]`:
|
||||
|
||||
```text
|
||||
{"kind":"api","name":"presentation.help","summary":"Search the presentation JS API and template catalog.","tags":["help","docs","examples","presentation.help"],"examples":[{"summary":"Find shape editing APIs","code":"const result = presentation.help('*', {\n search: 'slide.shapes.delete|shape.delete|slide.shapes.add|deleteAll',\n include: ['index', 'examples', 'notes'],\n maxChars: 12000,\n});\nconsole.log(result.ndjson);"}]}
|
||||
{"kind":"api","name":"slide.shapes.add","summary":"Add a preset/custom/connector shape to a slide.","tags":["shape","shapes.add","rectangle","ellipse","connector","slide.shapes.add"],"examples":[{"summary":"Create a styled rectangle","code":"const shape = slide.shapes.add({\n geometry: 'roundRect',\n position: { left: 72, top: 96, width: 320, height: 120 },\n fill: { type: 'solid', color: 'accent1' },\n line: { style: 'solid', fill: 'accent2', width: 2 },\n});\nshape.text = 'Launch plan';"}]}
|
||||
{"kind":"template","name":"agenda","summary":"Agenda slide with a title and list body.","examples":[{"summary":"Apply the agenda template","code":"presentation.apply(presentation.template('agenda'));"}]}
|
||||
```
|
||||
|
||||
Use API records to find facade names and examples; use template records with
|
||||
`presentation.template(name)`.
|
||||
|
||||
Common queries:
|
||||
|
||||
```text
|
||||
*, shape*, slide.shapes.add, chart xAxis, template*
|
||||
```
|
||||
|
||||
Query behavior:
|
||||
|
||||
```text
|
||||
* lists all matching API and template records
|
||||
shape* uses glob matching
|
||||
slide.shapes.add matches the exact dotted API name
|
||||
chart xAxis matches entries containing either word token
|
||||
template* lists template records only
|
||||
```
|
||||
|
||||
Use `search` as a case-insensitive regular expression over the JSON lines after
|
||||
the primary query has selected records:
|
||||
|
||||
```ts
|
||||
const focused = presentation.help("*", {
|
||||
search:
|
||||
"slide\\.shapes\\.delete|shape\\.delete|slide\\.shapes\\.add|deleteAll",
|
||||
include: ["index", "examples", "notes"],
|
||||
maxChars: 12000,
|
||||
});
|
||||
console.log(focused.ndjson);
|
||||
```
|
||||
|
||||
## Include
|
||||
|
||||
Default output includes index fields such as:
|
||||
|
||||
```text
|
||||
kind, name, summary, tags
|
||||
```
|
||||
|
||||
Useful include tokens:
|
||||
|
||||
```text
|
||||
index, examples, notes
|
||||
```
|
||||
|
||||
`include` accepts either an array or a comma-separated string:
|
||||
|
||||
```ts
|
||||
const shapeExamples = presentation.help("slide.shapes.add", {
|
||||
include: ["examples", "notes"],
|
||||
});
|
||||
|
||||
const templateExamples = presentation.help("template*", {
|
||||
include: "index,examples",
|
||||
});
|
||||
```
|
||||
|
||||
## Inline Type
|
||||
|
||||
```ts
|
||||
type PresentationHelpOptions = {
|
||||
include?: string[] | string;
|
||||
search?: string;
|
||||
maxChars?: number;
|
||||
};
|
||||
|
||||
type PresentationHelpResult = {
|
||||
ndjson: string;
|
||||
truncated: boolean;
|
||||
metadata: {
|
||||
revision: string;
|
||||
query: string;
|
||||
include: {
|
||||
requested?: string[] | string;
|
||||
tokens: string[];
|
||||
};
|
||||
search?: string;
|
||||
notices?: string[];
|
||||
};
|
||||
};
|
||||
```
|
||||
|
||||
## Record Kinds
|
||||
|
||||
API records describe public JS facades and methods:
|
||||
|
||||
```text
|
||||
{"kind":"api","name":"slide.shapes.add","summary":"Add a preset/custom/connector shape to a slide.","tags":["shape","shapes.add","rectangle","ellipse","connector","slide.shapes.add"]}
|
||||
{"kind":"api","name":"shape.delete","summary":"Delete this shape from its slide.","tags":["shape","delete shape","remove shape","shape.delete"]}
|
||||
```
|
||||
|
||||
When examples are included, records focus on usage snippets:
|
||||
|
||||
```text
|
||||
{"kind":"api","name":"slide.shapes.add","examples":[{"summary":"Create a styled rectangle","code":"const shape = slide.shapes.add({\n geometry: 'roundRect',\n position: { left: 72, top: 96, width: 320, height: 120 },\n fill: { type: 'solid', color: 'accent1' },\n line: { style: 'solid', fill: 'accent2', width: 2 },\n});\nshape.text = 'Launch plan';"}],"notes":["Preset geometry values include rect, roundRect, ellipse, triangle, rightArrow, and many other PowerPoint shape names."]}
|
||||
```
|
||||
|
||||
Template records describe named template patches for
|
||||
`presentation.template(name)`:
|
||||
|
||||
```text
|
||||
{"kind":"template","name":"title-slide","summary":"Title + subtitle slide with centered text boxes."}
|
||||
{"kind":"template","name":"two-up","summary":"Two-column slide with left/right content boxes."}
|
||||
{"kind":"template","name":"agenda","summary":"Agenda slide with a title and list body."}
|
||||
```
|
||||
|
||||
If output exceeds `maxChars`, the final line is a notice record and
|
||||
`result.truncated` is `true`:
|
||||
|
||||
```text
|
||||
{"kind":"notice","message":"Truncated: omitted 93 lines. Increase maxChars or narrow query."}
|
||||
```
|
||||
|
||||
## Create/Edit Loop
|
||||
|
||||
```ts
|
||||
// Find the public API surface for the edit.
|
||||
const shapeHelp = presentation.help("shape*", {
|
||||
include: ["index", "examples", "notes"],
|
||||
maxChars: 8000,
|
||||
});
|
||||
|
||||
// Build with the documented JS facade.
|
||||
const slide = presentation.slides.add();
|
||||
const shape = slide.shapes.add({
|
||||
geometry: "roundRect",
|
||||
position: { left: 72, top: 96, width: 320, height: 120 },
|
||||
fill: { type: "solid", color: "accent1" },
|
||||
});
|
||||
shape.text = "Launch plan";
|
||||
|
||||
// Inspect the live deck after editing.
|
||||
const snapshot = await presentation.inspect({
|
||||
kind: "slide,textbox,shape",
|
||||
maxChars: 4000,
|
||||
});
|
||||
```
|
||||
|
||||
## Imported Templates
|
||||
|
||||
```ts
|
||||
const templates = presentation.help("template*", {
|
||||
include: ["index", "examples"],
|
||||
maxChars: 4000,
|
||||
});
|
||||
|
||||
presentation.apply(presentation.template("agenda"));
|
||||
```
|
||||
|
||||
Use template help to discover the available names before calling
|
||||
`presentation.template(name)`.
|
||||
|
||||
## Cookbook
|
||||
|
||||
```ts
|
||||
// List the top-level deck APIs.
|
||||
const deckApis = presentation.help("presentation*", {
|
||||
include: "index",
|
||||
maxChars: 6000,
|
||||
});
|
||||
```
|
||||
|
||||
```ts
|
||||
// Search broadly, then filter by regex.
|
||||
const hits = presentation.help("*", {
|
||||
search: "chart|axis|legend",
|
||||
include: ["index", "examples"],
|
||||
maxChars: 8000,
|
||||
});
|
||||
```
|
||||
|
||||
```ts
|
||||
// Pull examples for one exact API.
|
||||
const examples = presentation.help("slide.charts.add", {
|
||||
include: ["examples", "notes"],
|
||||
maxChars: 4000,
|
||||
});
|
||||
```
|
||||
|
||||
```ts
|
||||
// Pair help with inspect for focused edits.
|
||||
const help = presentation.help("shape.text.replace", {
|
||||
include: ["examples", "notes"],
|
||||
});
|
||||
const before = await presentation.inspect({
|
||||
kind: "textbox,shape",
|
||||
search: "Placeholder",
|
||||
maxChars: 4000,
|
||||
});
|
||||
const target = presentation.resolve(anchorId);
|
||||
target.text.replace("Placeholder", "Updated text");
|
||||
const after = await presentation.inspect({
|
||||
target: { id: anchorId, beforeLines: 2, afterLines: 2 },
|
||||
kind: "textbox,shape",
|
||||
maxChars: 2000,
|
||||
});
|
||||
```
|
||||
Generated
Vendored
+286
@@ -0,0 +1,286 @@
|
||||
# Images
|
||||
|
||||
`slide.images` inserts image elements from local paths, bytes, data URLs, SVG, and prompts.
|
||||
|
||||
For embedded image output, use `blob={imageBytes}` with `contentType`. Download remote images
|
||||
first, then pass their local `path` or embedded `blob` bytes to `add` or `replace`.
|
||||
HTTP(S) sources are rejected without fetching them.
|
||||
|
||||
## Add Image
|
||||
|
||||
```ts
|
||||
const image = slide.images.add({
|
||||
blob: imageBytes,
|
||||
contentType: "image/png",
|
||||
alt: "Product screenshot",
|
||||
fit: "cover",
|
||||
position: { left: 72, top: 120, width: 520, height: 320 },
|
||||
crop: { left: 0.02, top: 0, right: 0.04, bottom: 0 },
|
||||
geometry: "roundRect",
|
||||
borderRadius: "rounded-2xl",
|
||||
});
|
||||
```
|
||||
|
||||
## Path Reference And Inline SVG
|
||||
|
||||
```ts
|
||||
const localImage = slide.images.add({
|
||||
path: "/absolute/path/to/product.png",
|
||||
alt: "Product screenshot from disk",
|
||||
fit: "cover",
|
||||
position: { left: 72, top: 120, width: 520, height: 320 },
|
||||
});
|
||||
|
||||
const icon = slide.images.add({
|
||||
svg: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10" fill="#2563eb"/></svg>',
|
||||
alt: "Blue status icon",
|
||||
position: { left: 620, top: 120, width: 48, height: 48 },
|
||||
});
|
||||
```
|
||||
|
||||
## Image Inline Types
|
||||
|
||||
```ts
|
||||
type ImageSource =
|
||||
| { path: string; prompt?: string }
|
||||
| { svg: string; prompt?: string }
|
||||
| { blob: ArrayBuffer | Uint8Array; prompt?: string }
|
||||
| { dataUrl: string; prompt?: string }
|
||||
| { prompt: string };
|
||||
|
||||
type ImageAddOptions = ImageSource & {
|
||||
alt?: string;
|
||||
fit?: "contain" | "cover";
|
||||
contentType?: string;
|
||||
position?: { left?: number; top?: number; width?: number; height?: number };
|
||||
frame?: { left?: number; top?: number; width?: number; height?: number };
|
||||
crop?: { left: number | string; top: number | string; right: number | string; bottom: number | string };
|
||||
geometry?: string; // common: "rect", "roundRect", "ellipse"; full list is the shape preset list
|
||||
borderRadius?: number | string; // number = pixels; string = supported rounded-* token
|
||||
};
|
||||
```
|
||||
|
||||
`position` and `frame` use the same pixel shape. Use either spelling; prefer
|
||||
`position` in add calls and `frame` when preserving imported placement.
|
||||
|
||||
## Resolved From Inspect
|
||||
|
||||
```ts
|
||||
const image = presentation.resolve("im/c3d4e5f6");
|
||||
const oldFrame = image.frame;
|
||||
const oldCrop = image.crop;
|
||||
const oldFit = image.fit;
|
||||
const oldAlt = image.alt;
|
||||
const oldPrompt = image.prompt;
|
||||
const oldGeometry = image.geometry;
|
||||
const oldBorderRadius = image.borderRadius;
|
||||
const oldRotation = image.rotation;
|
||||
const oldFlipHorizontal = image.flipHorizontal;
|
||||
const oldFlipVertical = image.flipVertical;
|
||||
const oldLockAspectRatio = image.lockAspectRatio;
|
||||
|
||||
image.replace({
|
||||
blob: nextBytes,
|
||||
contentType: "image/png",
|
||||
alt: oldAlt ?? "Updated screenshot",
|
||||
...(oldFit ? { fit: oldFit } : {}),
|
||||
...(oldPrompt ? { prompt: oldPrompt } : {}),
|
||||
});
|
||||
image.frame = oldFrame;
|
||||
image.crop = oldCrop;
|
||||
image.geometry = oldGeometry;
|
||||
image.borderRadius = oldBorderRadius;
|
||||
image.rotation = oldRotation;
|
||||
image.flipHorizontal = oldFlipHorizontal;
|
||||
image.flipVertical = oldFlipVertical;
|
||||
image.lockAspectRatio = oldLockAspectRatio;
|
||||
```
|
||||
|
||||
Use `presentation.inspect({ kind: "image", search })` to find the `im/...`
|
||||
anchor id. Preserve frame, crop, fit, alt text, mask geometry, and border radius
|
||||
unless the edit explicitly changes them.
|
||||
Concrete source replacements produce concrete images; pass `prompt` when it
|
||||
should remain available as regeneration metadata.
|
||||
|
||||
## Edit Placement And Fit
|
||||
|
||||
```ts
|
||||
image.position = position;
|
||||
image.frame = frame;
|
||||
image.fit = fit;
|
||||
image.crop = crop;
|
||||
image.geometry = "roundRect";
|
||||
image.borderRadius = "rounded-xl";
|
||||
image.rotation = rotationDeg;
|
||||
image.flipHorizontal = flipHorizontal;
|
||||
image.flipVertical = flipVertical;
|
||||
image.lockAspectRatio = true;
|
||||
image.width = 320;
|
||||
image.height = 180;
|
||||
image.alt = altText;
|
||||
```
|
||||
|
||||
`crop` supplies all four edges. Numbers are normalized `0..1` fractions removed
|
||||
from the source image; strings accept percentages such as `"10%"` or pixel
|
||||
insets such as `"24px"` when source dimensions are available. Values are clamped.
|
||||
`fit="cover"` fills the frame and may crop; `fit="contain"`
|
||||
preserves the full image. `geometry="ellipse"` or `geometry="roundRect"` clips
|
||||
the image. `borderRadius` is for rect/roundRect masks; numbers are pixels and
|
||||
strings use supported `rounded-*` tokens.
|
||||
|
||||
## Replace Source
|
||||
|
||||
```ts
|
||||
image.replace({
|
||||
blob,
|
||||
contentType,
|
||||
path,
|
||||
svg,
|
||||
dataUrl,
|
||||
prompt,
|
||||
alt,
|
||||
fit,
|
||||
});
|
||||
```
|
||||
|
||||
`replace` swaps the source and common source metadata. Choose one primary source
|
||||
field as with `add`. Preserve or set placement, crop, mask geometry, and border
|
||||
radius on the image facade itself.
|
||||
|
||||
## Replace And Regenerate Inline Types
|
||||
|
||||
```ts
|
||||
type ImageReplaceOptions = {
|
||||
alt?: string;
|
||||
fit?: "contain" | "cover";
|
||||
contentType?: string;
|
||||
path?: string;
|
||||
svg?: string;
|
||||
blob?: ArrayBuffer | Uint8Array;
|
||||
dataUrl?: string;
|
||||
prompt?: string;
|
||||
};
|
||||
|
||||
type ImageRegenerateOptions = {
|
||||
prompt?: string;
|
||||
kind?: "sticker" | "layout" | "content" | "infographic";
|
||||
fit?: "contain" | "cover";
|
||||
size?: "1024x1024" | "1536x1024" | "1024x1536";
|
||||
quality?: "low" | "medium" | "high";
|
||||
background?: "auto" | "transparent" | "opaque";
|
||||
outputFormat?: "png" | "jpeg" | "webp";
|
||||
};
|
||||
```
|
||||
|
||||
## Prompt Images
|
||||
|
||||
```ts
|
||||
const promptImage = slide.images.add({
|
||||
prompt,
|
||||
alt,
|
||||
position,
|
||||
fit,
|
||||
});
|
||||
|
||||
promptImage.regenerate({ kind });
|
||||
```
|
||||
|
||||
Prompt placeholders are optional. Use concrete sources when asset bytes or
|
||||
references are already available.
|
||||
|
||||
## Concrete Image Sources
|
||||
|
||||
```ts
|
||||
const imageBytes = assetBytes;
|
||||
const imageUri = assetUri;
|
||||
const imageDataUrl = assetDataUrl;
|
||||
```
|
||||
|
||||
## JSX Declarative Image
|
||||
|
||||
```tsx
|
||||
/** @jsxRuntime automatic */
|
||||
|
||||
slide.compose(
|
||||
<row width="fill" height="fill" gap={16}>
|
||||
<image
|
||||
blob={imageBytes}
|
||||
alt="Embedded bytes"
|
||||
fit="cover"
|
||||
width={320}
|
||||
height={180}
|
||||
/>
|
||||
<image
|
||||
path={imagePath}
|
||||
alt="Local image"
|
||||
fit="contain"
|
||||
width={320}
|
||||
height={180}
|
||||
/>
|
||||
</row>,
|
||||
{
|
||||
frame: { left: 48, top: 40, width: 864, height: 240 },
|
||||
baseUnit: 8,
|
||||
},
|
||||
);
|
||||
```
|
||||
|
||||
## Cookbook
|
||||
|
||||
```ts
|
||||
// Full-frame image crop.
|
||||
slide.images.add({
|
||||
blob: imageBytes,
|
||||
contentType: "image/jpeg",
|
||||
alt: "Workspace image",
|
||||
fit: "cover",
|
||||
position: { left: 0, top: 0, width: 1280, height: 720 },
|
||||
});
|
||||
```
|
||||
|
||||
```ts
|
||||
// Rounded image mask.
|
||||
slide.images.add({
|
||||
blob: imageBytes,
|
||||
contentType: "image/jpeg",
|
||||
alt: "Customer interview",
|
||||
fit: "cover",
|
||||
geometry: "roundRect",
|
||||
borderRadius: "rounded-3xl",
|
||||
position: { left: 720, top: 96, width: 448, height: 512 },
|
||||
});
|
||||
```
|
||||
|
||||
```tsx
|
||||
// Circular avatar mask in JSX.
|
||||
<image
|
||||
blob={avatarBytes}
|
||||
contentType="image/png"
|
||||
alt="Speaker"
|
||||
fit="cover"
|
||||
geometry="ellipse"
|
||||
width={96}
|
||||
height={96}
|
||||
/>
|
||||
```
|
||||
|
||||
```tsx
|
||||
// Rounded crop/mask in JSX.
|
||||
<image
|
||||
blob={portraitBytes}
|
||||
contentType="image/jpeg"
|
||||
alt="Customer portrait"
|
||||
fit="cover"
|
||||
geometry="roundRect"
|
||||
borderRadius="rounded-2xl"
|
||||
crop={{ left: 0.08, top: 0.02, right: 0.14, bottom: 0 }}
|
||||
width={320}
|
||||
height={420}
|
||||
/>
|
||||
```
|
||||
|
||||
```ts
|
||||
// Manual crop when the subject is off-center.
|
||||
image.fit = "cover";
|
||||
image.crop = { left: 0.08, top: 0.02, right: 0.18, bottom: 0.06 };
|
||||
```
|
||||
Generated
Vendored
+131
@@ -0,0 +1,131 @@
|
||||
# Inspect
|
||||
|
||||
`presentation.inspect({ select, include, fileName })` queries one public
|
||||
presentation tree with [RFC 9535 JSONPath](https://www.rfc-editor.org/rfc/rfc9535.html).
|
||||
The [JSON Schema](./inspect.schema.json) describes its content and layout fields.
|
||||
`select` finds nodes; `include` chooses exact fields from those nodes.
|
||||
|
||||
## Read content
|
||||
|
||||
```ts
|
||||
await presentation.inspect({
|
||||
select: "$.slides[*]",
|
||||
include: [
|
||||
"id", "index", "layout", "title",
|
||||
"elements.id", "elements.kind", "elements.text", "elements.alt", "elements.title",
|
||||
"notes.text",
|
||||
],
|
||||
fileName: "content.ndjson",
|
||||
});
|
||||
```
|
||||
|
||||
This writes one slide per line, retaining its applied layout and editable
|
||||
element IDs. Text includes paragraph breaks and complete table content. The
|
||||
query omits positions and styles, so those fields are not computed.
|
||||
|
||||
The tree has this shape (selected fields):
|
||||
|
||||
```json
|
||||
{
|
||||
"schema": "openai.presentation.inspection/v1",
|
||||
"unit": "px",
|
||||
"id": "pr/abcdefgh",
|
||||
"kind": "presentation",
|
||||
"slides": [{
|
||||
"id": "sl/12345678", "kind": "slide", "index": 0,
|
||||
"layout": { "id": "ly/abcdefgh", "name": "Title and image" },
|
||||
"elements": [{ "id": "sh/abcdefgh", "kind": "textbox", "text": "Welcome" }],
|
||||
"notes": { "id": "nt/12345678", "kind": "notes", "text": "Opening remarks" }
|
||||
}]
|
||||
}
|
||||
```
|
||||
|
||||
Only canonical prefix/hash IDs are exposed. Pass editable `sl/`, `sh/`, `im/`,
|
||||
`ch/`, `tb/`, `ea/`, and `nt/` IDs to `presentation.resolve(id)`.
|
||||
The read-only `ly/` ID identifies the applied layout. `index` is zero-based;
|
||||
positions and computed font sizes use pixels.
|
||||
|
||||
## Find and edit
|
||||
|
||||
```ts
|
||||
const hits = await presentation.inspect({
|
||||
select: "$.slides[*].elements[?(@.text == 'Confidential')]",
|
||||
include: ["id", "text"],
|
||||
});
|
||||
```
|
||||
|
||||
JSONPath filters inspect source fields before projection. Comparisons therefore
|
||||
match the text itself, rather than its serialized JSON representation. Use
|
||||
`$.slides[0,2].elements[*]` for two slides or a predicate such as
|
||||
`@.kind == 'image'` for one element kind. Selected scalar values are also valid;
|
||||
for example, `$.slides[*].title` returns title strings.
|
||||
|
||||
Use `search(@.text, 'overview|steps')` for a text pattern, or `match()` to match
|
||||
the entire string. Patterns follow [I-Regexp](https://www.rfc-editor.org/rfc/rfc9485.html).
|
||||
`length()` measures a value, `count()` counts selected nodes, and `value()`
|
||||
extracts a value when a query selects exactly one node. Filters use `==` and
|
||||
`!=`; JavaScript expressions and method calls are not part of JSONPath.
|
||||
Repeated selectors retain repeated results: `$.slides[0,0]` selects slide zero
|
||||
twice. Invalid queries report a syntax error with the character offset.
|
||||
|
||||
Use the literal ID from the result for subsequent edits. Read computed styling
|
||||
or mixed-format text for that same ID:
|
||||
|
||||
```ts
|
||||
await presentation.inspect({
|
||||
select: "$.slides[*].elements[?(@.id == 'sh/abcdefgh')]",
|
||||
include: ["id", "text", "position", "style", "paragraphs"],
|
||||
});
|
||||
```
|
||||
|
||||
`style` reflects theme and inherited formatting. `paragraphs` preserves styled
|
||||
runs; `cells` expands a table. These fields are evaluated when accessed without
|
||||
rendering slides or fetching images. Explicit paths keep queries focused;
|
||||
recursive `..` queries can traverse computed fields across the document.
|
||||
|
||||
`include` is an exact array of typed field paths. Nested paths such as
|
||||
`elements.text` preserve arrays and object structure. Including a parent such
|
||||
as `style` includes that complete object. Omitting `include` returns complete
|
||||
selected nodes. Include `id` explicitly when the next step needs an editing ID.
|
||||
|
||||
## Files and results
|
||||
|
||||
An attached Artifact Session writes all selected records to
|
||||
`<outputDirectory>/presentation-inspect.ndjson`. `fileName` chooses another
|
||||
NDJSON basename. Reusing a name replaces that file. The completed session run's
|
||||
`files` contains finalized paths. Unnamed inspection outside a session stays in
|
||||
memory; the Node runtime supports a named standalone output path.
|
||||
|
||||
The returned object prints `recordCount` and output metadata. Access `.records`
|
||||
or `.ndjson` explicitly for the complete values. No pagination or record
|
||||
abbreviation applies to JSONPath queries. Select nodes and fields according to
|
||||
the task before reading the output into model context.
|
||||
|
||||
Rendering separately writes `slide-N.png` and `slide-N.layout.json`. Layout
|
||||
files use these same element fields and canonical IDs in a slide-scoped file
|
||||
envelope. The file's `slide` contains the inspected slide metadata and its
|
||||
`elements` contains the compact layout field selection. The content query does
|
||||
not replace those render outputs. Full layout export also exposes inherited
|
||||
paint layers and paragraph/run formatting.
|
||||
|
||||
## Types
|
||||
|
||||
```ts
|
||||
type PresentationInspectQueryOptions = {
|
||||
select: string;
|
||||
include?: readonly PresentationInspectField[];
|
||||
fileName?: string;
|
||||
};
|
||||
|
||||
type PresentationInspectQueryResult = {
|
||||
readonly records: readonly unknown[];
|
||||
readonly recordCount: number;
|
||||
readonly ndjson: string;
|
||||
readonly path?: string;
|
||||
readonly status?: "pending" | "saved" | "conflict" | "error";
|
||||
readonly message?: string;
|
||||
};
|
||||
```
|
||||
|
||||
The earlier preset and record-filter overloads remain deprecated compatibility
|
||||
entry points. New callers should use the explicit query above.
|
||||
Generated
Vendored
+865
@@ -0,0 +1,865 @@
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"const": "openai.presentation.inspection/v1"
|
||||
},
|
||||
"unit": {
|
||||
"type": "string",
|
||||
"const": "px"
|
||||
},
|
||||
"id": {
|
||||
"type": "string",
|
||||
"pattern": "^pr\\/[a-z0-9]+$"
|
||||
},
|
||||
"kind": {
|
||||
"type": "string",
|
||||
"const": "presentation"
|
||||
},
|
||||
"slides": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/$defs/Slide"
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"schema",
|
||||
"unit",
|
||||
"id",
|
||||
"kind",
|
||||
"slides"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"$defs": {
|
||||
"Slide": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": {
|
||||
"type": "string",
|
||||
"pattern": "^sl\\/[a-z0-9]+$"
|
||||
},
|
||||
"kind": {
|
||||
"type": "string",
|
||||
"const": "slide"
|
||||
},
|
||||
"index": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
"layout": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": {
|
||||
"type": "string",
|
||||
"pattern": "^ly\\/[a-z0-9]+$"
|
||||
},
|
||||
"name": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"id"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"title": {
|
||||
"type": "string"
|
||||
},
|
||||
"position": {
|
||||
"$ref": "#/$defs/Position"
|
||||
},
|
||||
"backgroundColor": {
|
||||
"$ref": "#/$defs/Color"
|
||||
},
|
||||
"elements": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/$defs/Element"
|
||||
}
|
||||
},
|
||||
"notes": {
|
||||
"$ref": "#/$defs/Notes"
|
||||
},
|
||||
"inheritedLayers": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/$defs/InheritedLayer"
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"id",
|
||||
"kind",
|
||||
"index",
|
||||
"position",
|
||||
"elements"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"id": "Slide"
|
||||
},
|
||||
"Position": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"left": {
|
||||
"type": "number"
|
||||
},
|
||||
"top": {
|
||||
"type": "number"
|
||||
},
|
||||
"width": {
|
||||
"type": "number"
|
||||
},
|
||||
"height": {
|
||||
"type": "number"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"left",
|
||||
"top",
|
||||
"width",
|
||||
"height"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"id": "Position"
|
||||
},
|
||||
"Color": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"type": {
|
||||
"type": "string",
|
||||
"const": "rgb"
|
||||
},
|
||||
"value": {
|
||||
"type": "string"
|
||||
},
|
||||
"transform": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"opacity": {
|
||||
"type": "number"
|
||||
},
|
||||
"lighten": {
|
||||
"type": "number"
|
||||
},
|
||||
"darken": {
|
||||
"type": "number"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"type",
|
||||
"value"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"type": {
|
||||
"type": "string",
|
||||
"const": "theme"
|
||||
},
|
||||
"value": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"accent1",
|
||||
"accent2",
|
||||
"accent3",
|
||||
"accent4",
|
||||
"accent5",
|
||||
"accent6",
|
||||
"bg1",
|
||||
"bg2",
|
||||
"tx1",
|
||||
"tx2",
|
||||
"dk1",
|
||||
"lt1",
|
||||
"dk2",
|
||||
"lt2",
|
||||
"hlink",
|
||||
"folHlink"
|
||||
]
|
||||
},
|
||||
"transform": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"opacity": {
|
||||
"type": "number"
|
||||
},
|
||||
"lighten": {
|
||||
"type": "number"
|
||||
},
|
||||
"darken": {
|
||||
"type": "number"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"type",
|
||||
"value"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
],
|
||||
"id": "Color"
|
||||
},
|
||||
"Element": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": {
|
||||
"type": "string",
|
||||
"pattern": "^(sh|im|ch|tb|ea)\\/[a-z0-9]+$"
|
||||
},
|
||||
"kind": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"shape",
|
||||
"textbox",
|
||||
"image",
|
||||
"chart",
|
||||
"table",
|
||||
"embeddedArtifact"
|
||||
]
|
||||
},
|
||||
"name": {
|
||||
"type": "string"
|
||||
},
|
||||
"text": {
|
||||
"type": "string"
|
||||
},
|
||||
"title": {
|
||||
"type": "string"
|
||||
},
|
||||
"position": {
|
||||
"$ref": "#/$defs/Position"
|
||||
},
|
||||
"order": {
|
||||
"type": "integer",
|
||||
"exclusiveMinimum": 0,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
"scope": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"slide",
|
||||
"layout",
|
||||
"master"
|
||||
]
|
||||
},
|
||||
"editable": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"rotation": {
|
||||
"type": "number"
|
||||
},
|
||||
"horizontalFlip": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"verticalFlip": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"hidden": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"geometry": {
|
||||
"type": "string"
|
||||
},
|
||||
"style": {
|
||||
"$ref": "#/$defs/TextStyle"
|
||||
},
|
||||
"paragraphs": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/$defs/Paragraph"
|
||||
}
|
||||
},
|
||||
"fillColor": {
|
||||
"$ref": "#/$defs/Color"
|
||||
},
|
||||
"lineColor": {
|
||||
"$ref": "#/$defs/Color"
|
||||
},
|
||||
"lineWidth": {
|
||||
"type": "number"
|
||||
},
|
||||
"alt": {
|
||||
"type": "string"
|
||||
},
|
||||
"chartType": {
|
||||
"type": "string"
|
||||
},
|
||||
"rows": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
"cols": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
"contentType": {
|
||||
"type": "string"
|
||||
},
|
||||
"crop": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"left": {
|
||||
"type": "number"
|
||||
},
|
||||
"top": {
|
||||
"type": "number"
|
||||
},
|
||||
"right": {
|
||||
"type": "number"
|
||||
},
|
||||
"bottom": {
|
||||
"type": "number"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"left",
|
||||
"top",
|
||||
"right",
|
||||
"bottom"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"fit": {
|
||||
"type": "string"
|
||||
},
|
||||
"mask": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"geometry": {
|
||||
"type": "string"
|
||||
},
|
||||
"adjustmentList": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"name": {
|
||||
"type": "string"
|
||||
},
|
||||
"formula": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"geometry"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"prompt": {
|
||||
"type": "string"
|
||||
},
|
||||
"isPlaceholder": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"asset": {
|
||||
"$ref": "#/$defs/Asset"
|
||||
},
|
||||
"fillImage": {
|
||||
"$ref": "#/$defs/Asset"
|
||||
},
|
||||
"tableCell": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"tableId": {
|
||||
"type": "string",
|
||||
"pattern": "^(sh|im|ch|tb|ea)\\/[a-z0-9]+$"
|
||||
},
|
||||
"cellIndex": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
"row": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
"column": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
"overlap": {
|
||||
"type": "number"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"tableId",
|
||||
"cellIndex",
|
||||
"row",
|
||||
"column",
|
||||
"overlap"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"cells": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/$defs/TableCell"
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"id",
|
||||
"kind"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"id": "Element"
|
||||
},
|
||||
"TextStyle": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"anchor": {
|
||||
"type": "number"
|
||||
},
|
||||
"vertical": {
|
||||
"type": "number"
|
||||
},
|
||||
"rotation": {
|
||||
"type": "number"
|
||||
},
|
||||
"fontSize": {
|
||||
"type": "number"
|
||||
},
|
||||
"name": {
|
||||
"type": "string"
|
||||
},
|
||||
"family": {
|
||||
"type": "number"
|
||||
},
|
||||
"scheme": {
|
||||
"type": "string"
|
||||
},
|
||||
"typeface": {
|
||||
"type": "string"
|
||||
},
|
||||
"color": {
|
||||
"$ref": "#/$defs/Color"
|
||||
},
|
||||
"bold": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"italic": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"alignment": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"left",
|
||||
"center",
|
||||
"right",
|
||||
"justify"
|
||||
]
|
||||
},
|
||||
"verticalAlignment": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"top",
|
||||
"middle",
|
||||
"bottom"
|
||||
]
|
||||
},
|
||||
"lineSpacing": {
|
||||
"type": "number"
|
||||
},
|
||||
"textTransform": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"none",
|
||||
"uppercase",
|
||||
"smallCaps"
|
||||
]
|
||||
},
|
||||
"wrap": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"square",
|
||||
"none"
|
||||
]
|
||||
},
|
||||
"autoFit": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"none",
|
||||
"shrinkText",
|
||||
"resizeShapeToFitText"
|
||||
]
|
||||
},
|
||||
"autoFitScale": {
|
||||
"type": "number"
|
||||
},
|
||||
"autoFitLineSpaceReduction": {
|
||||
"type": "number"
|
||||
},
|
||||
"insets": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"top": {
|
||||
"type": "number"
|
||||
},
|
||||
"right": {
|
||||
"type": "number"
|
||||
},
|
||||
"bottom": {
|
||||
"type": "number"
|
||||
},
|
||||
"left": {
|
||||
"type": "number"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
"useParagraphSpacing": {
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false,
|
||||
"id": "TextStyle"
|
||||
},
|
||||
"Paragraph": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"index": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
"text": {
|
||||
"type": "string"
|
||||
},
|
||||
"bulletCharacter": {
|
||||
"type": "string"
|
||||
},
|
||||
"marginLeft": {
|
||||
"type": "number"
|
||||
},
|
||||
"indent": {
|
||||
"type": "number"
|
||||
},
|
||||
"lineSpacingPercent": {
|
||||
"type": "number"
|
||||
},
|
||||
"spaceBefore": {
|
||||
"type": "number"
|
||||
},
|
||||
"spaceAfter": {
|
||||
"type": "number"
|
||||
},
|
||||
"style": {
|
||||
"$ref": "#/$defs/TextStyle"
|
||||
},
|
||||
"runs": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/$defs/TextRun"
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"index",
|
||||
"runs"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"id": "Paragraph"
|
||||
},
|
||||
"TextRun": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"anchor": {
|
||||
"type": "number"
|
||||
},
|
||||
"vertical": {
|
||||
"type": "number"
|
||||
},
|
||||
"rotation": {
|
||||
"type": "number"
|
||||
},
|
||||
"fontSize": {
|
||||
"type": "number"
|
||||
},
|
||||
"name": {
|
||||
"type": "string"
|
||||
},
|
||||
"family": {
|
||||
"type": "number"
|
||||
},
|
||||
"scheme": {
|
||||
"type": "string"
|
||||
},
|
||||
"typeface": {
|
||||
"type": "string"
|
||||
},
|
||||
"color": {
|
||||
"$ref": "#/$defs/Color"
|
||||
},
|
||||
"bold": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"italic": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"alignment": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"left",
|
||||
"center",
|
||||
"right",
|
||||
"justify"
|
||||
]
|
||||
},
|
||||
"verticalAlignment": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"top",
|
||||
"middle",
|
||||
"bottom"
|
||||
]
|
||||
},
|
||||
"lineSpacing": {
|
||||
"type": "number"
|
||||
},
|
||||
"textTransform": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"none",
|
||||
"uppercase",
|
||||
"smallCaps"
|
||||
]
|
||||
},
|
||||
"wrap": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"square",
|
||||
"none"
|
||||
]
|
||||
},
|
||||
"autoFit": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"none",
|
||||
"shrinkText",
|
||||
"resizeShapeToFitText"
|
||||
]
|
||||
},
|
||||
"autoFitScale": {
|
||||
"type": "number"
|
||||
},
|
||||
"autoFitLineSpaceReduction": {
|
||||
"type": "number"
|
||||
},
|
||||
"insets": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"top": {
|
||||
"type": "number"
|
||||
},
|
||||
"right": {
|
||||
"type": "number"
|
||||
},
|
||||
"bottom": {
|
||||
"type": "number"
|
||||
},
|
||||
"left": {
|
||||
"type": "number"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
"useParagraphSpacing": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"index": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
"text": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"index",
|
||||
"text"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"id": "TextRun"
|
||||
},
|
||||
"Asset": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"contentType": {
|
||||
"type": "string"
|
||||
},
|
||||
"uri": {
|
||||
"type": "string"
|
||||
},
|
||||
"prompt": {
|
||||
"type": "string"
|
||||
},
|
||||
"byteLength": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 9007199254740991
|
||||
}
|
||||
},
|
||||
"additionalProperties": false,
|
||||
"id": "Asset"
|
||||
},
|
||||
"TableCell": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"index": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
"row": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
"column": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
"rowSpan": {
|
||||
"type": "integer",
|
||||
"exclusiveMinimum": 0,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
"colSpan": {
|
||||
"type": "integer",
|
||||
"exclusiveMinimum": 0,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
"position": {
|
||||
"$ref": "#/$defs/Position"
|
||||
},
|
||||
"text": {
|
||||
"type": "string"
|
||||
},
|
||||
"textDirection": {
|
||||
"type": "string"
|
||||
},
|
||||
"fillColor": {
|
||||
"$ref": "#/$defs/Color"
|
||||
},
|
||||
"style": {
|
||||
"$ref": "#/$defs/TextStyle"
|
||||
},
|
||||
"paragraphs": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/$defs/Paragraph"
|
||||
}
|
||||
},
|
||||
"ownedElementIds": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string",
|
||||
"pattern": "^(sh|im|ch|tb|ea)\\/[a-z0-9]+$"
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"index",
|
||||
"row",
|
||||
"column"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"id": "TableCell"
|
||||
},
|
||||
"Notes": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": {
|
||||
"type": "string",
|
||||
"pattern": "^nt\\/[a-z0-9]+$"
|
||||
},
|
||||
"kind": {
|
||||
"type": "string",
|
||||
"const": "notes"
|
||||
},
|
||||
"text": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"id",
|
||||
"kind",
|
||||
"text"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"id": "Notes"
|
||||
},
|
||||
"InheritedLayer": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": {
|
||||
"type": "string",
|
||||
"pattern": "^ly\\/[a-z0-9]+$"
|
||||
},
|
||||
"scope": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"layout",
|
||||
"master"
|
||||
]
|
||||
},
|
||||
"name": {
|
||||
"type": "string"
|
||||
},
|
||||
"type": {
|
||||
"type": "string"
|
||||
},
|
||||
"parentLayoutId": {
|
||||
"type": "string",
|
||||
"pattern": "^ly\\/[a-z0-9]+$"
|
||||
},
|
||||
"backgroundColor": {
|
||||
"$ref": "#/$defs/Color"
|
||||
},
|
||||
"backgroundImage": {
|
||||
"$ref": "#/$defs/Asset"
|
||||
},
|
||||
"elements": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/$defs/Element"
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"id",
|
||||
"scope",
|
||||
"elements"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"id": "InheritedLayer"
|
||||
}
|
||||
}
|
||||
}
|
||||
Generated
Vendored
+227
@@ -0,0 +1,227 @@
|
||||
# Presentation JSX Reference
|
||||
|
||||
This is the compact API reference for authoring editable presentations with
|
||||
presentation JSX. It describes the node vocabulary and layout mechanics. For
|
||||
first-principles row, column, grid, alignment, mask, and overlay recipes, read
|
||||
`cookbook/layout.md`.
|
||||
|
||||
Examples start after `presentation` and `slide` exist.
|
||||
|
||||
## Authoring Defaults
|
||||
|
||||
- Use JSX for structured slide layout: `slide.compose(<row ... />, { frame })`.
|
||||
- Use string sizing where supported: `width="fill"`, `height="hug"`,
|
||||
`height="fill"`.
|
||||
- Use raw pixel numbers for fixed sizes: `width={420}`, `gap={24}`,
|
||||
`padding={{ x: 48, y: 40 }}`.
|
||||
- Use Tailwind-like tokens for common styling: `fill="slate-950"`,
|
||||
`borderRadius="rounded-xl"`, `shadow="shadow-md"`,
|
||||
`className="bg-white rounded-xl shadow-sm"`.
|
||||
- Use `row`, `column`, `grid`, `layers`, and `box` for layout. Use absolute
|
||||
slide frames only for the outer composed region, fixed chrome, and
|
||||
imported-template details. For overlays, scrims, and masked image
|
||||
compositions inside a region, use `layers` and image `geometry`/`borderRadius`.
|
||||
- Put text in `paragraph` and inline emphasis in child `run` nodes.
|
||||
- Put real data in native `table` and `chart` nodes.
|
||||
- Model-facing examples use string sizing and local track objects instead of
|
||||
imported sizing helpers such as `wrap(...)`, `grow(...)`, and `fr(...)`.
|
||||
|
||||
## JSX Usage Rules
|
||||
|
||||
Use JSX props for layout and token strings for common visual styling:
|
||||
|
||||
| Need | Use |
|
||||
| --- | --- |
|
||||
| Layout sizing | `width="fill"`, `height={320}`, `gap={24}`, `padding={{ x: 32, y: 24 }}` |
|
||||
| Flex flow | `<row align="center" justify="between">` and `<column gap={16}>` |
|
||||
| Grid tracks | local arrays such as `[{ mode: "fr", value: 1 }]` |
|
||||
| Visual tokens | `className="bg-white rounded-xl shadow-sm"` |
|
||||
| Exact text | `style="font: 700 28px Inter; color: #0f172a; leading: 1.1"` |
|
||||
| Gradients | `fill="linear(135deg, #fff 0%, sky-100 100%)"` |
|
||||
| Image masks | `<image geometry="ellipse" crop={...} fit="cover" />` |
|
||||
|
||||
## Canonical Node Set
|
||||
|
||||
### Slide Roots
|
||||
|
||||
| Node | Purpose | Common props |
|
||||
| --- | --- | --- |
|
||||
| `slide` | Whole-slide JSX root | `id`, `name`, `width`, `height`, `padding`, `gap`, `align`, `justify`, `background`, `backgroundRef` |
|
||||
| `background` | Slide background metadata | `fill`, `ref` |
|
||||
|
||||
Most code composes directly into an existing `slide` facade rather than using a
|
||||
`<slide>` root.
|
||||
|
||||
### Layout Nodes
|
||||
|
||||
| Node | Purpose | Common props |
|
||||
| --- | --- | --- |
|
||||
| `row` | Horizontal flex-like layout | `width`, `height`, `gap`, `align`, `justify`, `padding` |
|
||||
| `column` | Vertical flex-like layout | `width`, `height`, `gap`, `align`, `justify`, `padding` |
|
||||
| `grid` | Track layout with spans | `columns`, `rows`, `autoRows`, `columnGap`, `rowGap`, `alignItems`, `justifyItems`, `padding` |
|
||||
| `layers` | Overlay children in one frame | `width`, `height`, `padding`, `alignItems`, `justifyItems` |
|
||||
| `box` | Surface/container with one child region | `width`, `height`, `padding`, `align`, `justify`, `fill`, `line`, `borderRadius`, `shadow`, `className` |
|
||||
|
||||
`align` controls the cross axis. `justify` controls the main axis. Supported
|
||||
values are `"start"`, `"center"`, `"end"`, `"stretch"` for alignment and
|
||||
`"start"`, `"center"`, `"end"`, `"between"` for distribution.
|
||||
|
||||
All direct grid children support `columnSpan` and `rowSpan`, including
|
||||
`row`, `column`, `box`, `paragraph`, `shape`, `image`, `table`, and `chart`.
|
||||
|
||||
### Content Nodes
|
||||
|
||||
| Node | Purpose | Common props |
|
||||
| --- | --- | --- |
|
||||
| `paragraph` | Text block | `width`, `height`, `style`, `className`, `transform`, `bulletCharacter`, `marginLeft`, `indent`, `spaceBefore`, `spaceAfter`, `styleId`, `paragraphStyle` |
|
||||
| `run` | Inline text run | children, `textStyle`, `className`, `link` |
|
||||
| `shape` | Primitive drawing | `geometry`, `width`, `height`, `fill`, `line`, `borderRadius`, `shadow`, `className` |
|
||||
| `image` | Raster/vector image | `path`, `blob`, `dataUrl`, `svg`, `prompt`, `contentType`, `fit`, `alt`, `geometry`, `borderRadius`, `crop`, `rotation`, `flipHorizontal`, `flipVertical`, `lockAspectRatio`, `width`, `height` |
|
||||
| `rule` | Divider line | `stroke`, `weight`, `opacity`, `width`, `height` |
|
||||
| `table` | Native table | `rows`, `columns`, `values`, `style`, `styleOptions`, `width`, `height` |
|
||||
| `chart` | Native chart | `chartType`, `title`, `categories`, `series`, `legend`, `xAxis`, `yAxis`, `width`, `height` |
|
||||
|
||||
`id` and `name` are supported on materialized nodes. Use deterministic
|
||||
kebab-case `name` values on composed roots and important descendants:
|
||||
`content-frame`, `primary-heading`, `metrics-grid`, `chart-frame`, `revenue-chart`.
|
||||
Names should describe role, not visual position. Use `id` when the calling code
|
||||
controls stability across edits.
|
||||
|
||||
### Chart Child Nodes
|
||||
|
||||
Use a compact chart config when it is clearest. Use nested chart nodes when the
|
||||
JSX tree should expose structure.
|
||||
|
||||
| Node | Purpose |
|
||||
| --- | --- |
|
||||
| `bar`, `line`, `area`, `scatter`, `bubble`, `radar`, `pie`, `doughnut`, `treemap`, `sunburst`, `map`, `waterfall`, `funnel`, `histogram`, `boxWhisker`, `stock`, `surface`, `surface3D`, `pareto`, `combo`, `line3D`, `pie3D`, `area3D`, `bar3D`, `ofPie` | Chart family selector/options |
|
||||
| `legend`, `data-labels`, `data-table`, `x-axis`, `y-axis`, `axis`, `major-gridlines`, `minor-gridlines` | Chart chrome and axes |
|
||||
| `series`, `marker`, `point`, `data-label`, `trendline`, `trendline-label`, `error-bars` | Series and point-level options |
|
||||
| `view-3d` | 3D camera options |
|
||||
|
||||
## Sizing And Frames
|
||||
|
||||
Use these forms first:
|
||||
|
||||
| Intent | JSX |
|
||||
| --- | --- |
|
||||
| Fill parent | `width="fill"` or `height="fill"` |
|
||||
| Fit content | `width="hug"` or `height="hug"` |
|
||||
| Fixed pixels | `width={320}` or `height={180}` |
|
||||
| Equal children in a row/column | give each child `width="fill"` or `height="fill"` |
|
||||
| One fixed region plus remaining space | one child `width={520}`, sibling `width="fill"` |
|
||||
| Fixed slide region | `slide.compose(node, { frame: { left, top, width, height } })` |
|
||||
|
||||
`frame` uses numeric pixels. JSX size props accept strings for `"fill"` and
|
||||
`"hug"` plus raw pixel numbers.
|
||||
|
||||
Use `1280 x 720` as the default canvas unless the task or source deck requires
|
||||
another size. A common content frame is:
|
||||
|
||||
```ts
|
||||
const PAGE = { left: 72, top: 64, width: 1136, height: 592 };
|
||||
```
|
||||
|
||||
## Alignment Matrix
|
||||
|
||||
| Node | Main axis | Cross axis | Distribution prop | Cross-axis prop | Defaults |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| `row` | horizontal | vertical | `justify`: `start`, `center`, `end`, `between` | `align`: `start`, `center`, `end`, `stretch` | `justify="start"`, `align="start"` |
|
||||
| `column` | vertical | horizontal | `justify`: `start`, `center`, `end`, `between` | `align`: `start`, `center`, `end`, `stretch` | `justify="start"`, `align="start"` |
|
||||
| `grid` | tracks | cells | `justifyItems`: `start`, `center`, `end`, `stretch` | `alignItems`: `start`, `center`, `end`, `stretch` | both `stretch` |
|
||||
| `layers` | shared frame | shared frame | `justifyItems`: `start`, `center`, `end`, `stretch` | `alignItems`: `start`, `center`, `end`, `stretch` | both `stretch` |
|
||||
|
||||
## Layout Recipes
|
||||
|
||||
This top-level reference stays close to the JSX API. For copy-paste row,
|
||||
column, 3-column, 12-grid, alignment, mask, overlay, and gradient recipes, use
|
||||
[`cookbook/layout.md`](./cookbook/layout.md).
|
||||
|
||||
## Text Examples
|
||||
|
||||
```tsx
|
||||
<paragraph className="text-slate-950 text-4xl font-bold leading-tight">
|
||||
A paragraph can contain plain text.
|
||||
</paragraph>
|
||||
|
||||
<paragraph className="text-slate-600 text-lg leading-relaxed">
|
||||
Use <run textStyle={{ bold: true, color: "sky-600" }}>runs</run> for inline
|
||||
emphasis or links.
|
||||
</paragraph>
|
||||
|
||||
<column width="fill" height="hug" gap={8}>
|
||||
<paragraph
|
||||
width="fill"
|
||||
className="text-slate-700 text-lg leading-relaxed"
|
||||
>
|
||||
First paragraph.
|
||||
</paragraph>
|
||||
<paragraph bulletCharacter="•" marginLeft={18} indent={-10}>
|
||||
Bulleted paragraph with native list metadata.
|
||||
</paragraph>
|
||||
</column>
|
||||
```
|
||||
|
||||
Use `style={{ ... }}` for exact text config and `className` for tokenized
|
||||
common text styling. A string `style` containing `:` or `;` is parsed as a
|
||||
compact text declaration; any other string is treated as a named presentation
|
||||
style id.
|
||||
|
||||
```tsx
|
||||
<paragraph style="font: 700 22px Inter; color: #334155; leading: 1.25; wrap: none">
|
||||
Exact style string
|
||||
</paragraph>
|
||||
```
|
||||
|
||||
## Tables And Charts
|
||||
|
||||
Prefer compact config for data objects.
|
||||
|
||||
```tsx
|
||||
<table
|
||||
rows={3}
|
||||
columns={3}
|
||||
values={[
|
||||
["Metric", "Q1", "Q2"],
|
||||
["Revenue", 12, 18],
|
||||
["Margin", "42%", "45%"],
|
||||
]}
|
||||
style="TableStyleMedium2"
|
||||
styleOptions={{ headerRow: true, bandedRows: true }}
|
||||
width="fill"
|
||||
height={220}
|
||||
/>
|
||||
|
||||
<chart
|
||||
chartType="bar"
|
||||
title="Pipeline"
|
||||
categories={["Q1", "Q2", "Q3"]}
|
||||
series={[{ name: "Revenue", values: [12, 18, 24], fill: "sky-500" }]}
|
||||
xAxis={{ textStyle: { fontSize: 10, fill: "slate-600" } }}
|
||||
yAxis={{ majorGridlines: { style: "solid", fill: "slate-200", width: 1 } }}
|
||||
width="fill"
|
||||
height={280}
|
||||
/>
|
||||
```
|
||||
|
||||
Use nested chart nodes when the chart needs explicit series, point, trendline,
|
||||
axis, or label structure in the JSX tree.
|
||||
|
||||
## Image Sources
|
||||
|
||||
| Source prop | Use when |
|
||||
| --- | --- |
|
||||
| `blob={bytes}` | Export must embed the actual image bytes. |
|
||||
| `dataUrl="data:image/..."` | Bytes are already encoded inline. |
|
||||
| `path="/assets/image.png"` | A downloaded image is available as a local file. |
|
||||
| `prompt="..."` | The slide should contain an image-generation placeholder. |
|
||||
|
||||
Use `fit="contain"` when the full image must remain visible. Use `fit="cover"`
|
||||
when cropping is deliberate. Keep labels and data as editable slide text layered
|
||||
with the image.
|
||||
|
||||
## Reference Tests
|
||||
|
||||
- `tests/presentation/jsx.spec.tsx`: JSX normalization and compose behavior.
|
||||
- `tests/presentation/jsx-style-language.spec.tsx`: compact style strings.
|
||||
- `tests/presentation/tailwind-tokens.sanity.spec.ts`: token coverage.
|
||||
Generated
Vendored
+155
@@ -0,0 +1,155 @@
|
||||
# Layouts
|
||||
|
||||
Layouts define reusable placeholder structure for slides.
|
||||
|
||||
## Create A Layout
|
||||
|
||||
```ts
|
||||
const layout = presentation.layouts.add(layoutName);
|
||||
layout.placeholders.add({
|
||||
type: placeholderType,
|
||||
index: placeholderIndex,
|
||||
text: placeholderText,
|
||||
geometry: "textbox",
|
||||
});
|
||||
```
|
||||
|
||||
## Placeholder Inline Type
|
||||
|
||||
```ts
|
||||
type PlaceholderConfig = {
|
||||
type?:
|
||||
| "title"
|
||||
| "subtitle"
|
||||
| "body"
|
||||
| "picture"
|
||||
| "chart"
|
||||
| "table"
|
||||
| "content";
|
||||
index?: number;
|
||||
text?: TextValue;
|
||||
geometry?: "textbox" | "rect" | "roundRect" | string;
|
||||
position?: { left?: number; top?: number; width?: number; height?: number };
|
||||
fill?: FillConfig;
|
||||
line?: LineConfig;
|
||||
};
|
||||
```
|
||||
|
||||
## Shape-Based Placeholders
|
||||
|
||||
```ts
|
||||
const placeholder = layout.shapes.addPlaceholder(placeholderName);
|
||||
placeholder.placeholder.type = placeholderType;
|
||||
placeholder.placeholder.index = placeholderIndex;
|
||||
placeholder.text = placeholderText;
|
||||
```
|
||||
|
||||
## Use A Layout
|
||||
|
||||
```ts
|
||||
slide.setLayout(layout);
|
||||
|
||||
const target = slide.placeholders.getItem(placeholderType);
|
||||
target.text = textValue;
|
||||
```
|
||||
|
||||
## Discover
|
||||
|
||||
```ts
|
||||
const layoutSummary = layout.placeholders.summary();
|
||||
const resolved = presentation.layouts.getById(layout.id);
|
||||
const importedGuides = layout.slideGuides;
|
||||
const actualPlaceholders = slide.placeholders.items;
|
||||
const emptyContentPlaceholders = slide.placeholders.editable;
|
||||
const allVisibleEmptyPlaceholders = slide.placeholders.unfilled;
|
||||
const missingLayoutSlots = slide.placeholders.availableFromLayout;
|
||||
```
|
||||
|
||||
These getters do not modify saved slide content.
|
||||
`items` includes filled placeholders. `editable` contains visible empty content
|
||||
shapes with positive bounds; `unfilled` also includes empty furniture.
|
||||
`availableFromLayout` contains missing layout slots for explicit creation.
|
||||
`getAll()` retains layout/master discovery, and `getItem()` creates a local
|
||||
instance when the requested placeholder exists only in the layout or master.
|
||||
|
||||
## Preview And Insert A Layout
|
||||
|
||||
```ts
|
||||
presentation.view.showPlaceholders();
|
||||
const image = await layout.export({ format: "png", scale: 0.25 });
|
||||
|
||||
const { slide } = presentation.slides.insert({
|
||||
after: selectedSlide,
|
||||
layoutId: layout.id,
|
||||
});
|
||||
slide.placeholders.addFromLayout();
|
||||
slide.placeholders.getItem("title").text = titleText;
|
||||
```
|
||||
|
||||
`addFromLayout()` creates missing content placeholders once and returns the
|
||||
created shapes. Adding a slide alone leaves placeholder creation to the caller.
|
||||
|
||||
## Cookbook
|
||||
|
||||
```ts
|
||||
// Branded title/body layout.
|
||||
const layout = presentation.layouts.add("Title Body");
|
||||
layout.placeholders.add({
|
||||
type: "title",
|
||||
index: 0,
|
||||
geometry: "textbox",
|
||||
position: { left: 72, top: 64, width: 920, height: 88 },
|
||||
text: "Title",
|
||||
});
|
||||
layout.placeholders.add({
|
||||
type: "body",
|
||||
index: 0,
|
||||
geometry: "roundRect",
|
||||
position: { left: 72, top: 180, width: 760, height: 360 },
|
||||
fill: "slate-50",
|
||||
line: { style: "solid", fill: "slate-200", width: 1 },
|
||||
});
|
||||
```
|
||||
|
||||
```ts
|
||||
// Use placeholders for repeated structure; override slide content locally.
|
||||
const slide = presentation.slides.add({ layout: "Title Body" });
|
||||
slide.placeholders.getItem("title").text = "Market overview";
|
||||
slide.placeholders.getItem("body").text = "Three editable points go here.";
|
||||
```
|
||||
|
||||
## Read A Rendered Slide's Layout
|
||||
|
||||
Each `presentation.render()` preview is an image Blob with a `.layout` JSON Blob.
|
||||
The paired files use the same stem, for example `slide-1.png` and
|
||||
`slide-1.layout.json`. A complete render replaces the previous render set;
|
||||
a subset render updates only the selected slides' pairs.
|
||||
|
||||
```ts
|
||||
const preview = await presentation.render({ slide: 0 });
|
||||
const layout = JSON.parse(await preview.layout.text());
|
||||
const title = layout.elements.find((element) => element.name === "cover-title");
|
||||
if (title) presentation.resolve(title.id).text = "Updated title";
|
||||
```
|
||||
|
||||
The default `openai.presentation.layout/v5` view is compact and uses pixels and
|
||||
canonical IDs. Request `slide.export({ format: "layout", detail: "full" })` for
|
||||
inherited paint layers, paragraph/run formatting, and table-cell details.
|
||||
Both views use the same IDs and editing coordinates:
|
||||
|
||||
| Field | Meaning |
|
||||
| ---------------------------------------------- | ------------------------------------------------------------------------------------------ |
|
||||
| `slide.id`, `slide.index` | Canonical slide ID and zero-based deck index. |
|
||||
| `slide.position` | Slide bounds: `{ left, top, width, height }`. |
|
||||
| `elements[].id`, `kind`, `name` | Canonical element ID, element kind, and optional authored name. |
|
||||
| `elements[].position` | Bounds using the same keys as edit configuration. |
|
||||
| `elements[].text`, `style` | Text and effective text styling, including `style.fontSize`. |
|
||||
| `elements[].crop`, `fit`, `mask` | Image crop, fitting, and geometry configuration. |
|
||||
| `elements[].scope`, `editable` | Owned slide content is editable; inherited layout/master content is identified separately. |
|
||||
| `tableCell.tableId`, `cells[].ownedElementIds` | Canonical IDs connecting a table, its cells, and cell-owned elements. |
|
||||
| `inheritedLayers[].id` | Canonical `ly/…` ID of a layout or master. |
|
||||
|
||||
Pass IDs from editable records to `presentation.resolve()` or
|
||||
`presentation.delete()`. In the full view, inherited content has `editable: false`; its IDs identify
|
||||
where the content came from and are not slide-owned edit targets. Raw PowerPoint
|
||||
IDs, asset IDs, and paragraph style IDs are not part of this public view.
|
||||
Generated
Vendored
+57
@@ -0,0 +1,57 @@
|
||||
# Masters
|
||||
|
||||
Masters share theme, background, and color-map structure with child layouts.
|
||||
|
||||
## Create And Link
|
||||
|
||||
```ts
|
||||
const master = presentation.masters.add(masterName);
|
||||
const layout = presentation.layouts.add(layoutName);
|
||||
|
||||
layout.setParentLayoutId(master.id);
|
||||
```
|
||||
|
||||
## Color Map And Background
|
||||
|
||||
```ts
|
||||
master.setColorMap(colorMapConfig);
|
||||
master.background.ref = backgroundRef;
|
||||
|
||||
const slide = presentation.slides.add();
|
||||
slide.setLayout(layout);
|
||||
```
|
||||
|
||||
## Master Inline Types
|
||||
|
||||
```ts
|
||||
type ColorMapConfig = Partial<Record<
|
||||
"bg1" | "tx1" | "bg2" | "tx2" | "accent1" | "accent2" | "accent3" | "accent4" | "accent5" | "accent6" | "hlink" | "folHlink",
|
||||
"bg1" | "tx1" | "bg2" | "tx2" | "accent1" | "accent2" | "accent3" | "accent4" | "accent5" | "accent6" | "hlink" | "folHlink"
|
||||
>>;
|
||||
```
|
||||
|
||||
## Resolve
|
||||
|
||||
```ts
|
||||
const resolved = presentation.layouts.getById(master.id);
|
||||
```
|
||||
|
||||
## Cookbook
|
||||
|
||||
```ts
|
||||
// Shared brand master with inherited layout.
|
||||
const master = presentation.masters.add("Brand Master");
|
||||
master.setColorMap({ bg1: "bg1", tx1: "tx1", accent1: "accent1" });
|
||||
master.background.ref = "bg1";
|
||||
|
||||
const layout = presentation.layouts.add("Brand Title");
|
||||
layout.setParentLayoutId(master.id);
|
||||
layout.placeholders.add({
|
||||
type: "title",
|
||||
geometry: "textbox",
|
||||
position: { left: 72, top: 72, width: 1000, height: 96 },
|
||||
});
|
||||
```
|
||||
|
||||
Before editing a master in an imported deck, inspect affected layouts and
|
||||
slides; master edits have intentional global blast radius.
|
||||
Generated
Vendored
+291
@@ -0,0 +1,291 @@
|
||||
# Presentation Facade
|
||||
|
||||
## Create And Load
|
||||
|
||||
```ts
|
||||
const presentation = Presentation.create({ slideSize });
|
||||
const loaded = await Presentation.load("input.pptx");
|
||||
const imported = Presentation.load(proto);
|
||||
```
|
||||
|
||||
## Create Inline Type
|
||||
|
||||
```ts
|
||||
type PresentationCreateOptions = {
|
||||
slideSize?: { width: number; height: number };
|
||||
};
|
||||
```
|
||||
|
||||
## Presentation Slide Collection
|
||||
|
||||
```ts
|
||||
const slide = presentation.slides.add({ layout, layoutId, background: { fill } });
|
||||
const inserted = presentation.slides.insert({ after, layout, layoutId });
|
||||
const byIndex = presentation.slides.getItem(slideIndex);
|
||||
presentation.slides.keep([0, 2, 4]);
|
||||
presentation.slides.reorder(orderedSlideIds);
|
||||
```
|
||||
|
||||
`keep` accepts an array of zero-based indexes or an array of canonical `sl/` IDs.
|
||||
It validates the selection against the current slide list, then preserves the
|
||||
selected slides in their existing relative order. Repeated selections are ignored;
|
||||
an empty array deletes all slides. `reorder` requires the complete desired order,
|
||||
with every current slide ID exactly once. Invalid selections fail before mutation.
|
||||
|
||||
## Presentation Slide Collection Inline Types
|
||||
|
||||
```ts
|
||||
type SlideAddOptions = {
|
||||
layout?: string;
|
||||
layoutId?: string;
|
||||
width?: number;
|
||||
height?: number;
|
||||
background?: { fill: FillConfig };
|
||||
};
|
||||
|
||||
type SlideInsertOptions = SlideAddOptions & {
|
||||
after?: Slide | number | null;
|
||||
};
|
||||
|
||||
interface SlideCollection {
|
||||
keep(selection: readonly number[] | readonly string[]): void;
|
||||
reorder(ids: readonly string[]): void;
|
||||
}
|
||||
|
||||
interface Presentation {
|
||||
delete(ids: string | readonly string[]): void;
|
||||
}
|
||||
```
|
||||
|
||||
## Discover And Edit
|
||||
|
||||
```ts
|
||||
const snapshot = await presentation.inspect({
|
||||
kind,
|
||||
search,
|
||||
limit,
|
||||
offset,
|
||||
});
|
||||
|
||||
const target = presentation.resolve(anchorId);
|
||||
const targets = presentation.resolve(anchorIds);
|
||||
presentation.delete(anchorIds);
|
||||
```
|
||||
|
||||
`delete` accepts one canonical ID or an array. It supports slides (`sl/`) and owned
|
||||
shapes, images, charts, tables, and embedded artifacts (`sh/`, `im/`, `ch/`, `tb/`,
|
||||
`ea/`). All IDs are validated first. Repeated IDs are ignored; selecting a slide
|
||||
and its children deletes the slide once. Inherited elements, notes, text ranges,
|
||||
and the presentation itself are not delete targets.
|
||||
|
||||
`inspect` returns stable anchor ids for slides, shapes, images, tables, charts, text ranges, speaker notes, and comment threads. `resolve` maps one anchor id to its facade, or an array of ids to facades in the same order. Layout records expose canonical `ly/...` IDs with `editable: false` for search and comparison; pass only `pr/`, `sl/`, `sh/`, `im/`, `tb/`, `ch/`, `nt/`, `th/`, and `tr/` anchors to `resolve`.
|
||||
|
||||
## Inspect
|
||||
|
||||
Use `presentation.inspect({ select, include, fileName })` with JSONPath over the
|
||||
public presentation tree. `include` is an exact array of typed fields, including
|
||||
nested paths such as `elements.text`. The query writes all selected records to
|
||||
NDJSON in the session output directory; ordinary printing shows the count and
|
||||
file metadata. See [Inspect](./inspect.md) and the
|
||||
[inspection JSON Schema](./inspect.schema.json) for content and layout queries.
|
||||
|
||||
## Help
|
||||
|
||||
```ts
|
||||
const help = presentation.help(query, {
|
||||
search,
|
||||
include,
|
||||
maxChars,
|
||||
});
|
||||
```
|
||||
|
||||
## Help Inline Type
|
||||
|
||||
```ts
|
||||
type PresentationHelpOptions = {
|
||||
search?: string;
|
||||
include?: string[]; // common: ["index", "examples", "notes"]
|
||||
maxChars?: number;
|
||||
};
|
||||
```
|
||||
|
||||
## Presentation View
|
||||
|
||||
```ts
|
||||
presentation.view.showGridlines();
|
||||
presentation.view.showGuides();
|
||||
presentation.view.showPlaceholders();
|
||||
|
||||
const gridlinesVisible = presentation.view.gridlinesVisible;
|
||||
const guidesVisible = presentation.view.guidesVisible;
|
||||
const placeholdersVisible = presentation.view.placeholdersVisible;
|
||||
const horizontalGridSpacingEmu = presentation.view.gridSpacingCxEmu;
|
||||
const verticalGridSpacingEmu = presentation.view.gridSpacingCyEmu;
|
||||
|
||||
presentation.view.hideGridlines();
|
||||
presentation.view.hideGuides();
|
||||
presentation.view.hidePlaceholders();
|
||||
|
||||
const nextGridlineState = presentation.view.toggleGridlines();
|
||||
const nextGuideState = presentation.view.toggleGuides();
|
||||
const nextPlaceholderState = presentation.view.togglePlaceholders();
|
||||
```
|
||||
|
||||
## Render And Export
|
||||
|
||||
```ts
|
||||
const overview = await presentation.render({ montage: true, fileName: "overview.png" });
|
||||
const selectedPreviews = await presentation.render({ slide: [0, 2] }); // PNG/layout pairs
|
||||
const allPreviews = await presentation.render(); // pairs in deck order
|
||||
const firstPreview = await presentation.render({ slide: 0 }); // one image Blob with .layout
|
||||
const pptxBlob = await presentation.export({ format: "pptx", fileName: "presentation.pptx" });
|
||||
const deckPdfBlob = await presentation.export({ format: "pdf" });
|
||||
const slidePdfBlob = await presentation.export({ slide, format: "pdf" });
|
||||
const layoutBlob = await slide.export({ format: "layout" });
|
||||
const proto = presentation.toProto();
|
||||
```
|
||||
|
||||
### Montage overview
|
||||
|
||||
`render({ montage: true })` includes every slide in deck order, regardless of
|
||||
which slide is active. It returns one image Blob without per-slide layout files.
|
||||
The default format is PNG and the default filename is `presentation-montage.png`.
|
||||
A custom `fileName` names the overview. In an Artifact Session, it is published
|
||||
as one render output under the session output directory.
|
||||
|
||||
Read the montage and content inspection first, then render selected slides for
|
||||
full-size PNGs and companion layout JSON files. A montage cannot combine with
|
||||
`slide`; use a separate selected render for detailed text and layout review.
|
||||
|
||||
Pass a montage options object to configure the grid. Dimensions are pixels before
|
||||
`scale`. Defaults are 320 pixels per slide, 16 pixels of padding and gap, and
|
||||
`ceil(sqrt(slideCount))` columns. Slides retain their aspect ratios; each row uses
|
||||
its tallest slide's height. `montage.width` sets the total width and overrides
|
||||
`slideWidth`. `montage.format` overrides the outer raster format. Widths and scale
|
||||
must be positive and finite, columns must be a positive integer, and padding and
|
||||
gap must be nonnegative and finite. Montages support PNG, JPEG, and WebP.
|
||||
|
||||
### Individual slide previews
|
||||
|
||||
Without a montage, `render()` defaults to every slide. An omitted `slide` or an
|
||||
index array returns an array of image Blobs; a single index or `Slide` returns one
|
||||
image Blob. Selected arrays preserve their requested order. Default output names
|
||||
use the actual slide number, such as `slide-1.png` and `slide-3.png` for
|
||||
`slide: [0, 2]`. A custom `fileName` requires a single selected slide.
|
||||
|
||||
Each returned image Blob has a `.layout` JSON Blob containing the same slide's
|
||||
layout view. Session outputs publish both files as render outputs with matching
|
||||
stems, such as `slide-1.png` and `slide-1.layout.json`. Full-deck renders replace
|
||||
both parts of the previous render set; subset renders update only the selected
|
||||
pairs. Rendering a montage does not replace that per-slide set. See
|
||||
[the layout reference](layout.spec.md#read-a-rendered-slides-layout) for the schema.
|
||||
An empty deck or empty selection returns `[]` for individual slide rendering.
|
||||
|
||||
Use `export({ format: "pptx" })` for the editable deliverable. Existing raster
|
||||
and montage `export` options remain supported; raster `export` without a montage
|
||||
retains its single-active-slide default.
|
||||
|
||||
Use `export({ format: "pdf" })` for one PDF containing every slide in deck order,
|
||||
or pass `slide` to export one slide as PDF.
|
||||
|
||||
## Render And Export Inline Types
|
||||
|
||||
```ts
|
||||
type PresentationMontageOptions = {
|
||||
format?: "png" | "jpeg" | "webp";
|
||||
width?: number;
|
||||
slideWidth?: number;
|
||||
padding?: number;
|
||||
gap?: number;
|
||||
background?: string;
|
||||
columns?: number;
|
||||
};
|
||||
|
||||
type PresentationExportOptions = {
|
||||
fileName?: string;
|
||||
slide?: Slide;
|
||||
format?: "png" | "jpeg" | "webp" | "pdf" | "layout" | "pptx";
|
||||
width?: number;
|
||||
height?: number;
|
||||
scale?: number;
|
||||
quality?: number;
|
||||
montage?: boolean | PresentationMontageOptions;
|
||||
};
|
||||
|
||||
type PresentationRenderOptions = Omit<
|
||||
PresentationExportOptions,
|
||||
"format" | "slide"
|
||||
> & {
|
||||
format?: "png" | "jpeg" | "webp";
|
||||
slide?: Slide | number | number[];
|
||||
};
|
||||
|
||||
type PresentationRenderResult = Blob & { layout: Blob };
|
||||
|
||||
interface Presentation {
|
||||
render(options: PresentationRenderOptions & { montage: true | PresentationMontageOptions; slide?: never }): Promise<Blob>;
|
||||
render(options: PresentationRenderOptions & { montage?: false; slide: Slide | number }): Promise<PresentationRenderResult>;
|
||||
render(options?: PresentationRenderOptions & { montage?: false; slide?: number[] }): Promise<PresentationRenderResult[]>;
|
||||
}
|
||||
```
|
||||
|
||||
## Scripts
|
||||
|
||||
```ts
|
||||
const result = presentation.scripts.run(scriptKind, scriptOptions);
|
||||
```
|
||||
|
||||
Scripts provide high-level authoring recipes. Use `presentation.help(...)` to discover available script keys and option shapes.
|
||||
|
||||
## Cookbook
|
||||
|
||||
```ts
|
||||
// New deck skeleton: create, set theme, add slides, render checks.
|
||||
const presentation = Presentation.create({
|
||||
slideSize: { width: 1280, height: 720 },
|
||||
});
|
||||
presentation.theme.colorScheme = {
|
||||
name: "Clean Product",
|
||||
themeColors: {
|
||||
accent1: "#2563eb",
|
||||
accent2: "#0f766e",
|
||||
accent3: "#f59e0b",
|
||||
accent4: "#dc2626",
|
||||
accent5: "#7c3aed",
|
||||
accent6: "#16a34a",
|
||||
bg1: "#ffffff",
|
||||
bg2: "#f8fafc",
|
||||
tx1: "#0f172a",
|
||||
tx2: "#475569",
|
||||
dk1: "#000000",
|
||||
dk2: "#1e293b",
|
||||
lt1: "#ffffff",
|
||||
lt2: "#e2e8f0",
|
||||
hlink: "#2563eb",
|
||||
folHlink: "#7c3aed",
|
||||
},
|
||||
};
|
||||
|
||||
const first = presentation.slides.add();
|
||||
const second = presentation.slides.add();
|
||||
const third = presentation.slides.add();
|
||||
|
||||
await presentation.render({
|
||||
slide: first,
|
||||
scale: 1,
|
||||
});
|
||||
const snapshot = await presentation.inspect({
|
||||
kind: "deck,slide,textbox,chart,table",
|
||||
limit: 20,
|
||||
});
|
||||
```
|
||||
|
||||
```ts
|
||||
// Existing deck: inspect first, then resolve exact anchors.
|
||||
const before = await presentation.inspect({
|
||||
kind: "slide,textbox,shape,image,table,chart,notes,thread,layout",
|
||||
search: "Customer growth",
|
||||
limit: 20,
|
||||
});
|
||||
const target = presentation.resolve(anchorIdFromBefore);
|
||||
```
|
||||
Generated
Vendored
+256
@@ -0,0 +1,256 @@
|
||||
# Rich Text
|
||||
|
||||
Shape text accepts strings, paragraph arrays, and structured runs.
|
||||
|
||||
## Set Text
|
||||
|
||||
```ts
|
||||
shape.text = textValue;
|
||||
shape.text = paragraphs;
|
||||
shape.text = structuredRuns;
|
||||
```
|
||||
|
||||
## Text Value Inline Types
|
||||
|
||||
```ts
|
||||
type TextValue = string | string[] | StructuredTextInput | Text;
|
||||
|
||||
type StructuredTextInput =
|
||||
| ParagraphRunsInput
|
||||
| StructuredTextParagraphInput
|
||||
| Array<ParagraphRunsInput | StructuredTextParagraphInput>;
|
||||
|
||||
type ParagraphRunsInput = Array<string | number | TextRunInput>;
|
||||
|
||||
type StructuredTextParagraphInput = {
|
||||
runs?: ParagraphRunsInput;
|
||||
bulletCharacter?: string;
|
||||
marginLeft?: number;
|
||||
indent?: number;
|
||||
spaceBefore?: number;
|
||||
spaceAfter?: number;
|
||||
styleId?: string;
|
||||
paragraphStyle?: Record<string, unknown>;
|
||||
};
|
||||
|
||||
type TextRunInput = {
|
||||
run: string;
|
||||
style?: {
|
||||
bold?: boolean;
|
||||
italic?: boolean;
|
||||
underline?: string;
|
||||
fontSize?: string;
|
||||
typeface?: string;
|
||||
color?: FillConfig;
|
||||
};
|
||||
textStyle?: TextRunInput["style"]; // Compatibility alias.
|
||||
link?: { uri: string; isExternal: boolean; action?: string };
|
||||
};
|
||||
```
|
||||
|
||||
`style` takes precedence as a complete object when both `style` and `textStyle` are supplied.
|
||||
|
||||
Structured run `fontSize` accepts unit strings such as `"20pt"` and `"28px"`.
|
||||
Shape text style setters use numeric pixels with `fontSize` and numeric points
|
||||
with `fontSizePt`.
|
||||
|
||||
## Structured Paragraphs
|
||||
|
||||
```ts
|
||||
shape.text.set([
|
||||
[{ run: "Status", style: { bold: true } }, { run: " review" }],
|
||||
{
|
||||
bulletCharacter: "•",
|
||||
marginLeft: 18,
|
||||
indent: -10,
|
||||
runs: [
|
||||
"Open the",
|
||||
{
|
||||
run: " rollout notes",
|
||||
style: { underline: "sng", color: "#2563eb" },
|
||||
link: { uri: "https://example.com", isExternal: true },
|
||||
},
|
||||
],
|
||||
},
|
||||
]);
|
||||
```
|
||||
|
||||
The paragraph-object form is the non-JSX peer of `<paragraph>...</paragraph>`. Use it when the text needs paragraph metadata plus authored runs.
|
||||
|
||||
## JSX Rich Text
|
||||
|
||||
```tsx
|
||||
/** @jsxRuntime automatic */
|
||||
|
||||
slide.compose(
|
||||
<column width="fill" height="hug" gap={8}>
|
||||
<paragraph width="fill" className="text-slate-950 text-2xl leading-tight">
|
||||
<run textStyle={{ bold: true }}>Status</run>
|
||||
<run> review</run>
|
||||
</paragraph>
|
||||
<paragraph
|
||||
width="fill"
|
||||
className="text-slate-950 text-2xl leading-tight"
|
||||
bulletCharacter="•"
|
||||
marginLeft={18}
|
||||
indent={-10}
|
||||
>
|
||||
Open the
|
||||
<run
|
||||
textStyle={{ underline: "sng", color: "#2563eb" }}
|
||||
link={{ uri: "https://example.com", isExternal: true }}
|
||||
>
|
||||
{" rollout notes"}
|
||||
</run>
|
||||
</paragraph>
|
||||
</column>,
|
||||
{
|
||||
frame: { left: 48, top: 40, width: 864, height: 160 },
|
||||
baseUnit: 8,
|
||||
},
|
||||
);
|
||||
```
|
||||
|
||||
## Shape Text Style
|
||||
|
||||
```ts
|
||||
shape.text.style = {
|
||||
styleName,
|
||||
fontSize: fontSizePx,
|
||||
color: colorConfig,
|
||||
fill: fillConfig,
|
||||
outline: lineConfig,
|
||||
alignment,
|
||||
verticalAlignment,
|
||||
autoFit: autoFitMode,
|
||||
wrap: wrapMode,
|
||||
insets,
|
||||
};
|
||||
```
|
||||
|
||||
Use grouped `text.style = { ... }` for whole-shape text formatting. Use single
|
||||
property setters for focused edits:
|
||||
|
||||
```ts
|
||||
shape.text.fontSize = fontSizePx;
|
||||
shape.text.color = colorConfig;
|
||||
shape.text.fill = fillConfig;
|
||||
shape.text.outline = lineConfig;
|
||||
shape.text.alignment = alignment;
|
||||
shape.text.verticalAlignment = verticalAlignment;
|
||||
shape.text.autoFit = autoFitMode;
|
||||
shape.text.wrap = wrapMode;
|
||||
shape.text.insets = 0; // Set all four sides; use an object for individual sides.
|
||||
```
|
||||
|
||||
`shape.text.color` uses `ColorConfig`. `shape.text.fill`, run `style.fill`,
|
||||
and text ranges accept the shared `FillConfig`, including linear and path
|
||||
gradients. `shape.text.outline`, run `style.outline`, and text ranges accept
|
||||
`LineConfig`; the outline line fill can be a solid, pattern, or gradient fill.
|
||||
|
||||
```ts
|
||||
shape.text.fill = {
|
||||
type: "gradient",
|
||||
gradientKind: "linear",
|
||||
angleDeg: 0,
|
||||
stops: [
|
||||
{ offset: 0, color: "#ff5a5f" },
|
||||
{ offset: 100000, color: "#4f46e5" },
|
||||
],
|
||||
};
|
||||
```
|
||||
|
||||
Path gradients use the same fill config with `gradientKind: "path"`, `pathType`, and optional
|
||||
`fillRect` in thousandths of a percent (`100000` = 100%).
|
||||
|
||||
## Text Style Inline Type
|
||||
|
||||
```ts
|
||||
type TextStyleConfig = {
|
||||
styleName?: string;
|
||||
className?: string;
|
||||
bold?: boolean;
|
||||
italic?: boolean;
|
||||
fontSize?: number;
|
||||
lineSpacing?: number;
|
||||
alignment?: "left" | "center" | "right" | "justify";
|
||||
verticalAlignment?: "top" | "middle" | "bottom";
|
||||
underline?: string;
|
||||
fill?: FillConfig;
|
||||
color?: ColorConfig;
|
||||
outline?: LineConfig;
|
||||
wrap?: "square" | "none";
|
||||
autoFit?: "none" | "shrinkText" | "resizeShapeToFitText";
|
||||
insets?: number | { top?: number; right?: number; bottom?: number; left?: number };
|
||||
typeface?: string;
|
||||
};
|
||||
```
|
||||
|
||||
## Ranges
|
||||
|
||||
```ts
|
||||
const range = shape.text.get(searchText);
|
||||
range.bold = isBold;
|
||||
range.italic = isItalic;
|
||||
range.fill = fillConfig;
|
||||
range.outline = lineConfig;
|
||||
range.link = linkConfig;
|
||||
|
||||
const fixedRange = shape.text.getRange(start, length);
|
||||
fixedRange.style = styleName;
|
||||
```
|
||||
|
||||
## Lists
|
||||
|
||||
```ts
|
||||
shape.text = listParagraphs;
|
||||
shape.text.style = listStyleName;
|
||||
shape.text.get(itemText).lineSpacing = lineSpacing;
|
||||
```
|
||||
|
||||
## Links
|
||||
|
||||
```ts
|
||||
shape.text.get(linkText).link = {
|
||||
uri,
|
||||
isExternal,
|
||||
};
|
||||
```
|
||||
|
||||
## Link Inline Type
|
||||
|
||||
```ts
|
||||
type LinkConfig = {
|
||||
uri: string;
|
||||
isExternal: boolean;
|
||||
action?: string;
|
||||
};
|
||||
```
|
||||
|
||||
## Cookbook
|
||||
|
||||
```ts
|
||||
// Title with emphasized suffix.
|
||||
shape.text.set([
|
||||
[
|
||||
{ run: "Revenue", style: { bold: true, color: "#0f172a" } },
|
||||
{ run: " momentum", style: { color: "#2563eb" } },
|
||||
],
|
||||
]);
|
||||
shape.text.style = { fontSize: 44, lineSpacing: 0.92 };
|
||||
```
|
||||
|
||||
```ts
|
||||
// Bullets with bold lead-ins.
|
||||
shape.text.set([
|
||||
{ bulletCharacter: "•", marginLeft: 22, indent: -12, runs: [{ run: "Quality:", style: { bold: true } }, " defect rate down 31%"] },
|
||||
{ bulletCharacter: "•", marginLeft: 22, indent: -12, runs: [{ run: "Speed:", style: { bold: true } }, " p95 latency under target"] },
|
||||
]);
|
||||
```
|
||||
|
||||
```ts
|
||||
// Edit one phrase inside imported text.
|
||||
const range = shape.text.get("legacy workflow");
|
||||
range.text = "new workflow";
|
||||
range.className = "text-emerald-700 font-bold";
|
||||
```
|
||||
Generated
Vendored
+279
@@ -0,0 +1,279 @@
|
||||
# Shapes
|
||||
|
||||
`slide.shapes` creates and edits drawable slide elements.
|
||||
|
||||
## Preset Shape
|
||||
|
||||
```ts
|
||||
const shape = slide.shapes.add({
|
||||
geometry,
|
||||
name,
|
||||
position,
|
||||
fill,
|
||||
line,
|
||||
adjustmentList,
|
||||
borderRadius,
|
||||
shadow,
|
||||
className,
|
||||
text: { text: textValue, style: { styleName: textStyleName, fontSize, bold, color } },
|
||||
});
|
||||
|
||||
shape.position = nextPosition;
|
||||
```
|
||||
|
||||
`geometry` is a string preset shape name, `"textbox"`, `"connector"`, or `"custom"`.
|
||||
Set `shape.text.insets = 0` to remove all text margins. A number sets every side;
|
||||
an object sets individual sides. Creation styles also accept `insets: 0`.
|
||||
|
||||
## Resolved From Inspect
|
||||
|
||||
```ts
|
||||
const shape = presentation.resolve("sh/a1b2c3d4");
|
||||
shape.text = "Updated copy";
|
||||
shape.fill = "accent1+18/90";
|
||||
shape.line = { style: "solid", fill: "slate-200", width: 1 };
|
||||
shape.geometry = "roundRect";
|
||||
shape.geometry; // "roundRect"
|
||||
shape.borderRadius = "rounded-2xl";
|
||||
shape.shadow = "shadow-sm";
|
||||
```
|
||||
|
||||
Use `presentation.inspect({ kind: "shape,textbox", search })` to find the
|
||||
`sh/...` anchor id. Keep the resolved facade type-aware; do not rebuild an
|
||||
imported shape unless the task requires a new object.
|
||||
|
||||
## Preset Shape Inline Type
|
||||
|
||||
```ts
|
||||
type ShapePresetName = string; // common: "textbox", "rect", "roundRect", "ellipse", "line", "rightArrow"
|
||||
// Full preset list: rg "SHAPE_GEOMETRY_NAME_TO_PROTO" src/models/presentation src/assets
|
||||
|
||||
type PositionConfig = {
|
||||
left?: number;
|
||||
top?: number;
|
||||
width?: number;
|
||||
height?: number;
|
||||
rotation?: number;
|
||||
horizontalFlip?: boolean;
|
||||
verticalFlip?: boolean;
|
||||
};
|
||||
|
||||
type PresetShapeConfig = {
|
||||
geometry: ShapePresetName;
|
||||
name?: string;
|
||||
position?: PositionConfig;
|
||||
fill?: FillConfig;
|
||||
line?: LineConfig;
|
||||
adjustmentList?: Array<{ name: string; formula: string }>;
|
||||
borderRadius?: number | string; // number = pixels; string = supported rounded-* token
|
||||
shadow?: string; // shadow token, "shadow-none", or custom "2px 7px 19px #000000/17"
|
||||
className?: string;
|
||||
text?: TextValue | { text: TextValue; style?: string | ShapeTextStyleConfig };
|
||||
placeholderType?: "title" | "subtitle" | "body" | "picture" | "chart" | "table" | "content";
|
||||
placeholderIndex?: number;
|
||||
};
|
||||
```
|
||||
|
||||
## Rounded Corners
|
||||
|
||||
Prefer `borderRadius` for rect-like rounded corners:
|
||||
|
||||
```ts
|
||||
slide.shapes.add({
|
||||
geometry: "rect",
|
||||
position: { left: 80, top: 120, width: 320, height: 160 },
|
||||
fill: "white",
|
||||
borderRadius: "rounded-2xl",
|
||||
});
|
||||
|
||||
shape.borderRadius = 24;
|
||||
```
|
||||
|
||||
Numbers are pixels. Strings use supported `rounded-*` tokens. `borderRadius`
|
||||
requires a shape with width/height and is supported for `rect`, `textbox`, and
|
||||
`roundRect`-like shapes. Use `adjustmentList` only when you need exact OpenXML
|
||||
preset adjustment formulas.
|
||||
|
||||
## Rounded Rect Adjustment
|
||||
|
||||
```ts
|
||||
const rounded = slide.shapes.add({
|
||||
geometry: "roundRect",
|
||||
position,
|
||||
fill,
|
||||
line,
|
||||
adjustmentList: [{ name: "adj", formula: adjustmentFormula }],
|
||||
});
|
||||
|
||||
rounded.adjustmentList = [{ name: "adj", formula: nextAdjustmentFormula }];
|
||||
rounded.adjustmentList;
|
||||
```
|
||||
|
||||
The `adj` value uses the OpenXML shape adjustment scale for the corner radius.
|
||||
|
||||
## Custom Path
|
||||
|
||||
```ts
|
||||
const custom = slide.shapes.add({
|
||||
geometry: "custom",
|
||||
position,
|
||||
fill,
|
||||
line,
|
||||
customPaths: [
|
||||
{
|
||||
width,
|
||||
height,
|
||||
commands,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
custom.customPaths = nextCustomPaths;
|
||||
custom.customPaths;
|
||||
```
|
||||
|
||||
Custom path coordinates use pixels in the path viewport.
|
||||
|
||||
## Bézier Curve
|
||||
|
||||
```ts
|
||||
const curve = slide.shapes.add({
|
||||
geometry: "custom",
|
||||
name: "Bezier curve",
|
||||
position: { left: 120, top: 190, width: 720, height: 240 },
|
||||
fill: "none",
|
||||
line: { style: "solid", fill: "#2463EB", width: 3 },
|
||||
customPaths: [{
|
||||
width: 720,
|
||||
height: 240,
|
||||
commands: [
|
||||
{ moveTo: { x: 0, y: 150 } },
|
||||
{ cubicBezTo: { x1: 100, y1: 150, x2: 120, y2: 0, x: 240, y: 40 } },
|
||||
{ cubicBezTo: { x1: 360, y1: 80, x2: 320, y2: 240, x: 480, y: 190 } },
|
||||
{ cubicBezTo: { x1: 620, y1: 130, x2: 620, y2: 80, x: 720, y: 100 } },
|
||||
],
|
||||
}],
|
||||
});
|
||||
```
|
||||
|
||||
Each cubic starts at the previous endpoint; `(x1, y1)` and `(x2, y2)` are its
|
||||
control points, and `(x, y)` is its endpoint. Omit `close` for an open curve.
|
||||
These coordinates define the curve directly; `adjustmentList` is for named
|
||||
geometry parameters. Use `slide.shapes.connect(..., { kind: "curved" })` for
|
||||
a connector that follows attached shapes.
|
||||
|
||||
## Custom Path Inline Type
|
||||
|
||||
```ts
|
||||
type CustomShapeConfig = Omit<PresetShapeConfig, "geometry"> & {
|
||||
geometry: "custom";
|
||||
customPaths: Array<{
|
||||
id?: string;
|
||||
width: number;
|
||||
height: number;
|
||||
commands: Array<
|
||||
| { moveTo: { x: number; y: number } }
|
||||
| { lineTo: { x: number; y: number } }
|
||||
| { quadBezTo: { x1: number; y1: number; x: number; y: number } }
|
||||
| { cubicBezTo: { x1: number; y1: number; x2: number; y2: number; x: number; y: number } }
|
||||
| { close: Record<string, never> }
|
||||
>;
|
||||
}>;
|
||||
};
|
||||
```
|
||||
|
||||
## Connector
|
||||
|
||||
```ts
|
||||
const connector = slide.shapes.connect(sourceShape, targetShape, {
|
||||
kind: "elbow",
|
||||
fromSide: "right",
|
||||
toSide: "left",
|
||||
line: { style: "solid", fill: "slate-400", width: 2 },
|
||||
head: { type: "arrow", width: "med", length: "med" },
|
||||
});
|
||||
```
|
||||
|
||||
Use [`connectors.md`](./connectors.md) for connector routing, side anchors,
|
||||
direct `geometry: "connector"` creation, arrowheads, and endpoint edits.
|
||||
|
||||
## Line Primitive Decision
|
||||
|
||||
| Need | Use |
|
||||
| --- | --- |
|
||||
| Divider inside compose JSX | `<rule stroke="slate-200" weight={1} />` |
|
||||
| Free-positioned line | `slide.shapes.add({ geometry: "line", position, fill: "none", line })` |
|
||||
| Freeform curve with Bézier control points | `slide.shapes.add({ geometry: "custom", position, fill: "none", line, customPaths })` |
|
||||
| Arrow connected to shapes | `slide.shapes.connect(fromShape, toShape, { line, head })` |
|
||||
| Border around a surface | shape or box `line={{ style: "solid", fill: "slate-200", width: 1 }}` |
|
||||
|
||||
## Shadows
|
||||
|
||||
Supported shadow tokens:
|
||||
|
||||
```text
|
||||
shadow-none, shadow-sm, shadow, shadow-md, shadow-lg, shadow-xl, shadow-2xl
|
||||
```
|
||||
|
||||
Custom shadow strings are also supported when the presentation has a theme
|
||||
context:
|
||||
|
||||
```ts
|
||||
shape.shadow = "shadow-md";
|
||||
shape.shadow = "2px 7px 19px #000000/17";
|
||||
shape.shadow = "shadow-none";
|
||||
```
|
||||
|
||||
## Ordering
|
||||
|
||||
```ts
|
||||
shape.bringToFront();
|
||||
shape.bringForward();
|
||||
shape.sendToBack();
|
||||
shape.sendBackward();
|
||||
```
|
||||
|
||||
These inherited methods also apply to images, tables, charts, embedded workbooks, and SmartArt. Forward/backward moves one position in the owning surface’s stack; front/back moves to an end.
|
||||
|
||||
## Cookbook
|
||||
|
||||
```ts
|
||||
// KPI metric surface.
|
||||
const metricSurface = slide.shapes.add({
|
||||
geometry: "roundRect",
|
||||
name: "kpi-surface",
|
||||
position: { left: 64, top: 132, width: 260, height: 148 },
|
||||
fill: "white",
|
||||
line: { style: "solid", fill: "slate-200", width: 1 },
|
||||
borderRadius: "rounded-2xl",
|
||||
shadow: "shadow-md",
|
||||
});
|
||||
metricSurface.text = "Revenue\n$12.4M";
|
||||
metricSurface.text.style = {
|
||||
className: "text-slate-950 text-2xl font-bold leading-tight",
|
||||
};
|
||||
```
|
||||
|
||||
```ts
|
||||
// Pill label.
|
||||
const pill = slide.shapes.add({
|
||||
geometry: "roundRect",
|
||||
position: { left: 64, top: 64, width: 148, height: 34 },
|
||||
fill: "emerald-50",
|
||||
line: { style: "solid", fill: "emerald-200", width: 1 },
|
||||
borderRadius: "rounded-full",
|
||||
});
|
||||
pill.text = "ON TRACK";
|
||||
pill.text.style = { className: "text-emerald-800 text-sm font-bold" };
|
||||
```
|
||||
|
||||
```ts
|
||||
// Directional connector between two shapes.
|
||||
slide.shapes.connect(sourceShape, targetShape, {
|
||||
kind: "elbow",
|
||||
fromSide: "right",
|
||||
toSide: "left",
|
||||
line: { style: "solid", fill: "slate-400", width: 2 },
|
||||
head: { type: "triangle", width: "sm", length: "sm" },
|
||||
});
|
||||
```
|
||||
Generated
Vendored
+199
@@ -0,0 +1,199 @@
|
||||
# Slide Facade
|
||||
|
||||
## Slide Show Visibility
|
||||
|
||||
```ts
|
||||
slide.hidden = isHidden;
|
||||
```
|
||||
|
||||
Hidden slides stay in the deck but are skipped during a slide show.
|
||||
|
||||
## Content Collections
|
||||
|
||||
```ts
|
||||
const shape = slide.shapes.add(shapeConfig);
|
||||
const image = slide.images.add(imageConfig);
|
||||
const table = slide.tables.add(tableConfig);
|
||||
const chart = slide.charts.add(chartType, chartConfig);
|
||||
```
|
||||
|
||||
## Content Config Pointers
|
||||
|
||||
```ts
|
||||
type ShapeConfig = PresetShapeConfig | CustomShapeConfig | ConnectorConfig; // see shapes.spec.md
|
||||
type ImageConfig = ImageAddOptions; // see images.spec.md
|
||||
type TableConfig = TableAddOptions | TableCellValue[][]; // see tables.spec.md
|
||||
type ChartConfig = {
|
||||
position?: { left?: number; top?: number; width?: number; height?: number };
|
||||
title?: string;
|
||||
categories?: string[];
|
||||
series?: Array<{ name: string; values?: number[] }>;
|
||||
}; // see charts.spec.md for axes, legend, labels, and series styling
|
||||
```
|
||||
|
||||
## Background
|
||||
|
||||
```ts
|
||||
const slide = presentation.slides.add({ background: { fill: fillConfig } });
|
||||
slide.background.fill = fillConfig;
|
||||
```
|
||||
|
||||
`fillConfig` accepts theme color strings, hex strings, solid configs, gradient configs, pattern configs, and image-fill configs.
|
||||
|
||||
## Layouts And Placeholders
|
||||
|
||||
```ts
|
||||
slide.setLayout(layout);
|
||||
|
||||
const placeholder = slide.placeholders.getItem(placeholderName);
|
||||
placeholder.text = placeholderText;
|
||||
placeholder.text.style = placeholderStyleName;
|
||||
```
|
||||
|
||||
```ts
|
||||
const actualPlaceholders = slide.placeholders.items;
|
||||
const emptyContentPlaceholders = slide.placeholders.editable;
|
||||
const allVisibleEmptyPlaceholders = slide.placeholders.unfilled;
|
||||
const missingLayoutSlots = slide.placeholders.availableFromLayout;
|
||||
const createdPlaceholders = slide.placeholders.addFromLayout();
|
||||
```
|
||||
|
||||
## Frame And Export
|
||||
|
||||
```ts
|
||||
const frame = slide.frame;
|
||||
const preview = await slide.export({ format, scale });
|
||||
const pdf = await slide.export({ format: "pdf" });
|
||||
```
|
||||
|
||||
## Compose Layout
|
||||
|
||||
```tsx
|
||||
/** @jsxRuntime automatic */
|
||||
|
||||
slide.compose(
|
||||
<row width="fill" height="fill" gap={20}>
|
||||
<column width={340} height="fill" gap={12}>
|
||||
<paragraph name="summary" className="text-slate-950 text-3xl font-bold">
|
||||
Summary
|
||||
</paragraph>
|
||||
<paragraph className="text-slate-600 text-sm">
|
||||
Compose-first layouts stay readable and export cleanly.
|
||||
</paragraph>
|
||||
</column>
|
||||
<box name="surface" width="fill" height="fill" padding={16} fill="#ffffff">
|
||||
<column height="fill" gap={10}>
|
||||
<rule stroke="#0f172a" weight={2} />
|
||||
</column>
|
||||
</box>
|
||||
</row>,
|
||||
{
|
||||
frame: { left: 48, top: 40, width: 864, height: 460 },
|
||||
baseUnit: 8,
|
||||
},
|
||||
);
|
||||
```
|
||||
|
||||
`slide.compose(...)` accepts either compose helper nodes or a JSX-authored tree.
|
||||
It still returns the materialized elements. Use `name` on materializing nodes
|
||||
when the slide needs stable inspect or layout-export anchors.
|
||||
|
||||
## Export Inline Type
|
||||
|
||||
```ts
|
||||
type SlideExportOptions = {
|
||||
format?: "png" | "jpeg" | "webp" | "pdf" | "layout";
|
||||
width?: number;
|
||||
height?: number;
|
||||
scale?: number;
|
||||
quality?: number;
|
||||
};
|
||||
```
|
||||
|
||||
`format: "layout"` exports the composed layout tree alongside the materialized slide elements. That is the most useful export when you need stable names, hierarchy paths, and resolved text for follow-up targeting.
|
||||
|
||||
## Auto Layout
|
||||
|
||||
```ts
|
||||
slide.autoLayout(shapes, {
|
||||
direction,
|
||||
frame,
|
||||
align,
|
||||
horizontalGap,
|
||||
verticalGap,
|
||||
horizontalPadding,
|
||||
verticalPadding,
|
||||
});
|
||||
```
|
||||
|
||||
## Auto Layout Inline Type
|
||||
|
||||
```ts
|
||||
type AutoLayoutOptions = {
|
||||
direction?: "horizontal" | "vertical";
|
||||
frame?:
|
||||
| "slide"
|
||||
| Shape
|
||||
| { left: number; top: number; width: number; height: number };
|
||||
align?:
|
||||
| "center"
|
||||
| "topLeft"
|
||||
| "topCenter"
|
||||
| "topRight"
|
||||
| "left"
|
||||
| "right"
|
||||
| "bottomLeft"
|
||||
| "bottomCenter"
|
||||
| "bottomRight";
|
||||
horizontalGap?: number | "auto";
|
||||
verticalGap?: number | "auto";
|
||||
horizontalPadding?: number;
|
||||
verticalPadding?: number;
|
||||
};
|
||||
```
|
||||
|
||||
## Speaker Notes
|
||||
|
||||
```ts
|
||||
slide.speakerNotes.text = notesText;
|
||||
slide.speakerNotes.setVisible(visible);
|
||||
```
|
||||
|
||||
## Visual QA Loop
|
||||
|
||||
```ts
|
||||
const preview = await slide.export({ format: "png", scale: 2 });
|
||||
const layout = await slide.export({ format: "layout" });
|
||||
const after = await presentation.inspect({
|
||||
kind: "slide,textbox,shape,image,table,chart,notes",
|
||||
target: { id: slideAnchorId, beforeLines: 2, afterLines: 8 },
|
||||
maxChars: 4000,
|
||||
});
|
||||
```
|
||||
|
||||
Check the PNG for clipping, overlap, weak contrast, illegible text, bad image
|
||||
crops, accidental rasterized labels, and off-canvas elements. Check the layout
|
||||
export or inspect output for stable `name` values on important nodes.
|
||||
|
||||
## Cookbook
|
||||
|
||||
```ts
|
||||
// Gradient background plus editable content.
|
||||
slide.background.fill = "linear(180deg, slate-950 0%, blue-950 100%)";
|
||||
const title = slide.shapes.add({
|
||||
geometry: "textbox",
|
||||
name: "title",
|
||||
position: { left: 72, top: 72, width: 760, height: 120 },
|
||||
fill: "none",
|
||||
line: { style: "solid", fill: "none", width: 0 },
|
||||
});
|
||||
title.text = "Editable headline";
|
||||
title.text.style = { fontSize: 44, bold: true, color: "white" };
|
||||
```
|
||||
|
||||
```ts
|
||||
// Clone rhythm from another slide, then change content.
|
||||
const next = sourceSlide.duplicate();
|
||||
next.moveTo(3);
|
||||
next.placeholders.getItem("title").text = "Updated section title";
|
||||
```
|
||||
Generated
Vendored
+48
@@ -0,0 +1,48 @@
|
||||
# Speaker Notes
|
||||
|
||||
Speaker notes live on `slide.speakerNotes`.
|
||||
|
||||
## Set Text
|
||||
|
||||
```ts
|
||||
const speakerNotes = slide.speakerNotes;
|
||||
speakerNotes.text = notesText;
|
||||
const savedText = speakerNotes.text;
|
||||
```
|
||||
|
||||
## Notes Text Inline Type
|
||||
|
||||
```ts
|
||||
type NotesTextValue = string | string[] | StructuredTextInput;
|
||||
|
||||
type TextRunInput = {
|
||||
run: string;
|
||||
style?: { bold?: boolean; italic?: boolean; fontSize?: string; color?: FillConfig };
|
||||
textStyle?: TextRunInput["style"]; // Compatibility alias.
|
||||
};
|
||||
```
|
||||
|
||||
## Visibility And Clearing
|
||||
|
||||
```ts
|
||||
speakerNotes.setVisible(visible);
|
||||
const visibleState = speakerNotes.isVisible();
|
||||
speakerNotes.clear();
|
||||
```
|
||||
|
||||
## Cookbook
|
||||
|
||||
```ts
|
||||
// Structured presenter notes.
|
||||
slide.speakerNotes.text = [
|
||||
"Open with the customer problem, not the feature list.",
|
||||
"Call out the chart source before discussing the slope.",
|
||||
"Pause for questions before the implementation timeline.",
|
||||
];
|
||||
slide.speakerNotes.setVisible(true);
|
||||
```
|
||||
|
||||
```ts
|
||||
// Append without deleting imported notes.
|
||||
slide.speakerNotes.append("\nFollow-up: confirm launch date with PM.");
|
||||
```
|
||||
Generated
Vendored
+85
@@ -0,0 +1,85 @@
|
||||
# Named Text Styles
|
||||
|
||||
`presentation.styles` stores reusable text styles for shapes and text ranges.
|
||||
|
||||
## Style Surface Map
|
||||
|
||||
| Need | API |
|
||||
| --- | --- |
|
||||
| Deck-level tokenized text style ids | `presentation.theme.textStyles({...})` |
|
||||
| Slide-scoped generated text style ids | `slide.theme.textStyles({...})` |
|
||||
| Explicit named styles by facade | `presentation.styles.add(name)` |
|
||||
|
||||
## Built-In Styles
|
||||
|
||||
```ts
|
||||
const styles = presentation.styles;
|
||||
const style = styles.get(styleName);
|
||||
const summary = styles.describe(styleName);
|
||||
const allStyles = styles.describe();
|
||||
```
|
||||
|
||||
## Custom Style
|
||||
|
||||
```ts
|
||||
const custom = presentation.styles.add(styleName);
|
||||
custom.description = styleDescription;
|
||||
custom.color = styleColor;
|
||||
custom.bold = isBold;
|
||||
custom.italic = isItalic;
|
||||
custom.fontSize = fontSizePx;
|
||||
custom.alignment = alignment;
|
||||
```
|
||||
|
||||
## Named Style Facade Fields
|
||||
|
||||
```ts
|
||||
type NamedStyleFacade = {
|
||||
description?: string;
|
||||
usageHint?: string;
|
||||
bold?: boolean;
|
||||
italic?: boolean;
|
||||
fontSize?: number;
|
||||
alignment?: "left" | "center" | "right" | "justify";
|
||||
underline?: string;
|
||||
color?: ColorConfig;
|
||||
};
|
||||
```
|
||||
|
||||
Use broader `TextStyleConfig` objects on `shape.text.style = { ... }`,
|
||||
`presentation.theme.textStyles(...)`, and `slide.theme.textStyles(...)`.
|
||||
|
||||
## Use A Style
|
||||
|
||||
```ts
|
||||
shape.text = textValue;
|
||||
shape.text.style = styleName;
|
||||
|
||||
const range = shape.text.get(rangeText);
|
||||
range.style = styleName;
|
||||
```
|
||||
|
||||
Named styles are block-level for paragraph style assignments and range-level for selected text ranges.
|
||||
|
||||
## Cookbook
|
||||
|
||||
```ts
|
||||
// Deck-level type scale.
|
||||
const display = presentation.styles.add("Display");
|
||||
display.fontSize = 52;
|
||||
display.bold = true;
|
||||
display.color = "#0f172a";
|
||||
display.usageHint = "Hero and section titles";
|
||||
|
||||
const body = presentation.styles.add("Body");
|
||||
body.fontSize = 20;
|
||||
body.color = "#475569";
|
||||
body.usageHint = "Readable body copy";
|
||||
```
|
||||
|
||||
```ts
|
||||
// Apply a style, then emphasize one range.
|
||||
shape.text = "Revenue accelerated across enterprise accounts.";
|
||||
shape.text.style = "Body";
|
||||
shape.text.get("Revenue").style = "Display";
|
||||
```
|
||||
Generated
Vendored
+198
@@ -0,0 +1,198 @@
|
||||
# Tables
|
||||
|
||||
`slide.tables` creates and edits PowerPoint-style tables.
|
||||
|
||||
## Resolved From Inspect
|
||||
|
||||
```ts
|
||||
const table = presentation.resolve("tb/d4e5f6a7");
|
||||
table.cells.set(1, 2, "$4.2M");
|
||||
table.getCell(1, 2).text.style = "Body Small";
|
||||
table.borders.assign({ style: "solid", fill: "slate-200", width: 1 });
|
||||
```
|
||||
|
||||
Use `presentation.inspect({ kind: "table", search })` to find the `tb/...`
|
||||
anchor id. If an imported table resolves as an image, preserve it as an image or
|
||||
rebuild it as a native table intentionally.
|
||||
|
||||
## Add Table
|
||||
|
||||
```ts
|
||||
const table = slide.tables.add({
|
||||
rows,
|
||||
columns,
|
||||
left,
|
||||
top,
|
||||
width,
|
||||
height,
|
||||
columnTracks: [fr(2), fr(1), fixed(120)],
|
||||
values,
|
||||
});
|
||||
```
|
||||
|
||||
Primitive matrices and structured text runs are accepted for `values`. Use `columnTracks` with `fr(...)` and `fixed(...)` when a table should fill its frame with proportional columns. Use `columnWidths` only for explicit pixel widths.
|
||||
|
||||
## Table Inline Types
|
||||
|
||||
```ts
|
||||
type TableAddOptions = {
|
||||
rows: number;
|
||||
columns: number;
|
||||
left?: number;
|
||||
top?: number;
|
||||
width?: number;
|
||||
height?: number;
|
||||
values?: TableCellValue[][];
|
||||
columnTracks?: TableColumnTrack[];
|
||||
columnWidths?: number[];
|
||||
};
|
||||
|
||||
type TableColumnTrack =
|
||||
| { mode: "fr"; value: number }
|
||||
| { mode: "fixed"; value: number };
|
||||
|
||||
type TableCellValue = string | number | string[] | StructuredTextInput | Text;
|
||||
```
|
||||
|
||||
## Cells
|
||||
|
||||
```ts
|
||||
const cell = table.getCell(rowIndex, columnIndex);
|
||||
cell.value = cellValue;
|
||||
cell.fill = fillConfig;
|
||||
cell.text.style = textStyleName;
|
||||
|
||||
table.cells.set(rowIndex, columnIndex, textObjectOrValue);
|
||||
```
|
||||
|
||||
## Ranges And Merges
|
||||
|
||||
```ts
|
||||
table.merge({
|
||||
startRow,
|
||||
endRow,
|
||||
startColumn,
|
||||
endColumn,
|
||||
});
|
||||
|
||||
const range = table.cells.block(rangeConfig);
|
||||
range.fill = fillConfig;
|
||||
range.textStyle.bold = isBold;
|
||||
range.textStyle.color = textColor;
|
||||
range.textStyle.fontSize = fontSizePx;
|
||||
range.borders = borderConfig;
|
||||
|
||||
table.unmerge({ startRow, endRow, startColumn, endColumn });
|
||||
```
|
||||
|
||||
## Insert And Delete Rows Or Columns
|
||||
|
||||
```ts
|
||||
table.insertRows({ index: rowIndex, count: 2 });
|
||||
table.deleteRows({ index: rowIndex, count: 1 });
|
||||
table.insertColumns({ index: columnIndex });
|
||||
table.deleteColumns({ index: columnIndex });
|
||||
```
|
||||
|
||||
## Range And Merge Inline Types
|
||||
|
||||
```ts
|
||||
type TableMergeRange = {
|
||||
startRow: number;
|
||||
endRow: number;
|
||||
startColumn: number;
|
||||
endColumn: number;
|
||||
};
|
||||
|
||||
type TableCellRangeConfig = {
|
||||
row: number;
|
||||
column: number;
|
||||
rowCount: number;
|
||||
columnCount: number;
|
||||
};
|
||||
```
|
||||
|
||||
## Style
|
||||
|
||||
```ts
|
||||
table.style = tableStyleId;
|
||||
table.styleOptions = tableStyleOptions;
|
||||
table.columnTracks = [fr(2), fr(1), fixed(120)];
|
||||
table.rows[0].height = headerHeightPx;
|
||||
table.columns.get(columnIndex).width = columnWidthPx;
|
||||
table.borders.assign(borderConfig);
|
||||
|
||||
table.cells.block({ row, column, rowCount, columnCount }).assign({
|
||||
fill,
|
||||
textStyle,
|
||||
borders,
|
||||
margins,
|
||||
anchor,
|
||||
horizontalOverflow,
|
||||
});
|
||||
```
|
||||
|
||||
## Style Inline Types
|
||||
|
||||
```ts
|
||||
type TableStyleOptions = {
|
||||
headerRow?: boolean;
|
||||
totalRow?: boolean;
|
||||
firstColumn?: boolean;
|
||||
lastColumn?: boolean;
|
||||
bandedRows?: boolean;
|
||||
bandedColumns?: boolean;
|
||||
};
|
||||
|
||||
type TableBorderLineConfig = {
|
||||
style?: "solid" | "dashed" | "dotted" | "dash-dot" | "dash-dot-dot" | string;
|
||||
width?: number;
|
||||
fill?: FillConfig;
|
||||
color?: FillConfig;
|
||||
};
|
||||
```
|
||||
|
||||
## Cookbook
|
||||
|
||||
```ts
|
||||
// Compact KPI table.
|
||||
const table = slide.tables.add({
|
||||
rows: 4,
|
||||
columns: 3,
|
||||
left: 96,
|
||||
top: 168,
|
||||
width: 680,
|
||||
height: 220,
|
||||
values: [
|
||||
["Metric", "Current", "Delta"],
|
||||
["Revenue", "$12.4M", "+18%"],
|
||||
["Retention", "94%", "+3 pts"],
|
||||
["Latency", "182 ms", "-22 ms"],
|
||||
],
|
||||
});
|
||||
table.styleOptions = { headerRow: true, bandedRows: true };
|
||||
table.getCell(0, 0).fill = "slate-950";
|
||||
table.getCell(0, 1).fill = "slate-950";
|
||||
table.getCell(0, 2).fill = "slate-950";
|
||||
table.borders.assign({ style: "solid", fill: "slate-200", width: 1 });
|
||||
```
|
||||
|
||||
```ts
|
||||
// Spanning title row.
|
||||
table.merge({ startRow: 0, endRow: 0, startColumn: 0, endColumn: 2 });
|
||||
table.getCell(0, 0).value = "Regional performance";
|
||||
table.getCell(0, 0).text.style = "title";
|
||||
```
|
||||
|
||||
```ts
|
||||
// Highlight a cell range.
|
||||
const riskRange = table.cells.block({
|
||||
row: 2,
|
||||
column: 2,
|
||||
rowCount: 2,
|
||||
columnCount: 1,
|
||||
});
|
||||
riskRange.fill = "amber-50";
|
||||
riskRange.textStyle.color = "#92400e";
|
||||
riskRange.textStyle.bold = true;
|
||||
```
|
||||
Generated
Vendored
+97
@@ -0,0 +1,97 @@
|
||||
# Theme
|
||||
|
||||
Themes provide default fonts, named colors, and text style tokens.
|
||||
|
||||
## Default Font
|
||||
|
||||
```ts
|
||||
presentation.theme.defaultFont = "Aptos";
|
||||
```
|
||||
|
||||
New presentations default to Aptos. Set `defaultFont: string` once during setup
|
||||
to choose the theme's Latin heading and body font. Shape text with no explicit
|
||||
`typeface` inherits the theme; a local `typeface` overrides it. The choice persists with
|
||||
the presentation. Imported presentations retain their existing font schemes;
|
||||
changing `defaultFont` preserves language-specific font mappings.
|
||||
|
||||
## Color Scheme
|
||||
|
||||
```ts
|
||||
presentation.theme.colorScheme = {
|
||||
name: themeName,
|
||||
themeColors,
|
||||
};
|
||||
|
||||
const hexMap = presentation.theme.hexColorMap;
|
||||
```
|
||||
|
||||
`themeColors` maps every theme color name to a color config value. Assigning
|
||||
`presentation.theme.colorScheme` replaces the active scheme, so provide the
|
||||
full map.
|
||||
|
||||
## Color Scheme Inline Type
|
||||
|
||||
```ts
|
||||
type ThemeColorName =
|
||||
| "accent1" | "accent2" | "accent3" | "accent4" | "accent5" | "accent6"
|
||||
| "bg1" | "bg2" | "tx1" | "tx2" | "dk1" | "lt1" | "dk2" | "lt2"
|
||||
| "hlink" | "folHlink";
|
||||
|
||||
type ColorSchemeConfig = {
|
||||
name: string;
|
||||
themeColors: Record<ThemeColorName, ColorConfig>;
|
||||
};
|
||||
```
|
||||
|
||||
## Theme Colors In Content
|
||||
|
||||
```ts
|
||||
const shape = slide.shapes.add({
|
||||
geometry,
|
||||
position,
|
||||
fill: themeColorName,
|
||||
line: { style: lineStyle, fill: lineColor, width: lineWidthPx },
|
||||
});
|
||||
```
|
||||
|
||||
## Text Styles
|
||||
|
||||
```ts
|
||||
const styles = slide.theme.textStyles({
|
||||
[styleName]: textStyleConfig,
|
||||
});
|
||||
```
|
||||
|
||||
## Cookbook
|
||||
|
||||
```ts
|
||||
// Business/product palette.
|
||||
presentation.theme.colorScheme = {
|
||||
name: "Product Editorial",
|
||||
themeColors: {
|
||||
accent1: "#2563eb",
|
||||
accent2: "#0f766e",
|
||||
accent3: "#f59e0b",
|
||||
accent4: "#dc2626",
|
||||
accent5: "#7c3aed",
|
||||
accent6: "#16a34a",
|
||||
bg1: "#ffffff",
|
||||
bg2: "#f8fafc",
|
||||
tx1: "#0f172a",
|
||||
tx2: "#475569",
|
||||
dk1: "#000000",
|
||||
dk2: "#1e293b",
|
||||
lt1: "#ffffff",
|
||||
lt2: "#e2e8f0",
|
||||
hlink: "#2563eb",
|
||||
folHlink: "#7c3aed",
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
```ts
|
||||
// Use theme tokens in content so later theme changes flow through.
|
||||
slide.background.fill = "bg1";
|
||||
shape.fill = "accent1";
|
||||
shape.text.style = { color: "tx1" };
|
||||
```
|
||||
Generated
Vendored
+447
@@ -0,0 +1,447 @@
|
||||
# Presentation Token Reference
|
||||
|
||||
This reference covers the Tailwind-like tokens supported by presentation
|
||||
shapes, text, and JSX. These are presentation tokens, not browser CSS.
|
||||
|
||||
## Where Tokens Work
|
||||
|
||||
| Surface | Token entry |
|
||||
| --- | --- |
|
||||
| Shape/box fill | `fill="sky-500"`, `fill="rose-500/80"` |
|
||||
| Shape/box line | `line={{ style: "solid", fill: "slate-200", width: 1 }}` |
|
||||
| Shape/box radius | `borderRadius="rounded-xl"` |
|
||||
| Image radius | `borderRadius="rounded-2xl"` |
|
||||
| Shape shadow | `shadow="shadow-md"` |
|
||||
| Shape/box className | `className="bg-white rounded-xl shadow-sm"` |
|
||||
| Text className | `className="text-slate-700 text-lg font-bold leading-tight"` |
|
||||
| Imperative shape | `shape.className = "bg-sky-50 rounded-lg shadow"` |
|
||||
| Imperative text | `shape.text.style = { className: "text-slate-800 text-xl leading-relaxed" }` |
|
||||
| Text range | `shape.text.get("Total").className = "text-emerald-600 font-bold"` |
|
||||
|
||||
Explicit props override `className` on JSX nodes. For example,
|
||||
`<box className="bg-slate-900" fill="white" />` uses the explicit `fill`.
|
||||
`className` is only for visual/text tokens. Use real JSX props for layout:
|
||||
`width`, `height`, `gap`, `padding`, `align`, and `justify`.
|
||||
|
||||
## Decision Table
|
||||
|
||||
| Need | Use |
|
||||
| --- | --- |
|
||||
| Common shape styling | `className="bg-white rounded-xl shadow-sm"` |
|
||||
| Exact fill or gradient | `fill="#0f172a"` or `fill="linear(135deg, #fff 0%, sky-100 100%)"` |
|
||||
| Exact line | `line={{ style: "solid", fill: "slate-200", width: 1 }}` |
|
||||
| Common text styling | `className="text-slate-700 text-lg font-bold leading-tight"` |
|
||||
| Exact text style | `style="font: 700 22px Inter; color: #334155; leading: 1.25; wrap: none"` |
|
||||
| Inline emphasis | `<run textStyle={{ bold: true, color: "sky-600" }}>...</run>` |
|
||||
| Layout | real props such as `gap={24}`, `padding={{ x: 32, y: 24 }}`, `align="center"` |
|
||||
|
||||
## Token Cookbook
|
||||
|
||||
Transparent overlay:
|
||||
|
||||
```tsx
|
||||
<shape geometry="rect" width="fill" height="fill" fill="black/45" />
|
||||
<paragraph className="text-white/80 text-xl">Readable over an image</paragraph>
|
||||
```
|
||||
|
||||
Theme color with a transform:
|
||||
|
||||
```tsx
|
||||
<box fill="accent1+18/90" />
|
||||
<paragraph style="font: 700 18px Inter; color: tx1-10/85; wrap: none">
|
||||
Theme-aware text
|
||||
</paragraph>
|
||||
```
|
||||
|
||||
`+` lightens, `-` darkens, and `/` sets opacity. The suffix accepts unit
|
||||
fractions, numbers, or percentages: `accent1+0.18/0.9`, `accent1+18/90`, and
|
||||
`accent1+18%/90%` are equivalent.
|
||||
|
||||
Soft surface with exact line:
|
||||
|
||||
```tsx
|
||||
<box
|
||||
fill="slate-50"
|
||||
line={{ style: "solid", fill: "slate-200", width: 1 }}
|
||||
borderRadius="rounded-2xl"
|
||||
shadow="shadow-sm"
|
||||
/>
|
||||
```
|
||||
|
||||
No fill, visible stroke:
|
||||
|
||||
```tsx
|
||||
<shape
|
||||
geometry="ellipse"
|
||||
fill="none"
|
||||
line={{ style: "dashed", fill: "sky-500/70", width: 2 }}
|
||||
width={96}
|
||||
height={96}
|
||||
/>
|
||||
```
|
||||
|
||||
Gradient background plus transparent edge:
|
||||
|
||||
```tsx
|
||||
<box fill="linear(135deg, #ffffff 0%, sky-100 58%, #ffffff/0 100%)" />
|
||||
```
|
||||
|
||||
Radial highlight:
|
||||
|
||||
```tsx
|
||||
<shape
|
||||
geometry="ellipse"
|
||||
fill="radial(white/80 0%, emerald-200/45 48%, emerald-700/0 100%)"
|
||||
width={420}
|
||||
height={260}
|
||||
/>
|
||||
```
|
||||
|
||||
Custom shadow:
|
||||
|
||||
```tsx
|
||||
<box fill="white" borderRadius="rounded-2xl" shadow="2px 7px 19px #000000/17" />
|
||||
```
|
||||
|
||||
Exact text style string:
|
||||
|
||||
```tsx
|
||||
<paragraph style="font: 700 24px Inter; color: #334155; leading: 1.2; wrap: none">
|
||||
One-line label
|
||||
</paragraph>
|
||||
```
|
||||
|
||||
Tokenized text with arbitrary size and leading:
|
||||
|
||||
```tsx
|
||||
<paragraph className="text-slate-950 text-[32px] font-bold leading-[1.12]">
|
||||
Precise headline
|
||||
</paragraph>
|
||||
```
|
||||
|
||||
## Color Tokens
|
||||
|
||||
Color tokens can be used directly as fill/color strings or through `bg-*` and
|
||||
`text-*` class names.
|
||||
|
||||
```tsx
|
||||
<box fill="slate-950" line={{ style: "solid", fill: "slate-700", width: 1 }} />
|
||||
<box className="bg-sky-50 rounded-xl shadow-sm" />
|
||||
<paragraph className="text-slate-700 text-lg">Readable text</paragraph>
|
||||
```
|
||||
|
||||
Alpha suffixes are supported:
|
||||
|
||||
```tsx
|
||||
<shape geometry="rect" fill="black/45" width="fill" height="fill" />
|
||||
<paragraph className="text-white/80 text-xl">Muted overlay text</paragraph>
|
||||
<box className="bg-rose-500/75 rounded-full" />
|
||||
```
|
||||
|
||||
Theme colors and aliases are supported as color strings:
|
||||
|
||||
```tsx
|
||||
<box fill="accent1" />
|
||||
<box fill="accent2+20/80" />
|
||||
<paragraph style="font: 600 18px Inter; color: text1/80; wrap: none">
|
||||
Uses the presentation theme text color
|
||||
</paragraph>
|
||||
```
|
||||
|
||||
Theme names:
|
||||
|
||||
```text
|
||||
accent1, accent2, accent3, accent4, accent5, accent6,
|
||||
bg1, bg2, tx1, tx2, dk1, dk2, lt1, lt2, hlink, folHlink
|
||||
```
|
||||
|
||||
Aliases:
|
||||
|
||||
```text
|
||||
background1 -> bg1
|
||||
background2 -> bg2
|
||||
text1 -> tx1
|
||||
text2 -> tx2
|
||||
dark1 -> dk1
|
||||
dark2 -> dk2
|
||||
light1 -> lt1
|
||||
light2 -> lt2
|
||||
```
|
||||
|
||||
Supported color names:
|
||||
|
||||
| Family | Tokens |
|
||||
| --- | --- |
|
||||
| Neutrals | `slate`, `gray`, `zinc`, `neutral`, `stone` |
|
||||
| Warm | `red`, `orange`, `amber`, `yellow`, `lime` |
|
||||
| Green/blue | `green`, `emerald`, `teal`, `cyan`, `sky`, `blue` |
|
||||
| Violet/pink | `indigo`, `violet`, `purple`, `fuchsia`, `pink`, `rose` |
|
||||
| Additional muted sets | `mauve`, `mist`, `olive`, `taupe` |
|
||||
| Singletons | `black`, `white` |
|
||||
|
||||
For palette families, supported shades are:
|
||||
|
||||
```text
|
||||
50, 100, 200, 300, 400, 500, 600, 700, 800, 900, 950
|
||||
```
|
||||
|
||||
Use `family-shade`, for example `slate-50`, `slate-900`, `sky-500`,
|
||||
`emerald-700`, or `rose-950`.
|
||||
|
||||
Alpha values accept percent-like numbers, percentages, or unit fractions:
|
||||
|
||||
```text
|
||||
sky-500/80
|
||||
sky-500/80%
|
||||
sky-500/0.8
|
||||
black/10
|
||||
white/65
|
||||
```
|
||||
|
||||
Hex, short hex, RGB, RGBA, and `transparent` are accepted:
|
||||
|
||||
```tsx
|
||||
<box fill="#0F172A/12" />
|
||||
<box fill="#0F172A1F" />
|
||||
<box fill="rgb(15 23 42 / 12%)" />
|
||||
<box fill="rgba(15, 23, 42, 0.12)" />
|
||||
<shape geometry="rect" fill="transparent" />
|
||||
```
|
||||
|
||||
Use `fill="none"` when the object should have no fill. Use
|
||||
`fill="transparent"` or `#00000000` when the object should keep an editable
|
||||
transparent solid fill. Express transparent and no-fill cases with the explicit
|
||||
`fill` prop.
|
||||
|
||||
## Gradient Strings
|
||||
|
||||
Gradient fill strings are supported wherever `FillConfig` strings are accepted.
|
||||
Use them for editable vector backgrounds and surfaces:
|
||||
|
||||
```tsx
|
||||
<box fill="linear(135deg, #ffffff 0%, sky-100 55%, #ffffff/0 100%)" />
|
||||
<shape geometry="ellipse" fill="radial(#ffffff 0%, emerald-200 48%, emerald-700 100%)" />
|
||||
```
|
||||
|
||||
`linear(...)` accepts an optional angle first. `radial(...)` is a path gradient.
|
||||
Stops use color plus optional offset percentages.
|
||||
|
||||
Offsets are optional; when omitted, stops are distributed evenly:
|
||||
|
||||
```tsx
|
||||
<box fill="linear(slate-950, blue-800, sky-400)" />
|
||||
```
|
||||
|
||||
Use explicit offsets when a narrow band or fade matters:
|
||||
|
||||
```tsx
|
||||
<box fill="linear(90deg, black/80 0%, black/36 42%, black/0 100%)" />
|
||||
<shape geometry="ellipse" fill="radial(accent1+35/55 0%, accent1/12 58%, accent1/0 100%)" />
|
||||
```
|
||||
|
||||
## Shape Class Tokens
|
||||
|
||||
Shape and box `className` supports:
|
||||
|
||||
```text
|
||||
bg-*
|
||||
rounded
|
||||
rounded-none
|
||||
rounded-sm
|
||||
rounded-md
|
||||
rounded-lg
|
||||
rounded-xl
|
||||
rounded-2xl
|
||||
rounded-3xl
|
||||
rounded-full
|
||||
shadow-none
|
||||
shadow-sm
|
||||
shadow
|
||||
shadow-md
|
||||
shadow-lg
|
||||
shadow-xl
|
||||
shadow-2xl
|
||||
```
|
||||
|
||||
Example:
|
||||
|
||||
```tsx
|
||||
<box
|
||||
width="fill"
|
||||
height={180}
|
||||
className="bg-white rounded-xl shadow-md"
|
||||
line={{ style: "solid", fill: "slate-200", width: 1 }}
|
||||
/>
|
||||
```
|
||||
|
||||
Radius values:
|
||||
|
||||
| Token | Radius |
|
||||
| --- | ---: |
|
||||
| `rounded-none` | `0px` |
|
||||
| `rounded-sm` | `2px` |
|
||||
| `rounded` | `4px` |
|
||||
| `rounded-md` | `6px` |
|
||||
| `rounded-lg` | `8px` |
|
||||
| `rounded-xl` | `12px` |
|
||||
| `rounded-2xl` | `16px` |
|
||||
| `rounded-3xl` | `24px` |
|
||||
| `rounded-full` | `9999px` |
|
||||
|
||||
Shadow tokens:
|
||||
|
||||
```text
|
||||
shadow-none, shadow-sm, shadow, shadow-md, shadow-lg, shadow-xl, shadow-2xl
|
||||
```
|
||||
|
||||
Custom shadow strings are also supported on `shadow`:
|
||||
|
||||
```tsx
|
||||
<box shadow="2px 7px 19px #000000/17" />
|
||||
```
|
||||
|
||||
## Text Class Tokens
|
||||
|
||||
Text `className` supports color, size, weight, italic, and leading:
|
||||
|
||||
```tsx
|
||||
<paragraph className="text-slate-950 text-5xl font-bold leading-tight">
|
||||
Large headline
|
||||
</paragraph>
|
||||
<paragraph className="text-slate-600 text-lg leading-relaxed">
|
||||
Body copy with looser line spacing.
|
||||
</paragraph>
|
||||
```
|
||||
|
||||
Text sizes:
|
||||
|
||||
| Token | Size |
|
||||
| --- | ---: |
|
||||
| `text-xs` | `12px` |
|
||||
| `text-sm` | `14px` |
|
||||
| `text-base` | `16px` |
|
||||
| `text-lg` | `18px` |
|
||||
| `text-xl` | `20px` |
|
||||
| `text-2xl` | `24px` |
|
||||
| `text-3xl` | `30px` |
|
||||
| `text-4xl` | `36px` |
|
||||
| `text-5xl` | `48px` |
|
||||
| `text-6xl` | `60px` |
|
||||
| `text-[32px]` | arbitrary positive pixel size |
|
||||
|
||||
Font weight tokens:
|
||||
|
||||
| Bold flag | Tokens |
|
||||
| --- | --- |
|
||||
| `true` | `font-semibold`, `font-bold`, `font-black` |
|
||||
| `false` | `font-thin`, `font-extralight`, `font-light`, `font-normal`, `font-medium`, `font-extrabold` |
|
||||
|
||||
Font weight maps to a boolean bold flag, not numeric weights. Use only
|
||||
`font-semibold`, `font-bold`, or `font-black` when the text should be bold. Use
|
||||
`font-normal` when the text should not be bold. `font-extrabold` maps to the
|
||||
non-bold side because exact `500`/`600`/`700`/`800` differences are not
|
||||
preserved.
|
||||
|
||||
`italic` sets italic text.
|
||||
|
||||
Leading tokens:
|
||||
|
||||
| Token | Line spacing |
|
||||
| --- | ---: |
|
||||
| `leading-none` | `1` |
|
||||
| `leading-tight` | `1.25` |
|
||||
| `leading-snug` | `1.375` |
|
||||
| `leading-normal` | `1.5` |
|
||||
| `leading-relaxed` | `1.625` |
|
||||
| `leading-loose` | `2` |
|
||||
| `leading-3` through `leading-10` | `12px` through `40px`, converted against current font size |
|
||||
| `leading-[1.35]` | arbitrary multiplier |
|
||||
| `leading-[150%]` | percentage multiplier |
|
||||
| `leading-[28px]` | absolute pixels, converted against current font size |
|
||||
|
||||
When using absolute leading such as `leading-7` or `leading-[28px]`, put the
|
||||
text size token before the leading token in the class string so conversion uses
|
||||
the intended font size:
|
||||
|
||||
```tsx
|
||||
<paragraph className="text-2xl leading-8">24px text with 32px leading</paragraph>
|
||||
```
|
||||
|
||||
## Direct Props Versus Class Names
|
||||
|
||||
Use direct props when a value is part of the object schema:
|
||||
|
||||
```tsx
|
||||
<shape
|
||||
geometry="rect"
|
||||
fill="emerald-500"
|
||||
line={{ style: "solid", fill: "emerald-700", width: 1 }}
|
||||
borderRadius="rounded-lg"
|
||||
shadow="shadow-sm"
|
||||
width={160}
|
||||
height={96}
|
||||
/>
|
||||
```
|
||||
|
||||
Use `className` when grouping common style tokens:
|
||||
|
||||
```tsx
|
||||
<box className="bg-emerald-50 rounded-xl shadow-sm">
|
||||
<paragraph className="text-emerald-900 text-xl font-bold leading-tight">
|
||||
Compact token styling
|
||||
</paragraph>
|
||||
</box>
|
||||
```
|
||||
|
||||
Use object `style` for exact text settings that tokens do not cover:
|
||||
|
||||
```tsx
|
||||
<paragraph
|
||||
style={{
|
||||
typeface: "Aptos",
|
||||
fontSize: 22,
|
||||
color: "slate-700",
|
||||
alignment: "center",
|
||||
lineSpacing: 1.2,
|
||||
}}
|
||||
>
|
||||
Exact text config
|
||||
</paragraph>
|
||||
```
|
||||
|
||||
Use a compact style string when the exact settings fit on one line:
|
||||
|
||||
```tsx
|
||||
<paragraph style="font: italic 600 20px Aptos; color: slate-700; leading: 1.25; align: center">
|
||||
Compact exact text config
|
||||
</paragraph>
|
||||
```
|
||||
|
||||
Supported text style declarations:
|
||||
|
||||
```text
|
||||
font, size, font-size, family, font-family, typeface,
|
||||
weight, font-weight, italic, font-style, color, fill,
|
||||
leading, align, alignment, wrap, underline, inset, insets,
|
||||
padding, autofit, auto-fit
|
||||
```
|
||||
|
||||
Use `leading`, not `line-height`, in style strings.
|
||||
|
||||
## ClassName Scope
|
||||
|
||||
The token parser covers visual and text styling. JSX layout props represent
|
||||
layout utilities such as padding, gap, width, height, flex flow, grid flow,
|
||||
alignment, and distribution:
|
||||
|
||||
```tsx
|
||||
<row width="fill" height="fill" gap={24} align="center" justify="between" />
|
||||
<box padding={{ x: 32, y: 24 }} line={{ style: "solid", fill: "slate-200", width: 1 }} />
|
||||
```
|
||||
|
||||
## Source References
|
||||
|
||||
- `src/models/presentation/utils/tailwind/*.ts`: token parsers.
|
||||
- `src/models/presentation/utils/tailwind/tailwind-colors.generated.ts`: full
|
||||
color token map.
|
||||
- `tests/presentation/tailwind-tokens.sanity.spec.ts`: visual token coverage.
|
||||
Generated
Vendored
+503
@@ -0,0 +1,503 @@
|
||||
# Using artifact_tool APIs (JavaScript)
|
||||
|
||||
Library version: 2.8.58+
|
||||
|
||||
## Required Imports + Startup
|
||||
|
||||
Import existing workbook only when needed:
|
||||
```js
|
||||
import { FileBlob, SpreadsheetFile } from "@oai/artifact-tool";
|
||||
|
||||
const input = await FileBlob.load("path/to/input.xlsx");
|
||||
const workbook = await SpreadsheetFile.importXlsx(input);
|
||||
```
|
||||
|
||||
Import CSV text directly when the source or intermediate data is CSV:
|
||||
```js
|
||||
import fs from "node:fs/promises";
|
||||
import { Workbook } from "@oai/artifact-tool";
|
||||
|
||||
const csvText = await fs.readFile("path/to/input.csv", "utf8");
|
||||
const workbook = await Workbook.fromCSV(csvText, { sheetName: "Sheet1" });
|
||||
```
|
||||
Prefer `Workbook.fromCSV(...)` over hand-parsing CSV rows; clean or analyze CSV with Python/Node first only when needed.
|
||||
CSV fields import as strings. Convert intended numeric/date columns before calculations; number formatting alone does not convert text to numbers.
|
||||
|
||||
Create new workbook:
|
||||
|
||||
```js
|
||||
import fs from "node:fs/promises";
|
||||
import { SpreadsheetFile, Workbook } from "@oai/artifact-tool";
|
||||
|
||||
const workbook = Workbook.create();
|
||||
const sheet = workbook.worksheets.add("Inputs");
|
||||
```
|
||||
|
||||
Final export:
|
||||
```js
|
||||
await fs.mkdir(outputDir, { recursive: true });
|
||||
const output = await SpreadsheetFile.exportXlsx(workbook);
|
||||
await output.save(`${outputDir}/output.xlsx`);
|
||||
```
|
||||
|
||||
## Build Patterns
|
||||
- Prefer block writes (`range.values`, `range.formulas`) over per-cell loops. Normally match the matrix shape to the target range (e.g. "D4:M4" → 1×10). To intentionally expand a larger matrix from an anchor, target a single cell or use `range.write(matrix)`.
|
||||
- `range.values = [[value]]` repeats that value across the range; range.formulas does not broadcast a single formula. For merged ranges, write to the top-left cell or `mergedRange.values = [[value]]` where `mergedRange` is a single merged range.
|
||||
- Seed scalar formulas once, then `fillDown()` / `fillRight()`. For dynamic-array formulas (`SEQUENCE`, `UNIQUE`, `FILTER`, `SORT`, `VSTACK`, `HSTACK`), write only the anchor cell and let the result spill after.
|
||||
- Use `range.displayFormulas` plus `range.formulaInfos` when you need to understand a spill child or a data-table output cell.
|
||||
- Formulas calculate automatically.
|
||||
- Prefer real `Date` objects for sortable/charted/formula date columns.
|
||||
- Number and date formats must be applied explicitly (for example `yyyy-mm-dd`).
|
||||
- Use JSON-serializable values for non-Date cells: `string | number | boolean | null`.
|
||||
- If a cell is intended to display literal text that begins with `=`, write it as a value prefixed with a single quote (for example `'=B2*C2`). This includes formula descriptions, validation examples, and labels; do not write these cells through `range.formulas`.
|
||||
- Create every worksheet referenced by formulas before writing any cross-sheet formulas.
|
||||
- Verify with `await workbook.inspect(...)`; use `workbook.help(...)` only when the quick surface below is insufficient.
|
||||
|
||||
## Conventions
|
||||
- Use camelCase API names and option keys.
|
||||
- Cell/range addressing: A1 notation (`sheet.getRange("A1:C10")`).
|
||||
- Drawing anchors (`sheet.charts`, `sheet.shapes`, `sheet.images`): 0-based `{ row, col }`.
|
||||
- Drawing offsets/extents use pixels (`rowOffsetPx`, `colOffsetPx`, `widthPx`, `heightPx`).
|
||||
|
||||
## API Discovery Policy (Strict)
|
||||
- Use this quick API surface first.
|
||||
- Use `workbook.help(...)` only when the supplied public documentation leaves a required operation unclear. Start with one bounded exact feature/path lookup, such as `range.dataValidation` or `chart.series.add`.
|
||||
- If that lookup returns no useful match, one bounded reformulation is allowed. Stop after those two attempts; do not repeat similar queries, inspect package internals/prototypes/nearby tests, or invent enum values and setters. Use a documented equivalent that preserves the task.
|
||||
- The examples below are alternatives for the relevant operation, not a discovery checklist to execute in full.
|
||||
- `render` can be used to examine an existing workbook visually and for visual verifications.
|
||||
|
||||
## Supported Formulas
|
||||
- Look up formula syntax with `fx.<formula>`, e.g. `workbook.help("fx.PMT", { include: "index,examples,notes", maxChars: 3000 })`. A help entry does not guarantee working calculation or Excel export.
|
||||
- To browse a family of formulas, use `fx.*` with a category regex. Useful categories: `financial`, `math-trig`, `statistical`, `lookup-reference`, `logical`, `text`, `date-time`, `information`, `engineering`, `database`.
|
||||
- For intent-based lookup, use a short natural query plus a narrow `search` regex of likely functions.
|
||||
- Keep `maxChars` bounded; if results are noisy, narrow `search` rather than issuing many similar queries.
|
||||
|
||||
Useful `help` calls:
|
||||
```js
|
||||
console.log(workbook.help("shape.add", { include: "examples,notes" }).ndjson);
|
||||
console.log(
|
||||
workbook.help("*", {
|
||||
search: "fill|borders|autofit",
|
||||
include: "index,examples,notes",
|
||||
maxChars: 6000,
|
||||
}).ndjson,
|
||||
);
|
||||
console.log(workbook.help("fx.PMT", { include: "index,examples,notes" }).ndjson);
|
||||
console.log(workbook.help("fx.*", { search: "financial", include: "index,examples", maxChars: 4000 }).ndjson);
|
||||
console.log(workbook.help("fx.*", { search: "math-trig", include: "index,examples", maxChars: 4000 }).ndjson);
|
||||
console.log(workbook.help("lookup with fallback", { search: "XLOOKUP|INDEX|MATCH|IFERROR", include: "index,examples,notes", maxChars: 4000 }).ndjson);
|
||||
```
|
||||
|
||||
### Known formula/export limitations (not exhaustive)
|
||||
If a formula fails, use a verified equivalent that preserves the intended result.
|
||||
|
||||
Known issues:
|
||||
- Avoid `MAP`, `REDUCE`, `SCAN`, `MAKEARRAY`, `GROUPBY`, `PIVOTBY`. Use helper cells and supported scalar formulas;
|
||||
- Prefix `XLOOKUP`, `TEXTJOIN`, `MINIFS`, `MAXIFS`, `IFS`, and `RANK.EQ` with `_xlfn.`, including nested calls: e.g. `'=_xlfn.TEXTJOIN(", ",TRUE,B2:C2)'`.
|
||||
- For `LET`, `LAMBDA`, `BYROW`, and `BYCOL`, prefix function names with `_xlfn.` and every LET/LAMBDA local-variable declaration and reference with `_xlpm.`.
|
||||
- PivotTable APIs exist, but XLSX export is unreliable; use formula summaries.
|
||||
- `COUNTIF` / `COUNTIFS` with an empty-string criterion can miss blank cells, even in bounded ranges. For unconditional blank counts, use `COUNTBLANK(range)`.
|
||||
|
||||
|
||||
## Reading existing/imported workbooks
|
||||
- On existing/imported workbooks, get a compact summary via `inspect` to understand what already exists and where.
|
||||
- Prefer `inspect(...)` for workbook understanding and discovery across broad areas.
|
||||
- Prefer direct getters like `range.formulas` when you already know the target range and need the exact rectangular formula matrix.
|
||||
- If formula locations are unknown, prefer `inspect({ kind: "formula", ... })` over reading `range.formulas` across a very large area.
|
||||
- Prefer to set `maxChars`, `tableMaxRows`, `tableMaxCols`, and/or `maxResults` to prevent large dumps of data.
|
||||
- For suspicious or high-impact outputs, use `workbook.trace("Sheet!A1")` to audit the dependency tree from final output/check cell back to source cells. Trace output can be large, so summarize by depth/node count before logging.
|
||||
|
||||
### Inspect for workbook understanding
|
||||
- Compact summary:
|
||||
```js
|
||||
await wb.inspect({
|
||||
kind: "workbook,sheet,table",
|
||||
maxChars: 6000,
|
||||
tableMaxRows: 6,
|
||||
tableMaxCols: 6,
|
||||
tableMaxCellChars: 80,
|
||||
});
|
||||
```
|
||||
- Quick overview of sheet ids and names: `await wb.inspect({ kind: "sheet", include: "id,name" })`
|
||||
- Formula discovery in a targeted area: `await wb.inspect({ kind: "formula", sheetId: firstSheetName, range: "A1:Z30", maxChars: 2500, options: {maxResults:50} })`
|
||||
- Checking existing styles in a targeted area: `await wb.inspect({ kind: "computedStyle", sheetId: firstSheetName, range: "A1:E10", maxChars: 2500 })`
|
||||
- Common `kind` tokens: `workbook`, `sheet`, `table`, `region`, `match`, `formula`, `thread`, `computedStyle`, `definedName`, `drawing`
|
||||
- Inspects can also be used to zoom in on specific areas, especially for target edits:
|
||||
```js
|
||||
await wb.inspect({
|
||||
kind: "region",
|
||||
sheetId: firstSheetName,
|
||||
range: "A1:Z30",
|
||||
maxChars: 2500,
|
||||
});
|
||||
```
|
||||
- Inspect output may include JSON records with `"id"` values (for example `"ws/r5qsk5"`), which you can resolve back to workbook objects with `wb.resolve(...)`:
|
||||
- `wb.resolve("ws/...")` -> worksheet
|
||||
- `wb.resolve("th/...")` -> comment thread
|
||||
|
||||
## Known Gotchas (Do not repeat)
|
||||
- Do not set undocumented attributes on remote objects.
|
||||
- `Workbook.create()` starts with no sheets; add one before calling `getActiveWorksheet()`.
|
||||
- Create every worksheet referenced by formulas before writing cross-sheet formulas.
|
||||
- Prefer bounded formula ranges with explicit start/end rows, e.g. `$A$6:$A$205`. Full-column references such as `A:A`, `$A:$A`, or `Sheet!B:B` can be truncated to each column's populated extent: unequal extents can make `COUNTIFS` / `SUMIFS` return `#VALUE!`, and `ROWS` / `INDEX` can differ from Excel.
|
||||
- If export fails, isolate the cause by checkpoint-export after major blocks to isolate the cause: base sheets, values/formulas, formatting, conditional formatting, tables, charts/rendering. For charts, first simplify optional styling first: nested border configs, custom chart axis/series mutations, broad autofit/formatting, then nonessential drawings.
|
||||
|
||||
## Additional feature-specific notes
|
||||
|
||||
### Merging cells
|
||||
- `range.merge()` merges the target range into one cell; `range.merge(true)` merges across each row in the target range.
|
||||
- `range.unmerge()` reverses a merge.
|
||||
For example:
|
||||
```js
|
||||
const range = sheet.getRange("I23:N24");
|
||||
range.merge();
|
||||
range.values = [["Source note spanning the recommendation panel"]];
|
||||
```
|
||||
|
||||
## Quick API Surface (High-Value + Common)
|
||||
|
||||
### Core workbook/file APIs
|
||||
- `import { FileBlob, SpreadsheetFile, Workbook } from "@oai/artifact-tool"`
|
||||
- `const workbook = Workbook.create()` to create an empty workbook
|
||||
- `const sheet = workbook.worksheets.add("Sheet1")` to add a sheet
|
||||
- `const workbook = await SpreadsheetFile.importXlsx(arrayBufferOrFileBlob)`
|
||||
- `const xlsx = await SpreadsheetFile.exportXlsx(workbook); await xlsx.save("output.xlsx")`
|
||||
- `const inspect = await workbook.inspect({ kind: "sheet", include: "id,name", sheetId, range: "A1:C10" })`
|
||||
- `const help = workbook.help("worksheet.getRange", { include: "index,examples" })`
|
||||
- Preferred: `const preview = await workbook.render({ sheetName: "Sheet1", autoCrop: "all", scale: 1, format: "png" })`
|
||||
- To get the bytes and/or save the blob to file:
|
||||
```js
|
||||
const previewBytes = new Uint8Array(await preview.arrayBuffer());
|
||||
await fs.writeFile(`${outputDir}/preview.png`, previewBytes);
|
||||
```
|
||||
- `const workbook = await Workbook.fromCSV(csvText, { sheetName: "Sheet1" })`
|
||||
- `await workbook.fromCSV(csvText, { sheetName: "ImportedData" })` requires an empty workbook; it does not append CSV to a populated workbook. Prefer static `Workbook.fromCSV(...)`.
|
||||
|
||||
### Worksheet selection/creation
|
||||
- `workbook.worksheets.add(name)`
|
||||
- `workbook.worksheets.getItem(name)`
|
||||
- `workbook.worksheets.getItemAt(index)`
|
||||
- `workbook.worksheets.getActiveWorksheet()` (only after at least one sheet exists)
|
||||
|
||||
### Worksheet operations
|
||||
- `sheet.getRange("A1:C10")`, `sheet.getRangeByIndexes(startRow, startCol, rowCount, colCount)`, `sheet.getCell(row, col)`
|
||||
- `sheet.getUsedRange(valuesOnly?)`
|
||||
- `sheet.mergeCells("A1:C1")`, `sheet.unmergeCells("A1:C1")`
|
||||
- `sheet.freezePanes.freezeRows(rowCount)`, `sheet.freezePanes.freezeColumns(columnCount)`, `sheet.freezePanes.unfreeze()`
|
||||
- `sheet.tabColor = "#1F4E78"` sets the worksheet tab color; the getter returns a `Color` object.
|
||||
- `sheet.tables`, `sheet.charts`, `sheet.sparklineGroups` (`sheet.sparklines` alias), `sheet.shapes`, `sheet.images`
|
||||
- `sheet.showGridLines = false`
|
||||
- `sheet.dataTables`, `sheet.conditionalFormattings`, `sheet.dataValidations`
|
||||
- `sheet.deleteAllDrawings()` removes all drawings, including charts, shapes, and images.
|
||||
|
||||
### Range values/formulas
|
||||
- `const range = sheet.getRange("A1:C10")`
|
||||
- `range.values = [[...], ...]` (2D matrix of values).
|
||||
- `range.formulas = [["=..."], ...]`
|
||||
- `range.formulasR1C1 = [["=RC[-1]*2"]]`
|
||||
- To read: `range.values` / `range.formulas` / `range.displayFormulas` / `range.formulaInfos` (for spill/array formulas)
|
||||
- `range.write(matrixOrPayload)` (auto-sizes/spills from anchor as needed)
|
||||
- `range.writeValues(matrixOrRows)`
|
||||
- `range.fillDown()`, `range.fillRight()`
|
||||
- `sheet.getRange("D2").formulas = [["=..."]]`
|
||||
- `sheet.getRange("D2:D200").fillDown()`
|
||||
- `range.clear({ applyTo: "contents" | "formats" | "all" })` clears cell contents, formatting, or both; drawings remain.
|
||||
- `range.copyFrom(sourceRange, "values" | "formulas" | "all")`. Prefer matching shapes; a single-cell value source can broadcast across a larger destination.
|
||||
- `range.copyTo(destRange, "values" | "formulas" | "all")`
|
||||
- `range.offset(rowOffset, colOffset)`, `range.resize(rowCount, columnCount)`, `range.getCurrentRegion()`, `range.getRow(i)`, `range.getColumn(j)`
|
||||
- `range.getRangeByIndexes(startRow, startCol, rowCount, colCount)`, `range.getCell(row, col)` (relative to the range)
|
||||
- `range.merge()`, `range.merge(true)` to merge across, `range.unmerge()`
|
||||
|
||||
### Formatting
|
||||
- `range.format` supports `fill`, `font`, `numberFormat`, `borders`, alignments, `wrapText`
|
||||
- `range.format.verticalAlignment = "center"` maps to Excel Middle Align
|
||||
- `range.format.autofitColumns()`, `range.format.autofitRows()`
|
||||
- Excel unit sizing: `range.format.columnWidth = 18`, `range.format.rowHeight = 24`
|
||||
- Pixel sizing: `range.format.columnWidthPx = 120`, `range.format.rowHeightPx = 24`
|
||||
- `range.setNumberFormat("yyyy-mm-dd")`
|
||||
- `range.format.numberFormat = [["0"], ["0.00"], ["@"]]`
|
||||
- Borders: There are two ways to set borders on a range (1) simple form (2) per edge form. Example:
|
||||
```js
|
||||
// (1) Preferred simple form
|
||||
// `preset` can be "none" | "outside" | "inside" | "all" | "doubleBottom"
|
||||
// "outside" will just set borders on the outside edges of the range.
|
||||
// `style` are Excel/OpenXML-style names such as "thin", "medium", "thick", "dashed", and "dotted".
|
||||
range.format.borders = { preset: "all", style: "thin", color: "#D9D9D9" };
|
||||
|
||||
// (2) Per-edge form. Use top/bottom/left/right, not edgeTop/edgeBottom/etc.
|
||||
// Format: {style?: string; color?: ColorConfig; weight?: number;}
|
||||
// Prefer setting `style` over `weight` unless you want granular control.
|
||||
range.format.borders = {
|
||||
insideHorizontal: { style: "thin", color: "#D9D9D9" },
|
||||
insideVertical: { style: "medium", color: "#D9D9D9" },
|
||||
top: { style: "thick", color: "#D9D9D9" },
|
||||
bottom: { style: "dashed", color: "#D9D9D9" },
|
||||
left: { style: "dotted", color: "#D9D9D9" },
|
||||
right: { style: "thin", color: "#D9D9D9" },
|
||||
};
|
||||
```
|
||||
|
||||
### Data Validation
|
||||
- `range.dataValidation = { rule: { type: "list", formula1: "Categories!$A$2:$A$4" } }`
|
||||
- `range.dataValidation = { rule: { type: "list", values: ["Not Started", "In Progress"] } }`
|
||||
- `sheet.dataValidations.add({ range: "B2:B100", rule: { type: "whole", operator: "between", formula1: 1, formula2: 10 } })`
|
||||
|
||||
### Conditional formatting
|
||||
- Use `range.conditionalFormats.add(ruleType, ConditionalFormatConfig);`.
|
||||
- Use `range.conditionalFormats.add(ruleType, {operator, formula, format});`. Choose ruleType, operator, color, and style strings from the inline types below.
|
||||
```
|
||||
type ConditionalFormatRuleType =
|
||||
| "cellIs" | "CellValue" | "Custom" | "expression"
|
||||
| "colorScale" | "dataBar" | "iconSet"
|
||||
| "containsText" | "notContainsText" | "beginsWith" | "endsWith"
|
||||
| "containsBlanks" | "notContainsBlanks" | "containsErrors" | "notContainsErrors"
|
||||
| "duplicateValues" | "uniqueValues" | "timePeriod" | "top10" | "aboveAverage";
|
||||
|
||||
type CellIsOperator =
|
||||
| "greaterThan"
|
||||
| "greaterThanOrEqual"
|
||||
| "lessThan"
|
||||
| "lessThanOrEqual"
|
||||
| "equal"
|
||||
| "notEqual"
|
||||
| "between"
|
||||
| "notBetween";
|
||||
|
||||
type ConditionalFormatConfig =
|
||||
| { operator: CellIsOperator; formula: string | number | Array<string | number>; format?: DifferentialFormatConfig }
|
||||
| { formula: string | number; format?: DifferentialFormatConfig }
|
||||
| { colors?: ColorConfig[]; thresholds?: CfvoInput[] }
|
||||
| { color?: ColorConfig; thresholds?: CfvoInput[]; gradient?: boolean }
|
||||
| { iconSet: string; showValue?: boolean; reverse?: boolean; thresholds?: CfvoInput[] }
|
||||
| { text: string; format?: DifferentialFormatConfig }
|
||||
| { timePeriod: "yesterday" | "today" | "tomorrow" | "last7Days" | "lastWeek" | "thisWeek" | "nextWeek" | "lastMonth" | "thisMonth" | "nextMonth"; format?: DifferentialFormatConfig }
|
||||
| { rank?: number; percent?: boolean; bottom?: boolean; format?: DifferentialFormatConfig }
|
||||
| { aboveAverage?: boolean; equalAverage?: boolean; stdDev?: number; format?: DifferentialFormatConfig };
|
||||
|
||||
type DifferentialFormatConfig = {
|
||||
fill?: FillConfig;
|
||||
font?: { bold?: boolean; italic?: boolean; color?: ColorConfig };
|
||||
border?: RangeBordersConfig; // Per-edge top/bottom/left/right only; presets are ignored here.
|
||||
numberFormat?: string;
|
||||
};
|
||||
|
||||
type CfvoInput =
|
||||
| "min"
|
||||
| "max"
|
||||
| number
|
||||
| `${number}%`
|
||||
| { type: "min" | "max" | "num" | "percent" | "percentile"; value?: string | number };
|
||||
```
|
||||
- Rule types (`ConditionalFormatRuleType`): "cellIs" | "CellValue" | "Custom" | "expression"
|
||||
| "colorScale" | "dataBar" | "iconSet"
|
||||
| "containsText" | "notContainsText" | "beginsWith" | "endsWith"
|
||||
| "containsBlanks" | "notContainsBlanks" | "containsErrors" | "notContainsErrors"
|
||||
| "duplicateValues" | "uniqueValues" | "timePeriod" | "top10" | "aboveAverage";
|
||||
- XLSX `iconSet` names: `3Arrows`, `4Arrows`, `5Arrows`, `3ArrowsGray`, `4ArrowsGray`, `5ArrowsGray`, `3TrafficLights1`, `3Signs`, `4RedToBlack`, `3TrafficLights2`, `4TrafficLights`, `3Symbols`, `3Flags`, `3Symbols2`, `5Quarters`, `4Rating`, `5Rating`. Avoid `3Stars`, `3Triangles`, and `5Boxes`: their current XLSX serialization is not reliable.
|
||||
- Custom conditional formatting: `range.conditionalFormats.addCustom(expression, {fill, font, border});`
|
||||
- `range.conditionalFormats.deleteAll()` / `range.conditionalFormats.clear()`
|
||||
|
||||
```js
|
||||
const grid = sheet.getRange("B2:J10");
|
||||
grid.conditionalFormats.add("colorScale", {
|
||||
colors: ["#2563EB", "#FDE047", "#DC2626"],
|
||||
thresholds: ["min", { type: "percentile", value: 50 }, "max"]
|
||||
});
|
||||
```
|
||||
|
||||
### Tables
|
||||
- When adding new tables, set explicit unique names (`TasksTable`, `SummaryTable`).
|
||||
- Do not overlap tables; the API does not reject overlaps. Check existing table ranges in the initial compact `inspect` summary before adding one.
|
||||
- `const table = sheet.tables.add("A1:H200", true, "TasksTable")`
|
||||
- `table.rows.add(null, [[...], ...])`, `table.getDataRows()`, `table.getHeaderRowRange()`
|
||||
- Read tables: `sheet.tables.items` -> `Table[]`
|
||||
- Set + Getters: `table.name`, `table.style`, `table.showHeaders`
|
||||
- Toggles for table utilities (set/get): `table.showTotals`, `table.showBandedColumns = true`, `table.showFilterButton`
|
||||
- `table.delete()`
|
||||
|
||||
### Images
|
||||
- `sheet.images.add({dataUrl: "data:image/png;base64,...", anchor: {from: { row: 1, col: 2 }, extent: { widthPx: 160, heightPx: 120 }}})`
|
||||
|
||||
|
||||
### Threaded Comments
|
||||
This is the API to create a threaded comment in Excel, which requires a user-visible author.
|
||||
- Required: Before adding a comment, create its visible author with `workbook.comments.setSelf({"displayName": <user_display_string>})`, where `<user_display_string>` is a string such as "User"
|
||||
- Create a new thread with a single comment: `const thread = workbook.comments.addThread({"cell": sheet.getRange("E2")}, "Source: <website>")`
|
||||
- To reply to a threaded comment: `thread.addReply("This is a reply to the comment")`
|
||||
- To resolve/re-open a thread: `thread.resolve()`, `thread.reopen()`
|
||||
|
||||
### Charts
|
||||
- Place charts in reserved blank areas with gutter rows/columns; do not cover data.
|
||||
- Prefer range-backed charts so source edits update the chart. Headers are detected when the first row contains text and no numeric cells.
|
||||
|
||||
|
||||
#### Fast-chart path
|
||||
- For contiguous data: pass categories first, then one column per series:
|
||||
```js
|
||||
sheet.getRange("F4:H6").values = [
|
||||
["Month", "Revenue", "EBITDA"],
|
||||
["Jan", 100, 10],
|
||||
["Feb", 120, 18],
|
||||
];
|
||||
const chart = sheet.charts.add("line", sheet.getRange("F4:H6"));
|
||||
```
|
||||
- For nonadjacent columns: pass equal-height, single-column ranges with categories first:
|
||||
```js
|
||||
const chart = sheet.charts.add("bar", [
|
||||
sheet.getRange("A1:A10"),
|
||||
sheet.getRange("D1:D10"),
|
||||
sheet.getRange("G1:G10"),
|
||||
]);
|
||||
chart.series.items[0].fill = "#F472B6";
|
||||
```
|
||||
- Both paths create source-cell references and show a bottom legend. Apply requested formatting once after creation:
|
||||
```js
|
||||
chart.setPosition("J4", "Q20"); // always set
|
||||
const fontFamily = "Arial";
|
||||
|
||||
chart.title = "Revenue and EBITDA Trend";
|
||||
chart.titleTextStyle.fontSize = 12;
|
||||
chart.titleTextStyle.typeface = fontFamily;
|
||||
|
||||
chart.legend = { position: "top", textStyle: { typeface: fontFamily } };
|
||||
chart.xAxis = { axisType: "textAxis", textStyle: { typeface: fontFamily, fontSize: 10 } };
|
||||
// Number formatting on chart axis must be set separately even if the source range is already formatted.
|
||||
chart.yAxis = { numberFormatCode: "$#,##0", numberFormatSourceLinked: false, textStyle: { typeface: fontFamily }, tickLabelInterval: 2 };
|
||||
chart.xAxis.title.text = "Month";
|
||||
chart.yAxis.title.text = "Revenue and EBITDA";
|
||||
```
|
||||
- Chart `textStyle.fontSize` uses pixels; `typeface` sets the family. Style axes, legend, and titles separately (`xAxis.textStyle`, `yAxis.textStyle`, `legend.textStyle`, `titleTextStyle`); cell fonts do not configure chart fonts.
|
||||
- Only set/style intended titles; styling an absent title can create a placeholder.
|
||||
- For custom axis formats, set `numberFormatSourceLinked: false`. For $M labels, use `$0.0,,"M"` for dollars, `$0.0,"M"` for thousands, or `$0.0"M"` for millions. Fix formatting without changing source data.
|
||||
- `chart.setData(range)` replaces categories/series but preserves title, legend, and axes. Apply series styling after binding data.
|
||||
- For month/date labels, use helper cells containing strings such as `Jan 2025`; date-axis formats may show serial numbers in previews.
|
||||
- Inspect series through `chart.series.items`; source bindings are `series.formula` and `series.categoryFormula`.
|
||||
- Additional chart getters: `chart.type`, `chart.title.text`, `chart.categories` (may be empty for range-backed charts; inspect series references).
|
||||
- Collection methods: `sheet.charts.getItemOrNullObject("Chart 1")`, `sheet.charts.deleteAll()`.
|
||||
- XLSX chart types: `"bar" | "line" | "area" | "pie" | "doughnut" | "scatter" | "bubble" | "radar" | "stock"`.
|
||||
- `"treemap"`, `"sunburst"`, `"histogram"`, `"boxWhisker"`, `"waterfall"`, `"funnel"`, and `"map"` are accepted by the API but omitted from XLSX exports in this runtime. Do not use them for Excel deliverables.
|
||||
|
||||
### Sparklines
|
||||
```js
|
||||
const group = sheet.sparklineGroups.add({
|
||||
type: "line",
|
||||
targetRange: "E2:E4",
|
||||
sourceData: "A2:C4",
|
||||
seriesColor: "#2563EB",
|
||||
markers: { high: true, low: true },
|
||||
});
|
||||
```
|
||||
- Sparkline type is a string. Use the public options documented below. Do not set internal/proto enum values for empty-cell display or axis modes; if a required option is not documented for the selected runtime, follow the bounded discovery policy.
|
||||
- Avoid `dateAxisRange` for XLSX output; it is not serialized. Keep automatic axis limits: `manualMin` / `manualMax` alone do not select custom limits in Excel.
|
||||
- Sparkline Inline Type:
|
||||
```
|
||||
type SparklineConfig = {
|
||||
type: "line" | "column" | "stacked";
|
||||
targetRange: Range | string;
|
||||
sourceData: Range | string;
|
||||
lineWeight?: number;
|
||||
displayHidden?: boolean;
|
||||
seriesColor?: ColorConfig;
|
||||
negativeColor?: ColorConfig;
|
||||
axisColor?: ColorConfig;
|
||||
markersColor?: ColorConfig;
|
||||
firstMarkerColor?: ColorConfig;
|
||||
lastMarkerColor?: ColorConfig;
|
||||
highMarkerColor?: ColorConfig;
|
||||
lowMarkerColor?: ColorConfig;
|
||||
markers?: SparklineMarkersOptions;
|
||||
axis?: SparklineAxisOptions;
|
||||
};
|
||||
|
||||
type SparklineMarkersOptions = {
|
||||
show?: boolean;
|
||||
high?: boolean;
|
||||
low?: boolean;
|
||||
first?: boolean;
|
||||
last?: boolean;
|
||||
negative?: boolean;
|
||||
};
|
||||
|
||||
type SparklineAxisOptions = {
|
||||
showAxis?: boolean;
|
||||
rightToLeft?: boolean;
|
||||
};
|
||||
```
|
||||
- Range Alias: `const group = targetRange.sparklines.add(type, sourceRange, sparklineConfig);`
|
||||
- Edit And Delete
|
||||
```js
|
||||
group.seriesColor = "#2563EB";
|
||||
group.markers.high = true;
|
||||
group.axis.showAxis = true;
|
||||
sheet.sparklineGroups.delete(group);
|
||||
sheet.sparklineGroups.deleteAll();
|
||||
```
|
||||
|
||||
### Help / Grep
|
||||
Use `workbook.help(...)` primarily for obscure/advanced surfaces (for example deep chart axis settings, unusual drawing configs, pivot APIs, or uncommon option schemas).
|
||||
- `workbook.help("enum.ShapeGeometry", { include: "index,notes" }).ndjson`
|
||||
- `workbook.help("enum.*", { search: "ShapeGeometry|LineStyle", include: "index" }).ndjson`
|
||||
- `workbook.help("shape.add", { include: "examples,notes" }).ndjson`
|
||||
- `workbook.help("fx.RATE", { include: "index,examples,notes" }).ndjson`
|
||||
- `workbook.help("cash flow return rate", { search: "IRR|XIRR|NPV|XNPV", include: "index,examples,notes", maxChars: 4000 }).ndjson`
|
||||
- `workbook.help("*", { search: "fill|borders|autofit", include: "index,examples,notes", maxChars: 6000 }).ndjson`
|
||||
|
||||
### Trace
|
||||
For tracing the full tree of how a formula is calculated, `workbook.trace("Sheet!A1")` is available. For complex formulas, the full tree can be extremely large, so output should be capped or outputted to a separate temp file (never dump raw traces). It takes only a cell reference.
|
||||
|
||||
|
||||
### JavaScript example snippet (runnable)
|
||||
|
||||
```js
|
||||
import fs from "node:fs/promises";
|
||||
import { SpreadsheetFile, Workbook } from "@oai/artifact-tool";
|
||||
|
||||
const fontFamily = "Arial";
|
||||
|
||||
const outputDir = "output";
|
||||
await fs.mkdir(outputDir, { recursive: true });
|
||||
|
||||
const workbook = Workbook.create();
|
||||
const sheet = workbook.worksheets.add("Summary");
|
||||
|
||||
sheet.getRange("A1:C4").values = [
|
||||
["Month", "Revenue", "EBITDA"],
|
||||
["Jan", 100, 10],
|
||||
["Feb", 120, 18],
|
||||
["Mar", 130, 22],
|
||||
];
|
||||
sheet.getRange("D1").values = [["Margin"]];
|
||||
sheet.getRange("D2").formulas = [["=C2/B2"]];
|
||||
sheet.getRange("D2:D4").fillDown();
|
||||
|
||||
sheet.getRange("A1:G4").format.font = { name: fontFamily, size: 11 };
|
||||
sheet.getRange("A1:D1").format = {
|
||||
fill: "#0F766E",
|
||||
font: { name: fontFamily, bold: true, color: "#FFFFFF" },
|
||||
};
|
||||
sheet.getRange("B2:C4").format.numberFormat = "$#,##0";
|
||||
sheet.getRange("D2:D4").format.numberFormat = "0.0%";
|
||||
|
||||
// Helper range links to source cells so edits update the chart.
|
||||
sheet.getRange("F1:G1").values = [["Month", "Revenue"]];
|
||||
sheet.getRange("F2:G2").formulas = [["=A2", "=B2"]];
|
||||
sheet.getRange("F2:G4").fillDown();
|
||||
const chart = sheet.charts.add("line", sheet.getRange("F1:G4"));
|
||||
chart.title = "Revenue Trend";
|
||||
chart.titleTextStyle.typeface = fontFamily;
|
||||
chart.hasLegend = false;
|
||||
chart.xAxis = { axisType: "textAxis", textStyle: { typeface: fontFamily } };
|
||||
chart.yAxis = { numberFormatCode: "$#,##0", numberFormatSourceLinked: false, textStyle: { typeface: fontFamily } };
|
||||
chart.setPosition("I1", "P15");
|
||||
|
||||
const preview = await workbook.render({
|
||||
sheetName: "Summary",
|
||||
autoCrop: "all",
|
||||
scale: 1,
|
||||
format: "png",
|
||||
});
|
||||
await fs.writeFile(`${outputDir}/summary.png`, new Uint8Array(await preview.arrayBuffer()));
|
||||
|
||||
const xlsx = await SpreadsheetFile.exportXlsx(workbook);
|
||||
await xlsx.save(`${outputDir}/summary.xlsx`);
|
||||
```
|
||||
Generated
Vendored
+210
@@ -0,0 +1,210 @@
|
||||
# Workbook API Docs
|
||||
|
||||
Use the workbook facades to create and edit Excel-style workbooks in TypeScript,
|
||||
including worksheets, ranges, formulas, tables, charts, drawings, comments,
|
||||
named ranges, import/export helpers, inspection, and recorded patches.
|
||||
|
||||
## Conventions
|
||||
|
||||
- **A1 addresses for ranges**: use `sheet.getRange("A1:B2")` for A1 ranges.
|
||||
Use `getRangeByIndexes(row, column, rowCount, columnCount)` and
|
||||
`getCell(row, column)` for zero-based index access.
|
||||
- **Matrices are row-major**: range values and formulas use `rows x columns`
|
||||
arrays. Single-row and single-column ranges accept one-dimensional arrays.
|
||||
- **Formulas include `=`**: assigning a string starting with `=` through
|
||||
`values` stores a formula; prefix with `'` to store a literal leading `=`.
|
||||
- **Use `write` for shape-matched writes**: `range.write(...)` can resize from
|
||||
the target top-left cell.
|
||||
- **Record user edits**: wrap edits in `workbook.record(() => { ... })` when a
|
||||
patch, id map, or CRDT update is needed.
|
||||
- **Inspect before editing imported workbooks**: use `inspect`, `findCells`,
|
||||
and `resolve` to locate exact sheets, tables, charts, and threads.
|
||||
- **Config-first creation**: prefer worksheet/range/table/chart config objects
|
||||
where available.
|
||||
- **PDF export**: `workbook.export({ format: "pdf" })` exports all worksheets.
|
||||
Set `pageSizing: "uniform"` for equal page sizes.
|
||||
|
||||
## Quick Start
|
||||
|
||||
```ts
|
||||
const workbook = Workbook.create();
|
||||
const sheet = workbook.worksheets.add("Data");
|
||||
|
||||
sheet.getRange("A1:C4").values = [
|
||||
["Region", "Q1", "Q2"],
|
||||
["North", 10, 12],
|
||||
["South", 8, 9],
|
||||
["Total", null, null],
|
||||
];
|
||||
sheet.getRange("B4:C4").formulas = [["=SUM(B2:B3)", "=SUM(C2:C3)"]];
|
||||
workbook.recalculate();
|
||||
|
||||
const table = sheet.tables.add("A1:C4", true, "DataTable");
|
||||
table.rows.add(null, [["West", 7, 11]]);
|
||||
|
||||
const chart = sheet.charts.add("bar", {
|
||||
from: { row: 1, col: 4 },
|
||||
extent: { widthPx: 420, heightPx: 260 },
|
||||
});
|
||||
chart.title = "Quarterly values";
|
||||
chart.categories = ["North", "South", "West"];
|
||||
const series = chart.series.add("Q1");
|
||||
series.values = [10, 8, 7];
|
||||
series.categories = chart.categories;
|
||||
|
||||
const preview = await workbook.export({
|
||||
sheet,
|
||||
range: "A1:C5",
|
||||
format: "png",
|
||||
scale: 2,
|
||||
});
|
||||
const layoutBlob = await workbook.export({
|
||||
sheet,
|
||||
range: "A1:C5",
|
||||
format: "layout",
|
||||
});
|
||||
const pdfBlob = await workbook.export({ format: "pdf" });
|
||||
const uniformPdfBlob = await workbook.export({
|
||||
format: "pdf",
|
||||
pageSizing: "uniform",
|
||||
headers: true,
|
||||
});
|
||||
const proto = workbook.toProto();
|
||||
```
|
||||
|
||||
## Load Existing Workbook Data
|
||||
|
||||
```ts
|
||||
const workbook = Workbook.load(proto, { validate: true });
|
||||
|
||||
const before = await workbook.inspect({
|
||||
kind: "sheet,table,formula,chart,thread",
|
||||
search: "Revenue",
|
||||
maxChars: 8000,
|
||||
});
|
||||
|
||||
const sheet = workbook.resolve(sheetAnchorId);
|
||||
sheet.getRange("B2").values = [["Updated"]];
|
||||
|
||||
const after = await workbook.inspect({
|
||||
target: { id: sheetAnchorId, beforeLines: 1, afterLines: 6 },
|
||||
kind: "sheet,table",
|
||||
});
|
||||
```
|
||||
|
||||
## Recorded Edit
|
||||
|
||||
```ts
|
||||
const { result, patch, idMap, crdtUpdateV2 } = workbook.record(() => {
|
||||
const sheet = workbook.worksheets.getItem("Data");
|
||||
sheet.getRange("A1:B2").values = [
|
||||
["Name", "Value"],
|
||||
["A", 1],
|
||||
];
|
||||
return sheet.tables.add("A1:B2", true, "DataTable");
|
||||
});
|
||||
```
|
||||
|
||||
`record` hydrates collaborative state when needed and returns the callback
|
||||
result, a workbook patch, created-id aliases, and a merged CRDT update when
|
||||
collaborative edits occurred.
|
||||
|
||||
## Core API Sequence
|
||||
|
||||
- Create workbooks with `Workbook.create()` and load with
|
||||
`Workbook.load(proto, { validate })`.
|
||||
- Import simple tabular data with `Workbook.fromCSV(...)`,
|
||||
`workbook.fromCSV(...)`, and `Workbook.fromMarkdown(...)`.
|
||||
- Add or select sheets with `workbook.worksheets.add(...)`, `getItem(...)`,
|
||||
`getActiveWorksheet()`, and
|
||||
`setActiveWorksheet(...)`.
|
||||
- Edit data with `sheet.getRange("A1:B2").values`, `.formulas`,
|
||||
`.formulasR1C1`, `.write(...)`, `.clear(...)`, `.merge(...)`, and
|
||||
`.copyFrom(...)`.
|
||||
- Add tables with `sheet.tables.add(range, hasHeaders, name)` and edit rows,
|
||||
columns, styles, totals, and filters on the table facade.
|
||||
- Add charts, images, shapes, sparklines, conditional formats, data
|
||||
validations, freeze panes, pivot tables, slicers, comments, notes, and names
|
||||
through their worksheet/workbook facades.
|
||||
- Recalculate formulas with `workbook.recalculate()` and inspect dependencies
|
||||
with `workbook.trace("Sheet!A1")`.
|
||||
- Inspect imported workbooks with `workbook.inspect(...)`, `findCells(...)`,
|
||||
`help(...)`, and `resolve(...)`.
|
||||
- Render previews with `workbook.render(...)` or `workbook.export(...)`.
|
||||
- Export all worksheets as PDF with `workbook.export({ format: "pdf" })`.
|
||||
Pass `sheet`, `sheetName`, or `sheetIndex` to export one worksheet.
|
||||
- Set PDF `pageSizing` to `"per-sheet"` (default) or `"uniform"`.
|
||||
- Export grid and style evidence with `workbook.export({ format: "layout" })`
|
||||
when template reconstruction needs cell frames, style regions, merged ranges,
|
||||
validations, defined names, and drawing anchors.
|
||||
- Serialize workbook data with `workbook.toProto()`.
|
||||
|
||||
## Output Map
|
||||
|
||||
| Output | API | Result |
|
||||
| --------------- | --------------------------------------------- | --------------------------------------------- |
|
||||
| Serialized data | `workbook.toProto()` | Serializable workbook proto |
|
||||
| Inspect records | `await workbook.inspect(options)` | Structured records and NDJSON |
|
||||
| Cell search | `workbook.findCells(options)` | Matches with sheet/address/value/formula info |
|
||||
| Help records | `workbook.help(query, options)` | Bounded NDJSON API help records |
|
||||
| Image preview | `workbook.export({ format: "png" })` | Workbook/sheet/range render blob |
|
||||
| PDF | `workbook.export({ format: "pdf" })` | PDF `Blob` |
|
||||
| Layout JSON | `workbook.export({ format: "layout" })` | Typed grid and style evidence |
|
||||
| Native workbook | `workbook.export({ format: "xlsx" })` | Editable XLSX `Blob` |
|
||||
| Render blob | `workbook.render(options)` | Render-provider blob |
|
||||
| HTML table | `workbook.toHTML(sheetIndex, range, options)` | Excel/Sheets-compatible HTML |
|
||||
| Recorded patch | `workbook.record(fn)` | `{ result, patch, idMap, crdtUpdateV2 }` |
|
||||
|
||||
## Minimal Patterns
|
||||
|
||||
```ts
|
||||
// Data + formulas.
|
||||
const workbook = Workbook.create();
|
||||
const sheet = workbook.worksheets.add("Calc");
|
||||
sheet.getRange("A1:B2").values = [
|
||||
[2, 3],
|
||||
[5, 7],
|
||||
];
|
||||
sheet.getRange("C1:C2").formulas = [["=A1+B1"], ["=A2+B2"]];
|
||||
workbook.recalculate();
|
||||
```
|
||||
|
||||
```ts
|
||||
// Inspect, resolve, edit, re-inspect.
|
||||
const snapshot = await workbook.inspect({
|
||||
kind: "sheet,table,formula,thread,chart",
|
||||
search: "Status",
|
||||
});
|
||||
const sheet = workbook.resolve(sheetAnchorId);
|
||||
sheet.getRange("B2").values = [["Closed"]];
|
||||
const updated = await workbook.inspect({
|
||||
target: { id: sheetAnchorId },
|
||||
kind: "sheet,table",
|
||||
});
|
||||
```
|
||||
|
||||
## Reference Map
|
||||
|
||||
- [`references/workbook.spec.md`](./references/workbook.spec.md) -
|
||||
`Workbook` create/load/import/export/inspect/help/record surface.
|
||||
- [`references/worksheets.spec.md`](./references/worksheets.spec.md) -
|
||||
worksheet collection and worksheet facade.
|
||||
- [`references/ranges.spec.md`](./references/ranges.spec.md) - values,
|
||||
formulas, indexing, formatting, clearing, merging, fill, and copy.
|
||||
- [`references/tables.spec.md`](./references/tables.spec.md) - worksheet
|
||||
tables, rows, columns, headers, totals, and recorded patches.
|
||||
- [`references/pivot-tables.spec.md`](./references/pivot-tables.spec.md) -
|
||||
pivot creation, calculations, layout, filtering, and editing.
|
||||
- [`references/formulas.spec.md`](./references/formulas.spec.md) -
|
||||
recalculation, formula assignment, dynamic arrays, trace, and names.
|
||||
- [`references/formatting.spec.md`](./references/formatting.spec.md) - range
|
||||
formats, workbook theme, conditional formatting, data validation, and freeze
|
||||
panes.
|
||||
- [`references/charts-drawings.spec.md`](./references/charts-drawings.spec.md)
|
||||
- worksheet charts, images, shapes, sparklines, and drawing layout.
|
||||
- [`references/comments-notes-names.spec.md`](./references/comments-notes-names.spec.md)
|
||||
- comments, notes, workbook-scoped names, and sheet-scoped names.
|
||||
- [`references/inspect-help.md`](./references/inspect-help.md) - inspect,
|
||||
resolve, findCells, and help workflows.
|
||||
- [`references/import-export.md`](./references/import-export.md) - CSV,
|
||||
Markdown, HTML, image import, rendering, export, and Google Sheets adapters.
|
||||
Generated
Vendored
+264
@@ -0,0 +1,264 @@
|
||||
# Charts And Drawings
|
||||
|
||||
Worksheets expose drawing collections for charts, images, and shapes.
|
||||
|
||||
## Charts
|
||||
|
||||
```ts
|
||||
const chart = sheet.charts.add("bar", {
|
||||
from: { row: 1, col: 4 },
|
||||
extent: { widthPx: 420, heightPx: 260 },
|
||||
});
|
||||
chart.title = "Values";
|
||||
chart.categories = ["A", "B", "C"];
|
||||
const series = chart.series.add("Value");
|
||||
series.values = [3, 5, 8];
|
||||
series.categories = chart.categories;
|
||||
```
|
||||
|
||||
Charts can be resolved from inspect anchors:
|
||||
|
||||
```ts
|
||||
const chart = workbook.resolve("ch/<chartId>");
|
||||
```
|
||||
|
||||
### Edit The Chart Frame
|
||||
|
||||
```ts
|
||||
chart.roundedCorners = true;
|
||||
chart.roundedCorners = false;
|
||||
chart.roundedCorners = null;
|
||||
const roundedCorners = chart.roundedCorners;
|
||||
```
|
||||
|
||||
### Edit Chart Family Options
|
||||
|
||||
```ts
|
||||
histogram.apply({ histogramOptions: { binCount: 8, underflow: 0, overflow: 30 } });
|
||||
histogram.apply({ histogramOptions: { binWidth: null, binCount: null } });
|
||||
histogram.apply({ histogramOptions: { underflow: null, overflow: null } });
|
||||
bubble.bubbleOptions = { scale: 150, sizeRepresents: "width" };
|
||||
bubble.bubbleOptions = { scale: null, sizeRepresents: null };
|
||||
const settings = bubble.bubbleOptions;
|
||||
```
|
||||
|
||||
[Chart family options](../../../presentations/api/references/charts.spec.md#chart-family-options)
|
||||
|
||||
### Edit Error Bars
|
||||
|
||||
```ts
|
||||
const errorBars = chart.series.getItemAt(0).errorBars;
|
||||
errorBars.apply("y", { type: "fixedValue", value: 2 });
|
||||
errorBars.apply("y", {
|
||||
display: "both",
|
||||
endStyle: "cap",
|
||||
line: { fill: "accent1", width: 1.5, style: "solid" },
|
||||
});
|
||||
const editableDirections = errorBars.directions;
|
||||
const settings = errorBars.get("y");
|
||||
errorBars.apply("y", { line: { width: null } });
|
||||
errorBars.apply("y", { type: "none" });
|
||||
```
|
||||
|
||||
### Edit Individual Trendlines
|
||||
|
||||
```ts
|
||||
const trendlines = chart.series.getItemAt(0).trendlines;
|
||||
const types = trendlines.supportedTypes;
|
||||
const trendline = trendlines.add("linear", { name: "Forecast" });
|
||||
trendline.apply({
|
||||
forecastForward: 2,
|
||||
displayEquation: true,
|
||||
line: { fill: "accent2", width: 2, style: "dashed" },
|
||||
label: {
|
||||
numberFormatCode: "0.00",
|
||||
numberFormatSourceLinked: false,
|
||||
textStyle: { fontSizePt: 12, typeface: "Arial", color: "accent2" },
|
||||
manualLayout: { x: 0.2, y: 0.3 },
|
||||
fill: "#FFFFFF",
|
||||
line: { fill: "accent2", width: 1 },
|
||||
},
|
||||
});
|
||||
trendline.apply({ forecastForward: null });
|
||||
trendlines.deleteAt(0);
|
||||
```
|
||||
|
||||
### Replace Chart Data
|
||||
|
||||
```ts
|
||||
chart.setData("A1:C8");
|
||||
chart.setData("'Source data'!A1:C8");
|
||||
chart.setData(["'Source data'!A1:A8", "D1:D8", "G1:G8"]);
|
||||
```
|
||||
|
||||
| Chart | Source columns |
|
||||
| --- | --- |
|
||||
| Bar, line, area, pie | Categories, then one column per series |
|
||||
| Scatter | X values, then one Y column per series |
|
||||
| Bubble | X, Y, Size per series |
|
||||
| Treemap or sunburst | Outer-to-inner category levels, then values |
|
||||
| Box and whisker or histogram | One numeric column per sample series |
|
||||
|
||||
### Empty Cells
|
||||
|
||||
```ts
|
||||
chart.displayBlanksAs = "gap";
|
||||
chart.displayBlanksAs = "zero";
|
||||
chart.displayBlanksAs = "span";
|
||||
chart.displayBlanksAs = null;
|
||||
chart.displayBlanksAsOptions;
|
||||
```
|
||||
|
||||
### Edit One Series Binding
|
||||
|
||||
```ts
|
||||
const series = chart.series.getItemAt(0);
|
||||
series.valuesSource = "'Source data'!D2:D8";
|
||||
series.categoriesSource = "A2:A8";
|
||||
series.xValuesSource = "B2:B8";
|
||||
// Bubble charts:
|
||||
series.bubbleSizesSource = "C2:C8";
|
||||
// Treemap and sunburst charts:
|
||||
series.categoryPathsSource = "A2:B8";
|
||||
```
|
||||
|
||||
### Edit An Axis
|
||||
|
||||
```ts
|
||||
const axes = chart.getAxisTargets(); // { axisId: number, axis: "x" | "y" }[]
|
||||
const axisId = axes[0].axisId;
|
||||
const axis = chart.getAxisById(axisId);
|
||||
chart.applyAxis(axisId, {
|
||||
min: 0,
|
||||
max: 100,
|
||||
title: { text: "Value", textStyle: { bold: true } },
|
||||
});
|
||||
```
|
||||
|
||||
### Scoped Data Labels
|
||||
|
||||
```ts
|
||||
const target = { scope: "point", seriesIndex: 0, pointIndex: 1 } as const;
|
||||
const targetExists = chart.hasDataLabelTarget(target);
|
||||
const labels = chart.getDataLabels(target);
|
||||
chart.applyDataLabels(target, { textStyle: { bold: true }, separator: " / " });
|
||||
chart.applyDataLabels(target, { showValue: false });
|
||||
chart.applyDataLabels(target, { showValue: null }); // Restore the parent flag.
|
||||
chart.applyDataLabels(target, null); // Remove the entire point override.
|
||||
chart.applyDataLabels({ scope: "series", seriesIndex: 0 }, {
|
||||
showValue: true, numberFormatCode: "0.00",
|
||||
});
|
||||
chart.applyDataLabels({ scope: "chart" }, { position: "outEnd" });
|
||||
```
|
||||
|
||||
### Series Markers And Bar Spacing
|
||||
|
||||
```ts
|
||||
chart.applySeriesStyle(0, {
|
||||
marker: { symbol: "diamond", size: 8, fill: "#156082" },
|
||||
});
|
||||
chart.applySeriesStyle(0, { marker: { size: 12 } });
|
||||
chart.applySeriesStyle(0, { stroke: { style: "dashed", compound: "double" } });
|
||||
chart.applySeriesStyle(0, { stroke: { width: 3 } });
|
||||
chart.format.apply({ barOptions: { gapWidth: 150, overlap: 0 } });
|
||||
```
|
||||
|
||||
## Chart To Image
|
||||
|
||||
```ts
|
||||
const result = await workbook.chartToImage(0, chart.id);
|
||||
```
|
||||
|
||||
## Images
|
||||
|
||||
```ts
|
||||
const image = sheet.images.add({
|
||||
blob: imageBytes,
|
||||
contentType: "image/png",
|
||||
anchor: {
|
||||
from: { row: 1, col: 2 },
|
||||
extent: { widthPx: 240, heightPx: 160 },
|
||||
},
|
||||
});
|
||||
|
||||
image.id;
|
||||
image.bytes;
|
||||
image.contentType;
|
||||
image.prompt;
|
||||
image.uri;
|
||||
```
|
||||
|
||||
## Shapes
|
||||
|
||||
```ts
|
||||
const shape = sheet.shapes.add({
|
||||
geometry: "rect",
|
||||
anchor: {
|
||||
from: { row: 2, col: 3 },
|
||||
extent: { widthPx: 240, heightPx: 80 },
|
||||
},
|
||||
fill: "#f8fafc",
|
||||
line: { fill: "#334155", width: 1 },
|
||||
});
|
||||
shape.text = "Label";
|
||||
shape.geometry = "roundRect";
|
||||
shape.geometry; // "roundRect"
|
||||
shape.borderRadius = 16;
|
||||
shape.borderRadius;
|
||||
shape.borderRadiusApplies;
|
||||
```
|
||||
|
||||
## Sparklines
|
||||
|
||||
```ts
|
||||
const group = sheet.sparklineGroups.add({
|
||||
targetRange: sheet.getRange("D2:D10"),
|
||||
sourceData: sheet.getRange("B2:C10"),
|
||||
type: "line",
|
||||
});
|
||||
|
||||
group.apply({
|
||||
sourceData: "'Source data'!B2:C12",
|
||||
locationRange: "D2:D12",
|
||||
type: "line",
|
||||
lineWeight: 2,
|
||||
dateAxisRange: "'Source data'!B1:C1",
|
||||
displayHidden: false,
|
||||
axis: { manualMin: 0, manualMax: 100 },
|
||||
});
|
||||
|
||||
group.apply({ axis: { manualMin: undefined, manualMax: undefined } });
|
||||
group.apply({ dateAxisRange: undefined }); // Restore evenly spaced samples.
|
||||
|
||||
group.sourceAddress;
|
||||
group.dateAxisAddress;
|
||||
group.dateAxisFormula;
|
||||
group.uid;
|
||||
```
|
||||
|
||||
## Auto Layout
|
||||
|
||||
```ts
|
||||
sheet.autoLayoutDrawings(sheet.charts.items, {
|
||||
direction: "vertical",
|
||||
frame: { startCell: "E2", width: 800, height: 1200 },
|
||||
gap: 16,
|
||||
padding: 24,
|
||||
});
|
||||
```
|
||||
|
||||
## Cookbook
|
||||
|
||||
```ts
|
||||
sheet.getRange("A1:B4").values = [
|
||||
["Name", "Value"],
|
||||
["A", 3],
|
||||
["B", 5],
|
||||
["C", 8],
|
||||
];
|
||||
|
||||
sheet.charts.add("bar", {
|
||||
from: { row: 1, col: 4 },
|
||||
extent: { widthPx: 420, heightPx: 260 },
|
||||
});
|
||||
```
|
||||
Generated
Vendored
+78
@@ -0,0 +1,78 @@
|
||||
# Comments, Notes, And Names
|
||||
|
||||
Workbook comments, notes, and names are root-level facades. Sheet-scoped names
|
||||
are available from `worksheet.names`.
|
||||
|
||||
## Comments
|
||||
|
||||
```ts
|
||||
workbook.comments.setSelf({
|
||||
displayName: "Reviewer",
|
||||
initials: "RV",
|
||||
});
|
||||
|
||||
const thread = workbook.comments.addThread(
|
||||
{ cell: sheet.getRange("B2") },
|
||||
"Review this cell",
|
||||
);
|
||||
|
||||
thread.addReply("Updated.");
|
||||
thread.resolve();
|
||||
thread.reopen();
|
||||
```
|
||||
|
||||
Threads appear in `workbook.inspect({ kind: "thread" })` and resolve from
|
||||
`th/...` anchors.
|
||||
|
||||
## Notes
|
||||
|
||||
```ts
|
||||
workbook.notes;
|
||||
```
|
||||
|
||||
Notes serialize through `workbook.toProto()` and participate in recorded
|
||||
workbook state.
|
||||
|
||||
## Workbook-Scoped Names
|
||||
|
||||
```ts
|
||||
workbook.names.addRange("SalesRange", "Data!$A$1:$A$3", {
|
||||
description: "Sales data",
|
||||
});
|
||||
|
||||
const namedRange = workbook.names.getItem("SalesRange");
|
||||
const range = namedRange.getRange();
|
||||
namedRange.delete();
|
||||
```
|
||||
|
||||
## Functions
|
||||
|
||||
```ts
|
||||
workbook.names.addFunction("AddTax", {
|
||||
lambda: "=LAMBDA(amount, amount * 1.1)",
|
||||
description: "Add tax",
|
||||
});
|
||||
```
|
||||
|
||||
## Sheet-Scoped Names
|
||||
|
||||
```ts
|
||||
sheet.names.addRange("LocalRange", "Sheet1!$A$1:$A$10");
|
||||
```
|
||||
|
||||
## Alias
|
||||
|
||||
```ts
|
||||
workbook.definedNames === workbook.names;
|
||||
```
|
||||
|
||||
## Cookbook
|
||||
|
||||
```ts
|
||||
const data = workbook.worksheets.add("Data");
|
||||
data.getRange("A1:A3").values = [[1], [2], [3]];
|
||||
workbook.names.add("SalesRange", data.getRange("A1:A3"));
|
||||
|
||||
workbook.comments.setSelf({ displayName: "Reviewer", initials: "RV" });
|
||||
workbook.comments.addThread({ cell: data.getRange("A1") }, "Check value.");
|
||||
```
|
||||
Generated
Vendored
+286
@@ -0,0 +1,286 @@
|
||||
# Formatting, Validation, And Theme
|
||||
|
||||
Use range formatting for cell style, worksheet collections for validation and
|
||||
conditional formatting, and `workbook.colorScheme` for workbook theme colors.
|
||||
|
||||
## Range Format
|
||||
|
||||
```ts
|
||||
range.format = {
|
||||
fill: "#f8fafc",
|
||||
font: {
|
||||
name: "Aptos",
|
||||
bold: true,
|
||||
underline: "single",
|
||||
color: "#0f172a",
|
||||
size: 11,
|
||||
},
|
||||
borders: {
|
||||
bottom: { style: "thin", color: "#94a3b8" },
|
||||
},
|
||||
numberFormat: "$#,##0.00",
|
||||
horizontalAlignment: "center",
|
||||
verticalAlignment: "middle",
|
||||
wrapText: true,
|
||||
rowHeightPx: 28,
|
||||
columnWidthPx: 120,
|
||||
};
|
||||
```
|
||||
|
||||
### Cell fills
|
||||
|
||||
```ts
|
||||
range.format.fill = {
|
||||
type: "gradient",
|
||||
angleDeg: 45,
|
||||
offsetScale: 100000,
|
||||
stops: [
|
||||
{ offset: 0, color: "accent1" },
|
||||
{ offset: 100000, color: "#ffffff" },
|
||||
],
|
||||
};
|
||||
range.format.fill = {
|
||||
type: "solid",
|
||||
color: "#ffffff",
|
||||
pattern: { type: "lightGrid", color: "#64748b" },
|
||||
};
|
||||
```
|
||||
|
||||
### Reading mixed formatting
|
||||
|
||||
```ts
|
||||
const summary = range.format.getSummary();
|
||||
if (summary.font.bold.state === "uniform") {
|
||||
console.log(summary.font.bold.value);
|
||||
}
|
||||
range.format = { font: { bold: true } };
|
||||
```
|
||||
|
||||
## Number Format
|
||||
|
||||
```ts
|
||||
range.setNumberFormat("0.0%");
|
||||
```
|
||||
|
||||
## Conditional Formatting
|
||||
|
||||
```ts
|
||||
sheet.getRange("B2:B10").conditionalFormats.add("cellIs", {
|
||||
operator: "greaterThan",
|
||||
formula: 10,
|
||||
format: {
|
||||
fill: "#dcfce7",
|
||||
font: { bold: true, color: "#166534" },
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
### Add and edit rules
|
||||
|
||||
```ts
|
||||
const rule = sheet.conditionalFormattings.add({
|
||||
range: "C2:C20",
|
||||
rule: {
|
||||
type: "cellIs",
|
||||
operator: "greaterThan",
|
||||
formula: "=$B2",
|
||||
format: { font: { bold: true, underline: "single" }, numberFormat: "0.0%" },
|
||||
},
|
||||
stopIfTrue: true,
|
||||
});
|
||||
rule.assign({ ranges: ["C2:C20", "E2:E20"] });
|
||||
rule.assign({ stopIfTrue: false });
|
||||
const sameRule = sheet.conditionalFormattings.getItem(rule.id);
|
||||
const matchingRules = sheet.conditionalFormattings.getIntersecting("C5");
|
||||
rule.moveBefore(null); // Last priority.
|
||||
```
|
||||
|
||||
### Edit rule formatting
|
||||
|
||||
```ts
|
||||
rule.assign({
|
||||
formatPatch: {
|
||||
font: { bold: false, color: null }, // Reset the font color override.
|
||||
border: { bottom: { style: "double" } },
|
||||
numberFormat: "0.00%",
|
||||
},
|
||||
});
|
||||
rule.assign({ ranges: ["E4:E20"], formatPatch: { font: { italic: true } } });
|
||||
```
|
||||
|
||||
### Text predicates
|
||||
|
||||
```ts
|
||||
const textRule = sheet.conditionalFormattings.add({
|
||||
range: "A2:A20",
|
||||
rule: {
|
||||
type: "containsText",
|
||||
text: "ready",
|
||||
formula: '=AND(ISNUMBER(SEARCH("ready",A2)),B2>0)',
|
||||
format: { fill: "accent2" },
|
||||
},
|
||||
});
|
||||
textRule.assign({
|
||||
predicatePatch: { type: "containsText", text: "approved" },
|
||||
formatPatch: { font: { bold: true } },
|
||||
ranges: ["C4:C22"],
|
||||
});
|
||||
textRule.assign({
|
||||
predicatePatch: { type: "containsText", formula: null },
|
||||
});
|
||||
```
|
||||
|
||||
### Date-period formula overrides
|
||||
|
||||
```ts
|
||||
const dates = sheet.conditionalFormattings.add({
|
||||
range: "B2:B20",
|
||||
rule: {
|
||||
type: "timePeriod",
|
||||
timePeriod: "last7Days",
|
||||
formula: "=AND(B2>=TODAY()-7,B2<=TODAY())",
|
||||
format: { fill: "accent2" },
|
||||
},
|
||||
});
|
||||
const dateConfig = dates.config;
|
||||
if (dateConfig.supported && dateConfig.rule.type === "timePeriod") {
|
||||
dates.assign({ rule: { ...dateConfig.rule, formula: "=B2=TODAY()" } });
|
||||
dates.assign({ rule: { ...dateConfig.rule, formula: undefined } });
|
||||
}
|
||||
```
|
||||
|
||||
### Data bars
|
||||
|
||||
```ts
|
||||
const bars = sheet.conditionalFormattings.add({
|
||||
range: "B2:B20",
|
||||
rule: {
|
||||
type: "dataBar",
|
||||
color: "accent1",
|
||||
gradient: false,
|
||||
showValue: true,
|
||||
minLength: 0,
|
||||
maxLength: 100,
|
||||
direction: "leftToRight", // "context" | "leftToRight" | "rightToLeft"
|
||||
axisPosition: "automatic", // "automatic" | "middle" | "none"
|
||||
border: true,
|
||||
borderColor: "accent1",
|
||||
negativeBarColorSameAsPositive: false,
|
||||
negativeFillColor: "accent2",
|
||||
negativeBarBorderColorSameAsPositive: false,
|
||||
negativeBorderColor: "accent2",
|
||||
axisColor: "text1",
|
||||
thresholds: [{ type: "autoMin" }, { type: "autoMax" }],
|
||||
},
|
||||
});
|
||||
const snapshot = bars.config;
|
||||
if (snapshot.supported && snapshot.rule.type === "dataBar") {
|
||||
bars.assign({ rule: { ...snapshot.rule, showValue: false } });
|
||||
}
|
||||
```
|
||||
|
||||
### Icon sets
|
||||
|
||||
```ts
|
||||
sheet.conditionalFormattings.add({
|
||||
range: "C2:C20",
|
||||
rule: {
|
||||
type: "iconSet",
|
||||
iconSet: "3Arrows",
|
||||
thresholds: [
|
||||
{ type: "num", value: 0 },
|
||||
{ type: "formula", value: "=$E$2", gte: false },
|
||||
{ type: "formula", value: "=$E$3", gte: true },
|
||||
],
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
### Clear and delete rules
|
||||
|
||||
```ts
|
||||
sheet.conditionalFormattings.clear("E5:E6");
|
||||
rule.delete();
|
||||
```
|
||||
|
||||
## Data Validation
|
||||
|
||||
```ts
|
||||
sheet.getRange("A2:A10").dataValidation = {
|
||||
list: {
|
||||
source: ["Open", "Closed"],
|
||||
inCellDropDown: true,
|
||||
},
|
||||
allowBlank: true,
|
||||
};
|
||||
```
|
||||
|
||||
The range setter accepts list assignments or validation config
|
||||
objects.
|
||||
|
||||
```ts
|
||||
sheet.getRange("B2:B20").dataValidation = {
|
||||
rule: { type: "whole", operator: "between", formula1: 0, formula2: 100 },
|
||||
ignoreBlanks: true,
|
||||
prompt: { show: true, title: "Score", message: "Enter 0–100." },
|
||||
errorAlert: {
|
||||
show: true,
|
||||
style: "warning",
|
||||
message: "Outside the expected range.",
|
||||
},
|
||||
};
|
||||
sheet.getRange("B5").dataValidation.clear();
|
||||
```
|
||||
|
||||
### Check cell values
|
||||
|
||||
```ts
|
||||
const cell = sheet.getRange("B2");
|
||||
const check = workbook.checkCellValue(sheet.name, "B2", 150);
|
||||
const result = cell.setValueChecked(150);
|
||||
if (
|
||||
!result.applied &&
|
||||
!result.validation.valid &&
|
||||
result.validation.style !== "stop"
|
||||
) {
|
||||
// After the user confirms the warning/information message:
|
||||
cell.setValueChecked(150, { acceptWarning: true });
|
||||
}
|
||||
```
|
||||
|
||||
## Freeze Panes
|
||||
|
||||
```ts
|
||||
sheet.freezePanes.freezeRows(1);
|
||||
sheet.freezePanes.freezeColumns(1);
|
||||
sheet.freezePanes.unfreeze();
|
||||
```
|
||||
|
||||
## Theme
|
||||
|
||||
```ts
|
||||
const current = workbook.colorScheme;
|
||||
console.log(current.name, current.themeColors.accent1);
|
||||
|
||||
workbook.colorScheme = {
|
||||
name: "Workbook Theme",
|
||||
themeColors: {
|
||||
accent1: "#2563eb",
|
||||
accent2: "#0f766e",
|
||||
bg1: "#ffffff",
|
||||
tx1: "#0f172a",
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
## Cookbook
|
||||
|
||||
```ts
|
||||
const header = sheet.getRange("A1:C1");
|
||||
header.format = {
|
||||
fill: "#0f172a",
|
||||
font: { bold: true, color: "#ffffff" },
|
||||
horizontalAlignment: "center",
|
||||
};
|
||||
sheet.freezePanes.freezeRows(1);
|
||||
```
|
||||
Generated
Vendored
+74
@@ -0,0 +1,74 @@
|
||||
# Formulas
|
||||
|
||||
Workbook formulas are stored on ranges and evaluated by `workbook.recalculate()`.
|
||||
|
||||
## Assign Formulas
|
||||
|
||||
```ts
|
||||
sheet.getRange("A1:B2").values = [
|
||||
[2, 3],
|
||||
[5, 7],
|
||||
];
|
||||
|
||||
sheet.getRange("C1:C2").formulas = [["=A1+B1"], ["=A2+B2"]];
|
||||
workbook.recalculate();
|
||||
```
|
||||
|
||||
Strings starting with `=` assigned through `values` are treated as formulas.
|
||||
Use a leading apostrophe for literal strings:
|
||||
|
||||
```ts
|
||||
sheet.getRange("C1").values = [["=SUM(A1:B1)"]];
|
||||
sheet.getRange("D1").values = [["'=SUM(A1:B1)"]];
|
||||
```
|
||||
|
||||
## Dynamic Arrays And Spill
|
||||
|
||||
```ts
|
||||
sheet.getRange("E1").formulas = [["=SEQUENCE(3, 2)"]];
|
||||
workbook.recalculate();
|
||||
```
|
||||
|
||||
Spill projection cells are not directly editable formula anchors.
|
||||
|
||||
## Trace
|
||||
|
||||
```ts
|
||||
const trace = workbook.trace("Sheet1!C1");
|
||||
```
|
||||
|
||||
`trace` recalculates first and returns a dependency tree for the target cell or
|
||||
`null` for an invalid reference.
|
||||
|
||||
## Formula Usage Stats
|
||||
|
||||
```ts
|
||||
const stats = workbook.collectFormulaUsageStats();
|
||||
```
|
||||
|
||||
## Names
|
||||
|
||||
```ts
|
||||
workbook.names.addRange("SalesRange", "Data!$A$1:$A$3", {
|
||||
description: "Sales data",
|
||||
});
|
||||
|
||||
workbook.names.addFunction("AddTax", {
|
||||
lambda: "=LAMBDA(amount, amount * 1.1)",
|
||||
description: "Add tax",
|
||||
});
|
||||
|
||||
sheet.names.addRange("LocalRange", "Sheet1!$A$1:$A$10");
|
||||
```
|
||||
|
||||
## Cookbook
|
||||
|
||||
```ts
|
||||
const workbook = Workbook.create();
|
||||
const sheet = workbook.worksheets.add("Calc");
|
||||
sheet.getRange("A1:A3").values = [[1], [2], [3]];
|
||||
sheet.getRange("B1").formulas = [["=SUM(A1:A3)"]];
|
||||
workbook.recalculate();
|
||||
|
||||
const trace = workbook.trace("Calc!B1");
|
||||
```
|
||||
Generated
Vendored
+168
@@ -0,0 +1,168 @@
|
||||
# Import, Export, HTML, Images, And Google Sheets
|
||||
|
||||
Workbook import/export helpers cover CSV, Markdown, HTML copy/paste,
|
||||
image/chart conversion, rendering, and Google Sheets adapter flows.
|
||||
|
||||
## CSV
|
||||
|
||||
```ts
|
||||
const workbook = await Workbook.fromCSV(csv, {
|
||||
sheetName: "Data",
|
||||
});
|
||||
|
||||
const { sheet, range } = await workbook.fromCSV(csv, {
|
||||
sheetName: "Imported",
|
||||
});
|
||||
```
|
||||
|
||||
## Markdown Table
|
||||
|
||||
```ts
|
||||
const workbook = await Workbook.fromMarkdown(markdown, {
|
||||
sheetName: "Data",
|
||||
format: true,
|
||||
});
|
||||
```
|
||||
|
||||
Markdown import expects a Markdown table. With `format: true`, the imported
|
||||
range is formatted as a worksheet table and columns are autofit.
|
||||
|
||||
## HTML
|
||||
|
||||
```ts
|
||||
const html = source.toHTML(0, "A1:B2");
|
||||
const withFormulas = source.toHTML(0, "A1:B2", { formulas: true });
|
||||
|
||||
const result = target.fromHTML(0, html, "C3");
|
||||
const filled = target.fromHTML(0, html, "B2:C4");
|
||||
```
|
||||
|
||||
`sheetIndex` is zero-based. The optional range uses A1 syntax.
|
||||
|
||||
## Image Import
|
||||
|
||||
```ts
|
||||
const result = workbook.fromImage(
|
||||
0,
|
||||
{ bytes: imageBytes, contentType: "image/png" },
|
||||
"A1:D10",
|
||||
);
|
||||
```
|
||||
|
||||
### Worksheet Images
|
||||
|
||||
```ts
|
||||
const sheet = workbook.worksheets.getItem("Data");
|
||||
sheet.images.add({
|
||||
svg: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10" /></svg>',
|
||||
anchor: {
|
||||
from: { row: 0, col: 4 },
|
||||
extent: { widthPx: 48, heightPx: 48 },
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
## Chart To Image
|
||||
|
||||
```ts
|
||||
const result = await workbook.chartToImage(0, chart.id);
|
||||
```
|
||||
|
||||
## Render And Export
|
||||
|
||||
```ts
|
||||
const renderBlob = await workbook.render({
|
||||
sheet: "Data",
|
||||
range: "A1:C10",
|
||||
format: "png",
|
||||
scale: 2,
|
||||
});
|
||||
|
||||
const exportBlob = await workbook.export({
|
||||
sheetName: "Data",
|
||||
range: "A1:C10",
|
||||
format: "png",
|
||||
scale: 2,
|
||||
headers: true,
|
||||
});
|
||||
|
||||
const layoutBlob = await workbook.export({
|
||||
sheetName: "Data",
|
||||
range: "A1:C10",
|
||||
format: "layout",
|
||||
});
|
||||
|
||||
const allSheetsPdf = await workbook.export({ format: "pdf" });
|
||||
const uniformSheetsPdf = await workbook.export({
|
||||
format: "pdf",
|
||||
pageSizing: "uniform",
|
||||
headers: true,
|
||||
});
|
||||
const oneSheetPdf = await workbook.export({
|
||||
sheetName: "Data",
|
||||
format: "pdf",
|
||||
scale: 2,
|
||||
});
|
||||
const xlsxBlob = await workbook.export({
|
||||
format: "xlsx",
|
||||
fileName: "report.xlsx",
|
||||
});
|
||||
```
|
||||
|
||||
`format: "pdf"` exports all worksheets in workbook order. `sheet`, `sheetName`,
|
||||
or `sheetIndex` selects one worksheet. PDF `pageSizing` accepts `"per-sheet"`
|
||||
(default) or `"uniform"`.
|
||||
|
||||
`format: "layout"` exports sheet/range geometry, cell frames, styles, merged
|
||||
ranges, validations, defined names, and drawing anchors. It supports sheet
|
||||
selection, `range`, and `autoCrop`. `center`, `width`, and `height` apply to
|
||||
preview and PDF exports, not layout.
|
||||
|
||||
## Export Inline Types
|
||||
|
||||
```ts
|
||||
type WorkbookExportFormat = "png" | "jpeg" | "layout" | "xlsx" | "pdf";
|
||||
|
||||
type WorkbookExportOptions = {
|
||||
fileName?: string;
|
||||
sheet?: Worksheet | string | number;
|
||||
sheetName?: string;
|
||||
sheetIndex?: number;
|
||||
range?: string;
|
||||
center?: string;
|
||||
width?: number;
|
||||
height?: number;
|
||||
scale?: number;
|
||||
autoCrop?: "all" | "charts";
|
||||
headers?: boolean;
|
||||
format?: WorkbookExportFormat;
|
||||
quality?: number;
|
||||
pageSizing?: "per-sheet" | "uniform";
|
||||
};
|
||||
```
|
||||
|
||||
## Google Sheets
|
||||
|
||||
```ts
|
||||
const workbook = await Workbook.fromGoogleSheets(config);
|
||||
workbook.configureGoogleSheets(config);
|
||||
|
||||
const { patch } = workbook.record(() => {
|
||||
workbook.worksheets.getItem("Data").getRange("A1").values = [["Updated"]];
|
||||
});
|
||||
|
||||
await workbook.apply(patch, { target: "googleSheets" });
|
||||
```
|
||||
|
||||
## Cookbook
|
||||
|
||||
```ts
|
||||
const workbook = await Workbook.fromCSV(csv, { sheetName: "Data" });
|
||||
const preview = await workbook.export({
|
||||
sheetName: "Data",
|
||||
range: "A1:D20",
|
||||
format: "png",
|
||||
scale: 2,
|
||||
});
|
||||
const proto = workbook.toProto();
|
||||
```
|
||||
Generated
Vendored
+152
@@ -0,0 +1,152 @@
|
||||
# Inspect and Help
|
||||
|
||||
`workbook.inspect({ select, include })` queries a semantic workbook tree with RFC 9535 JSONPath. The [JSON Schema](inspect.schema.json) describes the nodes and value semantics.
|
||||
|
||||
## Navigate before reading cells
|
||||
|
||||
```ts
|
||||
const overview = await workbook.inspect({
|
||||
select: "$.sheets[*]",
|
||||
include: ["name", "range", "tables.name", "tables.range", "tables.columns.name"],
|
||||
});
|
||||
console.log(overview.records);
|
||||
|
||||
const statistics = await workbook.inspect({
|
||||
select: "$.sheets[?(@.name == 'Data')].columns[?(@.letter == 'B')].statistics",
|
||||
include: ["numericCount", "min", "max", "sum", "average", "errorCount"],
|
||||
});
|
||||
console.log(statistics.records);
|
||||
```
|
||||
|
||||
The tree contains `sheets` and workbook-scoped `definedNames`. Sheets contain native `tables`, `charts`, `drawings`, `pivotTables`, `sparklines`, `slicers`, what-if `dataTables`, `threads`, classic `notes`, `dataValidations`, `conditionalFormats`, `mergedRanges`, `freezePanes`, and layout metadata. Select the fields needed for the decision. Objects retain public names, drawing IDs, or fully qualified A1 addresses for subsequent edits.
|
||||
|
||||
`regions` describes inferred data blocks separately from native tables. Each region bounds cells connected horizontally or vertically through nonblank values or formulas. Rectangles can contain blanks and can overlap; their statistics describe the full rectangle. Region column names are copied from text in the first row, without inferring a formal header or changing the workbook.
|
||||
|
||||
```ts
|
||||
const regions = await workbook.inspect({
|
||||
select: "$.sheets[*].regions[*]",
|
||||
include: ["sheet", "range", "rowCount", "columnCount", "columns.name"],
|
||||
});
|
||||
|
||||
const sources = await workbook.inspect({
|
||||
select: "$.sheets[*].charts[*]",
|
||||
include: ["sheet", "id", "title", "type", "series.name", "series.formula", "series.categoryFormula"],
|
||||
});
|
||||
```
|
||||
|
||||
Statistics use finite computed numbers. Numeric-looking strings, dates, booleans, blanks, and errors are counted separately. `min`, `max`, and `average` are `null` without numeric values; `sum` is zero. An overflowing sum is `null`. Native table column statistics exclude headers and totals. Sheet and inferred-region column statistics cover their reported ranges.
|
||||
|
||||
## Search content, formulas, and appearance
|
||||
|
||||
```ts
|
||||
const matches = await workbook.inspect({
|
||||
select: "$.sheets[*].cells[?search(@.text, 'Revenue')]",
|
||||
include: ["sheet", "address", "text"],
|
||||
});
|
||||
|
||||
const errors = await workbook.inspect({
|
||||
select: "$.sheets[*].cells[?(@.formula && @.valueType == 'error')]",
|
||||
include: ["sheet", "address", "formula", "error"],
|
||||
});
|
||||
|
||||
const formatting = await workbook.inspect({
|
||||
select: "$.sheets[?(@.name == 'Data')].cells[?(@.row <= 10 && @.column <= 4)]",
|
||||
include: ["address", "value", "text", "computedStyle.numberFormat", "computedStyle.fillColor"],
|
||||
});
|
||||
```
|
||||
|
||||
Cells are sparse, sorted by row and column, and include materialized styled blanks. Untouched blank positions are absent; whole-row and whole-column layout spans are represented separately. Cell row/column numbers are one-based; sheet index is zero-based. `value` is JSON-safe, dates are ISO timestamps, and `valueType` distinguishes dates and errors from strings. Formulas include `=`. Follow the workbook calculation lifecycle: recalculate after formula/input edits before querying current computed results.
|
||||
|
||||
`text` is displayed text. `computedStyle` follows the renderer, including inheritance, table/pivot formatting, theme colors, number-format colors, and supported conditional effects. Fields contain format codes, readable alignments, point font sizes, and resolved colors. Conditional rule definitions are separately available, including visual effects such as data bars and icon sets.
|
||||
|
||||
Mixed rich text exposes resolved `runs`; `computedStyle.font` describes the cell default when runs differ. Cells also expose their `links`, applicable `validation`, and containing `mergedRange`. Sheet `layout` reports authored/default dimensions and hidden spans, without expanding entire rows or columns into blank cell records.
|
||||
|
||||
Filters run before exact projection. `include` is an array of fields on selected nodes; dotted paths project nested objects and arrays. JSONPath slices, unions, recursive traversal, and standard `match()`/`search()` functions work without another inspection language.
|
||||
|
||||
`match()` and `search()` are case-sensitive. For example, `search(@.text, '[Rr]evenue')` matches both `Revenue` and `revenue`. A legacy case-insensitive regex needs an explicit equivalent when moving to JSONPath.
|
||||
|
||||
## Complete results and sessions
|
||||
|
||||
```ts
|
||||
const result = await workbook.inspect({
|
||||
select: "$.sheets[*].cells[?(@.formula)]",
|
||||
include: ["sheet", "address"],
|
||||
fileName: "formula-addresses.ndjson",
|
||||
});
|
||||
console.log(result.recordCount);
|
||||
```
|
||||
|
||||
Files contain every selected record, with no hidden preview truncation. Narrow `select` and `include` to control size. `records` and `ndjson` remain available programmatically; ordinary result serialization returns count and output metadata. Return `result.records` explicitly from a session callback for a small immediate answer. Completed files are listed separately by the session runner.
|
||||
|
||||
```ts
|
||||
type WorkbookInspectQueryOptions = {
|
||||
select: string;
|
||||
include?: readonly string[];
|
||||
fileName?: string;
|
||||
};
|
||||
```
|
||||
|
||||
The previous `kind`/`searchTerm` API remains a separate overload. JSONPath requests use `select`, `include`, and `fileName` only.
|
||||
|
||||
## Find cells and API guidance
|
||||
|
||||
```ts
|
||||
const matches = workbook.findCells({
|
||||
searchTerm: "East", sheetId: "Data",
|
||||
options: { maxResults: 10, matchFormulas: true },
|
||||
});
|
||||
```
|
||||
|
||||
Result matches include sheet, address, value/formula match metadata, and total
|
||||
count.
|
||||
|
||||
## Help
|
||||
|
||||
```ts
|
||||
const help = workbook.help("*", {
|
||||
search: "colorScheme|worksheet.charts.add",
|
||||
include: ["index", "examples", "notes"],
|
||||
maxChars: 12000,
|
||||
});
|
||||
console.log(help.ndjson);
|
||||
```
|
||||
|
||||
Common queries:
|
||||
|
||||
```text
|
||||
*, workbook.colorScheme, worksheet.charts.add, formulas, enum.ChartType
|
||||
```
|
||||
|
||||
## Navigate inspection results
|
||||
|
||||
Inspection IDs use each object's public navigation API. Select worksheets with `workbook.worksheets.getItem(id)`, cells with `sheet.getRange(address)`, and inferred regions with `sheet.getRange(range)`. Native table and slicer IDs are names for their sheet collections' `getItem(id)` methods; pivot IDs work with `workbook.pivotTables.getItem(id)`. Drawings retain their collection IDs. Include `sheet` when selecting objects across sheets.
|
||||
|
||||
Returned chart (`ch/<id>`) and thread (`th/<id>`) anchors work directly with `workbook.resolve`. Legacy worksheet anchors (`ws/<id>`) also continue to work; an inspection sheet's `id` is its public name, rather than a `ws/` anchor.
|
||||
|
||||
## Create/Edit Loop
|
||||
|
||||
```ts
|
||||
const before = await workbook.inspect({
|
||||
select: "$.sheets[?(@.name == 'Data')].cells[?(@.row == 2 && @.column == 2)]",
|
||||
include: ["address", "value", "formula"],
|
||||
});
|
||||
|
||||
const sheet = workbook.worksheets.getItem("Data");
|
||||
sheet.getRange("B2").values = [["Closed"]];
|
||||
workbook.recalculate();
|
||||
|
||||
const after = await workbook.inspect({
|
||||
select: "$.sheets[?(@.name == 'Data')].cells[?(@.row == 2 && @.column == 2)]",
|
||||
include: ["address", "value", "formula"],
|
||||
});
|
||||
```
|
||||
|
||||
## Inline Types
|
||||
|
||||
```ts
|
||||
type WorkbookHelpOptions = {
|
||||
include?: string[] | string;
|
||||
search?: string;
|
||||
maxChars?: number;
|
||||
};
|
||||
```
|
||||
Generated
Vendored
+2283
File diff suppressed because it is too large
Load Diff
Generated
Vendored
+122
@@ -0,0 +1,122 @@
|
||||
# Pivot Tables
|
||||
|
||||
## Create and Summarize
|
||||
|
||||
```ts
|
||||
const data = workbook.worksheets.add("Data");
|
||||
const output = workbook.worksheets.add("Summary");
|
||||
data.getRange("A1:C5").values = [
|
||||
["Region", "Product", "Sales"],
|
||||
["East", "A", 10],
|
||||
["East", "B", 20],
|
||||
["West", "A", 30],
|
||||
["West", "B", 40],
|
||||
];
|
||||
|
||||
const pivot = output.pivotTables.add(
|
||||
"SalesSummary",
|
||||
data.getRange("A1:C5"),
|
||||
output.getRange("A1"),
|
||||
);
|
||||
pivot.rowHierarchies.add(pivot.hierarchies.getItem("Region"));
|
||||
pivot.columnHierarchies.add(pivot.hierarchies.getItem("Product"));
|
||||
const sales = pivot.dataHierarchies.add(pivot.hierarchies.getItem("Sales"));
|
||||
sales.summarizeBy = "Sum";
|
||||
sales.name = "Revenue";
|
||||
sales.numberFormat = "#,##0.00";
|
||||
pivot.layout.layoutType = "Tabular";
|
||||
|
||||
sales.field.name;
|
||||
pivot.layout.getDataBodyRange().values;
|
||||
```
|
||||
|
||||
## Show Values As
|
||||
|
||||
```ts
|
||||
sales.showAs = { calculation: "PercentOfGrandTotal" };
|
||||
sales.numberFormat = "0.0%";
|
||||
|
||||
const region = pivot.hierarchies.getItem("Region").fields.getItem("Region");
|
||||
sales.showAs = {
|
||||
calculation: "DifferenceFrom",
|
||||
baseField: region,
|
||||
baseItem: region.items.getItem("East"),
|
||||
};
|
||||
```
|
||||
|
||||
```ts
|
||||
sales.showAs = { calculation: "RunningTotal", baseField: region };
|
||||
sales.showAs = { calculation: "PercentRunningTotal", baseField: region };
|
||||
sales.showAs = { calculation: "RankDecending", baseField: region };
|
||||
sales.showAs = { calculation: "PercentOfParentRowTotal" };
|
||||
sales.showAs = { calculation: "Index" };
|
||||
```
|
||||
|
||||
## Layout, Subtotals, and Sorting
|
||||
|
||||
```ts
|
||||
pivot.layout.layoutType = "Tabular";
|
||||
pivot.layout.showRowGrandTotals = false;
|
||||
pivot.layout.showColumnGrandTotals = false;
|
||||
pivot.layout.subtotalLocation = "AtBottom"; // "AtTop" | "AtBottom" | "Off"
|
||||
pivot.layout.repeatAllItemLabels(true);
|
||||
pivot.layout.displayBlankLineAfterEachItem(false);
|
||||
pivot.styleName = "PivotStyleMedium2";
|
||||
pivot.layout.hideValuesRow = true;
|
||||
|
||||
region.subtotals = { automatic: false };
|
||||
region.subtotals = { sum: true, average: true, count: true };
|
||||
region.sortByLabels("Ascending");
|
||||
region.sortByValues("Descending", sales);
|
||||
```
|
||||
|
||||
```ts
|
||||
const product = pivot.hierarchies.getItem("Product").fields.getItem("Product");
|
||||
region.sortByValues("Descending", sales, [product.items.getItem("A")]);
|
||||
```
|
||||
|
||||
## Filter Fields
|
||||
|
||||
```ts
|
||||
region.applyFilter({ manualFilter: { selectedItems: ["East"] } });
|
||||
region.applyFilter({ labelFilter: { condition: "BeginsWith", substring: "E" } });
|
||||
region.applyFilter({
|
||||
valueFilter: { condition: "GreaterThan", comparator: 25, value: "Revenue" },
|
||||
});
|
||||
region.clearAllFilters();
|
||||
```
|
||||
|
||||
```ts
|
||||
region.getFilters();
|
||||
region.isFiltered();
|
||||
region.isFiltered("Value");
|
||||
region.clearFilter("Value");
|
||||
region.clearAllFilters();
|
||||
```
|
||||
|
||||
## Edit Hierarchies and Items
|
||||
|
||||
```ts
|
||||
const hierarchy = pivot.rowHierarchies.getItem("Region");
|
||||
hierarchy.name = "Area";
|
||||
hierarchy.position = 0;
|
||||
sales.position = 0;
|
||||
const item = region.items.getItem("East");
|
||||
item.name = "Atlantic";
|
||||
item.isExpanded = false;
|
||||
item.visible = false;
|
||||
```
|
||||
|
||||
## Read and Delete
|
||||
|
||||
```ts
|
||||
pivot.refresh();
|
||||
const existing = workbook.pivotTables.getItemOrNullObject("SalesSummary");
|
||||
if (existing !== null) {
|
||||
existing.dataHierarchies.items;
|
||||
existing.layout.getDataBodyRange();
|
||||
}
|
||||
pivot.rowHierarchies.remove(hierarchy);
|
||||
pivot.dataHierarchies.remove(sales);
|
||||
workbook.pivotTables.getItem("SalesSummary").delete();
|
||||
```
|
||||
Generated
Vendored
+150
@@ -0,0 +1,150 @@
|
||||
# Ranges
|
||||
|
||||
Ranges read and write cell values, formulas, formatting, validation,
|
||||
conditional formats, sparklines, merges, fills, and copies.
|
||||
|
||||
## Addressing
|
||||
|
||||
```ts
|
||||
const range = sheet.getRange("A1:B2");
|
||||
const byIndexes = sheet.getRangeByIndexes(0, 0, 2, 2);
|
||||
const cell = sheet.getCell(0, 0);
|
||||
|
||||
range.address;
|
||||
range.getAddress();
|
||||
range.rowIndex;
|
||||
range.columnIndex;
|
||||
range.rowCount;
|
||||
range.columnCount;
|
||||
```
|
||||
|
||||
## Values
|
||||
|
||||
```ts
|
||||
sheet.getRange("A1:B2").values = [
|
||||
[1, 2],
|
||||
[3, 4],
|
||||
];
|
||||
|
||||
sheet.getRange("B1:I1").values = [1, 2, 3, 4, 5, 6, 7, 8];
|
||||
sheet.getRange("A2:A5").values = ["a", "b", "c", "d"];
|
||||
```
|
||||
|
||||
Single-cell ranges can spill larger matrices:
|
||||
|
||||
```ts
|
||||
sheet.getRange("N9").values = [[1, 2, 3]];
|
||||
sheet.getRange("B2").values = [[1], [2], [3]];
|
||||
```
|
||||
|
||||
## Formulas
|
||||
|
||||
```ts
|
||||
sheet.getRange("C1").values = [["=SUM(A1:B1)"]];
|
||||
sheet.getRange("D1").values = [["'=SUM(A1:B1)"]];
|
||||
|
||||
sheet.getRange("C1:C2").formulas = [["=A1+B1"], ["=A2+B2"]];
|
||||
sheet.getRange("B3:E3").formulas = ["=1+1", "=2+2", "=3+3", "=4+4"];
|
||||
sheet.getRange("G2:G5").formulas = ["=10", "=11", "=12", "=13"];
|
||||
```
|
||||
|
||||
## Write
|
||||
|
||||
```ts
|
||||
sheet.getRange("A1").write([
|
||||
["Name", "Value"],
|
||||
["A", 1],
|
||||
]);
|
||||
|
||||
sheet.getRange("C1").write({ formulas: [["=SUM(B2:B10)"]] });
|
||||
sheet.getRange("E1").write({ values: [["Literal"]] }, { overwrite: "error" });
|
||||
```
|
||||
|
||||
## Format
|
||||
|
||||
```ts
|
||||
range.format = {
|
||||
fill: "#f8fafc",
|
||||
font: { bold: true, color: "#0f172a" },
|
||||
numberFormat: "$#,##0.00",
|
||||
horizontalAlignment: "center",
|
||||
verticalAlignment: "middle",
|
||||
wrapText: true,
|
||||
rowHeightPx: 28,
|
||||
columnWidthPx: 120,
|
||||
};
|
||||
|
||||
range.setNumberFormat("0.0%");
|
||||
```
|
||||
|
||||
## Navigation
|
||||
|
||||
```ts
|
||||
range.getCell(0, 1);
|
||||
range.getRow(0);
|
||||
range.getColumn(1);
|
||||
range.getRange("A1");
|
||||
range.getRangeByIndexes(0, 0, 1, 1);
|
||||
range.getOffsetRange(1, 0);
|
||||
range.getResizedRange(2, 3);
|
||||
range.getResizeRange(10, 4);
|
||||
range.offset(1, 0);
|
||||
range.resize(10, 4);
|
||||
range.getCurrentRegion();
|
||||
```
|
||||
|
||||
## Clear, Merge, Fill, Copy
|
||||
|
||||
```ts
|
||||
range.clear({ applyTo: "contents" });
|
||||
range.clear({ applyTo: "formats" });
|
||||
range.clear({ applyTo: "all" });
|
||||
|
||||
range.merge();
|
||||
range.unmerge();
|
||||
|
||||
range.fillDown();
|
||||
range.fillRight();
|
||||
range.fillFrom(sourceRange);
|
||||
|
||||
range.copyFrom(sourceRange);
|
||||
range.copyTo(targetRange);
|
||||
range.copyFrom(sourceRange, "values");
|
||||
range.copyTo(targetRange, "formulas");
|
||||
```
|
||||
|
||||
## Inline Types
|
||||
|
||||
```ts
|
||||
type CellValue = string | number | boolean | Date | null;
|
||||
|
||||
type RangeWriteOptions = {
|
||||
clear?: "contents" | "formats" | "all";
|
||||
overwrite?: "allow" | "error";
|
||||
resize?: "auto" | "none";
|
||||
};
|
||||
|
||||
type RangeWritePayload =
|
||||
| CellValue[][]
|
||||
| CellValue[]
|
||||
| null
|
||||
| {
|
||||
values?: CellValue[][] | CellValue[] | null;
|
||||
formulas?: string[][] | string[];
|
||||
formulasR1C1?: string[][] | string[];
|
||||
};
|
||||
```
|
||||
|
||||
## Cookbook
|
||||
|
||||
```ts
|
||||
const data = sheet.getRange("A1:C4");
|
||||
data.values = [
|
||||
["Region", "Q1", "Q2"],
|
||||
["North", 10, 12],
|
||||
["South", 8, 9],
|
||||
["Total", null, null],
|
||||
];
|
||||
sheet.getRange("B4:C4").formulas = [["=SUM(B2:B3)", "=SUM(C2:C3)"]];
|
||||
data.format = { numberFormat: "General", wrapText: true };
|
||||
```
|
||||
Generated
Vendored
+93
@@ -0,0 +1,93 @@
|
||||
# Tables
|
||||
|
||||
Worksheet tables are created from an existing range and can edit rows, headers,
|
||||
data body ranges, names, style, and totals.
|
||||
|
||||
## Add Table
|
||||
|
||||
```ts
|
||||
const sheet = workbook.worksheets.add("Inventory");
|
||||
sheet.getRange("A1:C3").values = [
|
||||
["SKU", "Color", "Stock"],
|
||||
["100-001", "Black", 15],
|
||||
["100-002", "Sage", 40],
|
||||
];
|
||||
|
||||
const table = sheet.tables.add("A1:C3", true, "InventoryTable");
|
||||
```
|
||||
|
||||
## Read
|
||||
|
||||
```ts
|
||||
sheet.tables.items;
|
||||
sheet.tables.getItem("InventoryTable");
|
||||
sheet.tables.getItemAt(0);
|
||||
sheet.tables.getItemById(table.id);
|
||||
sheet.tables.getIntersecting(sheet.getRange("A1:C5"));
|
||||
|
||||
table.id;
|
||||
table.name;
|
||||
table.rowCount; // data rows, excluding headers and totals
|
||||
table.columnCount;
|
||||
table.columnNames;
|
||||
table.address;
|
||||
table.getRange();
|
||||
table.getHeaderRowRange();
|
||||
table.getDataRows();
|
||||
```
|
||||
|
||||
## Configure and Resize
|
||||
|
||||
```ts
|
||||
table.name = "InventoryTable";
|
||||
table.style = "TableStyleMedium9";
|
||||
table.showHeaders = true;
|
||||
table.showFilterButton = true;
|
||||
table.showTotals = false;
|
||||
table.showBandedRows = true;
|
||||
table.showBandedColumns = false;
|
||||
table.highlightFirstColumn = false;
|
||||
table.highlightLastColumn = false;
|
||||
table.resize("A1:C8");
|
||||
```
|
||||
|
||||
## Add Rows
|
||||
|
||||
```ts
|
||||
table.rows.add(null, [["100-003", "Denim", 12]]);
|
||||
```
|
||||
|
||||
## Headerless Table
|
||||
|
||||
```ts
|
||||
sheet.getRange("A1:B3").values = [
|
||||
["West", 12],
|
||||
["East", 9],
|
||||
["South", 15],
|
||||
];
|
||||
sheet.tables.add("A1:B3", false, "HeaderlessTable");
|
||||
```
|
||||
|
||||
## Recorded Table Edit
|
||||
|
||||
```ts
|
||||
const { patch } = workbook.record(() => {
|
||||
const table = sheet.tables.add("A1:C3", true, "InventoryTable");
|
||||
table.rows.add(null, [["100-003", "Denim", 12]]);
|
||||
});
|
||||
```
|
||||
|
||||
The recorded patch uses `table.add` followed by row/column/table operations for
|
||||
subsequent edits.
|
||||
|
||||
## Cookbook
|
||||
|
||||
```ts
|
||||
const table = sheet.tables.add("A1:D5", true, "DataTable");
|
||||
table.rows.add(null, [["West", "Ava", 12, 14]]);
|
||||
|
||||
sheet.getRange(table.address).format = {
|
||||
font: { name: "Aptos" },
|
||||
wrapText: true,
|
||||
};
|
||||
```
|
||||
Generated
Vendored
+129
@@ -0,0 +1,129 @@
|
||||
# Workbook Facade
|
||||
|
||||
## Create And Load
|
||||
|
||||
```ts
|
||||
const workbook = Workbook.create();
|
||||
const [sheet1, sheet2] = workbook.worksheets.add(["Sheet1", "Sheet2"]);
|
||||
const loaded = Workbook.load(proto);
|
||||
const validated = Workbook.load(proto, { validate: true });
|
||||
```
|
||||
|
||||
## Import
|
||||
|
||||
```ts
|
||||
const fromCsv = await Workbook.fromCSV(csv, { sheetName: "Data" });
|
||||
const fromMarkdown = await Workbook.fromMarkdown(markdown, {
|
||||
sheetName: "Data",
|
||||
format: true,
|
||||
});
|
||||
|
||||
const { sheet, range } = await workbook.fromCSV(csv, { sheetName: "Data" });
|
||||
```
|
||||
|
||||
## Root Collections
|
||||
|
||||
```ts
|
||||
workbook.worksheets;
|
||||
workbook.sheets; // alias
|
||||
workbook.pivotTables;
|
||||
workbook.slicers;
|
||||
workbook.comments;
|
||||
workbook.notes;
|
||||
workbook.names;
|
||||
workbook.definedNames; // alias
|
||||
workbook.awareness;
|
||||
```
|
||||
|
||||
## Theme
|
||||
|
||||
```ts
|
||||
workbook.colorScheme = {
|
||||
name: "Workbook Theme",
|
||||
themeColors: {
|
||||
accent1: "#2563eb",
|
||||
bg1: "#ffffff",
|
||||
tx1: "#0f172a",
|
||||
},
|
||||
};
|
||||
const theme = workbook.theme;
|
||||
```
|
||||
|
||||
## Recalculate And Trace
|
||||
|
||||
```ts
|
||||
workbook.recalculate();
|
||||
const trace = workbook.trace("Data!C2");
|
||||
const stats = workbook.collectFormulaUsageStats();
|
||||
```
|
||||
|
||||
## Inspect, Search, Help, Resolve
|
||||
|
||||
```ts
|
||||
const snapshot = await workbook.inspect({ kind: "sheet,table,formula" });
|
||||
const matches = workbook.findCells({
|
||||
searchTerm: "East",
|
||||
sheetId: "Revenue",
|
||||
options: { maxResults: 10, matchFormulas: true },
|
||||
});
|
||||
const help = workbook.help("*", {
|
||||
search: "colorScheme|worksheet.charts.add",
|
||||
include: ["index", "examples", "notes"],
|
||||
});
|
||||
const target = workbook.resolve(anchorId);
|
||||
```
|
||||
|
||||
## Record And Apply
|
||||
|
||||
```ts
|
||||
const { result, patch, idMap, crdtUpdateV2 } = workbook.record(() => {
|
||||
const sheet = workbook.worksheets.getItem("Data");
|
||||
sheet.getRange("A1").values = [["Value"]];
|
||||
return sheet;
|
||||
});
|
||||
|
||||
const applied = workbook.apply(patch);
|
||||
```
|
||||
|
||||
## CRDT
|
||||
|
||||
```ts
|
||||
workbook.hydrateCrdtFromProto();
|
||||
const ready = workbook.isCollaborativeStateReady();
|
||||
const unsubscribe = workbook.onCrdtUpdateV2((update, origin) => {
|
||||
send(update);
|
||||
});
|
||||
workbook.applyCrdtUpdateV2(remoteUpdate, { recalculate: true });
|
||||
unsubscribe();
|
||||
```
|
||||
|
||||
## Serialize
|
||||
|
||||
```ts
|
||||
const proto = workbook.toProto();
|
||||
```
|
||||
|
||||
## Utilities
|
||||
|
||||
```ts
|
||||
workbook.utils.columnToLetter(1); // "A"
|
||||
workbook.utils.letterToColumn("AA"); // 27
|
||||
workbook.utils.toA1String(1, 1, 3, 2); // "A1:B3"
|
||||
workbook.utils.fillRight([[1]], 3); // [[1, 1, 1]]
|
||||
workbook.utils.fillDown([[1]], 3); // [[1], [1], [1]]
|
||||
```
|
||||
|
||||
## Cookbook
|
||||
|
||||
```ts
|
||||
const workbook = Workbook.create();
|
||||
const sheet = workbook.worksheets.add("Data");
|
||||
sheet.getRange("A1:B2").values = [
|
||||
["Name", "Value"],
|
||||
["A", 1],
|
||||
];
|
||||
|
||||
const { patch } = workbook.record(() => {
|
||||
sheet.getRange("B2").values = [[2]];
|
||||
});
|
||||
```
|
||||
Generated
Vendored
+122
@@ -0,0 +1,122 @@
|
||||
# Worksheets
|
||||
|
||||
`workbook.worksheets` and `workbook.sheets` expose the worksheet collection.
|
||||
|
||||
## Collection
|
||||
|
||||
```ts
|
||||
const sheet = workbook.worksheets.add("Data");
|
||||
workbook.worksheets.add("New data", { ifExists: "error" });
|
||||
const existing = workbook.worksheets.getItem("Data");
|
||||
const maybe = workbook.worksheets.getItemOrNullObject("Data");
|
||||
const first = workbook.worksheets.getFirst();
|
||||
const active = workbook.worksheets.getActiveWorksheet();
|
||||
|
||||
workbook.worksheets.setActiveWorksheet("Data");
|
||||
const count = workbook.worksheets.getSheetCount();
|
||||
const index = workbook.worksheets.getSheetIndex("Data");
|
||||
const name = workbook.worksheets.getSheetNameByIndex(0);
|
||||
const byIndex = workbook.worksheets.getItemAt(0);
|
||||
```
|
||||
|
||||
## Worksheet Properties
|
||||
|
||||
```ts
|
||||
sheet.name = "Renamed";
|
||||
sheet.index = 0;
|
||||
sheet.showGridLines = false;
|
||||
sheet.tabColor = "#1F4E78";
|
||||
sheet.freezePanes.freezeRows(1);
|
||||
sheet.freezePanes.freezeColumns(1);
|
||||
|
||||
sheet.id;
|
||||
sheet.sheetId;
|
||||
sheet.tabColor;
|
||||
sheet.defaultRowHeight;
|
||||
sheet.defaultColWidth;
|
||||
sheet.baseColWidth;
|
||||
```
|
||||
|
||||
## Ranges
|
||||
|
||||
```ts
|
||||
const range = sheet.getRange("A1:B2");
|
||||
const byIndexes = sheet.getRangeByIndexes(0, 0, 2, 2);
|
||||
const cell = sheet.getCell(0, 0);
|
||||
const used = sheet.getUsedRange();
|
||||
const usedValuesOnly = sheet.getUsedRange(true);
|
||||
```
|
||||
|
||||
`getRange` accepts A1 strings only. Use zero-based row/column indexes with
|
||||
`getRangeByIndexes` and `getCell`.
|
||||
|
||||
## Worksheet Collections
|
||||
|
||||
```ts
|
||||
sheet.tables;
|
||||
sheet.charts;
|
||||
sheet.shapes;
|
||||
sheet.images;
|
||||
sheet.pivotTables;
|
||||
sheet.slicers;
|
||||
sheet.sparklineGroups;
|
||||
sheet.conditionalFormattings;
|
||||
sheet.dataValidations;
|
||||
sheet.freezePanes;
|
||||
sheet.names;
|
||||
sheet.cells;
|
||||
```
|
||||
|
||||
## Reset And Delete
|
||||
|
||||
```ts
|
||||
sheet.reset({
|
||||
clear: "used",
|
||||
applyTo: "all",
|
||||
deleteTables: true,
|
||||
deleteCharts: true,
|
||||
deleteDrawings: true,
|
||||
deleteSparklines: true,
|
||||
});
|
||||
|
||||
sheet.delete();
|
||||
```
|
||||
|
||||
## Merge
|
||||
|
||||
```ts
|
||||
sheet.mergeCells("A1:B2");
|
||||
sheet.unmergeCells("A1:B2");
|
||||
```
|
||||
|
||||
## Drawings
|
||||
|
||||
```ts
|
||||
sheet.deleteAllDrawings();
|
||||
sheet.autoLayoutDrawings(items, options);
|
||||
```
|
||||
|
||||
## Inline Types
|
||||
|
||||
```ts
|
||||
type WorksheetResetOptions = {
|
||||
clear?: "used" | "none";
|
||||
applyTo?: "contents" | "formats" | "all";
|
||||
deleteTables?: boolean;
|
||||
deleteCharts?: boolean;
|
||||
deleteDrawings?: boolean;
|
||||
deleteSparklines?: boolean;
|
||||
};
|
||||
```
|
||||
|
||||
## Cookbook
|
||||
|
||||
```ts
|
||||
const sheet = workbook.worksheets.add("Data");
|
||||
sheet.getRange("A1:B2").values = [
|
||||
["Name", "Value"],
|
||||
["A", 1],
|
||||
];
|
||||
sheet.mergeCells("D1:E1");
|
||||
sheet.freezePanes.freezeRows(1);
|
||||
```
|
||||
Generated
Vendored
+56
@@ -0,0 +1,56 @@
|
||||
# Sparklines
|
||||
|
||||
```js
|
||||
const group = sheet.sparklineGroups.add({
|
||||
type: "line",
|
||||
targetRange: "E2:E4",
|
||||
sourceData: "A2:C4",
|
||||
seriesColor: "#2563EB",
|
||||
markers: { high: true, low: true },
|
||||
});
|
||||
```
|
||||
- Sparkline type is a string. Use the public options documented below. Do not set internal/proto enum values for empty-cell display or axis modes; if a required option is not documented for the selected runtime, follow the bounded discovery policy.
|
||||
- Avoid `dateAxisRange` for XLSX output; it is not serialized. Keep automatic axis limits: `manualMin` / `manualMax` alone do not select custom limits in Excel.
|
||||
- Sparkline Inline Type:
|
||||
```
|
||||
type SparklineConfig = {
|
||||
type: "line" | "column" | "stacked";
|
||||
targetRange: Range | string;
|
||||
sourceData: Range | string;
|
||||
lineWeight?: number;
|
||||
displayHidden?: boolean;
|
||||
seriesColor?: ColorConfig;
|
||||
negativeColor?: ColorConfig;
|
||||
axisColor?: ColorConfig;
|
||||
markersColor?: ColorConfig;
|
||||
firstMarkerColor?: ColorConfig;
|
||||
lastMarkerColor?: ColorConfig;
|
||||
highMarkerColor?: ColorConfig;
|
||||
lowMarkerColor?: ColorConfig;
|
||||
markers?: SparklineMarkersOptions;
|
||||
axis?: SparklineAxisOptions;
|
||||
};
|
||||
|
||||
type SparklineMarkersOptions = {
|
||||
show?: boolean;
|
||||
high?: boolean;
|
||||
low?: boolean;
|
||||
first?: boolean;
|
||||
last?: boolean;
|
||||
negative?: boolean;
|
||||
};
|
||||
|
||||
type SparklineAxisOptions = {
|
||||
showAxis?: boolean;
|
||||
rightToLeft?: boolean;
|
||||
};
|
||||
```
|
||||
- Range Alias: `const group = targetRange.sparklines.add(type, sourceRange, sparklineConfig);`
|
||||
- Edit And Delete
|
||||
```js
|
||||
group.seriesColor = "#2563EB";
|
||||
group.markers.high = true;
|
||||
group.axis.showAxis = true;
|
||||
sheet.sparklineGroups.delete(group);
|
||||
sheet.sparklineGroups.deleteAll();
|
||||
```
|
||||
Generated
Vendored
+97
@@ -0,0 +1,97 @@
|
||||
import fs from "node:fs/promises";
|
||||
|
||||
import { SpreadsheetFile, Workbook, ChartDataLabels } from "@oai/artifact-tool";
|
||||
|
||||
async function buildChartSuggestionWorkbook(outputDir: string): Promise<void> {
|
||||
await fs.mkdir(outputDir, { recursive: true });
|
||||
|
||||
const workbook = Workbook.create();
|
||||
const sheet = workbook.worksheets.add("Charts");
|
||||
sheet.showGridLines = false;
|
||||
|
||||
sheet.getRange("A1:C5").values = [
|
||||
["Month", "Revenue", "EBITDA"],
|
||||
["Jan", 100000, 18000],
|
||||
["Feb", 121000, 23000],
|
||||
["Mar", 132000, 28000],
|
||||
["Apr", 149000, 34000],
|
||||
];
|
||||
sheet.getRange("A1:C1").format = {
|
||||
fill: "#0F766E",
|
||||
font: { bold: true, color: "#FFFFFF" },
|
||||
};
|
||||
sheet.getRange("B2:C5").format.numberFormat = "$#,##0";
|
||||
sheet.getRange("A:C").format.columnWidthPx = 96;
|
||||
|
||||
// Fast chart path: chart a continuous helper range. The helper range is
|
||||
// formula-backed so edits to the source table update the chart.
|
||||
sheet.getRange("F1:H1").values = [["Month", "Revenue", "EBITDA"]];
|
||||
sheet.getRange("F2:H2").formulas = [["=A2", "=B2", "=C2"]];
|
||||
sheet.getRange("F2:H5").fillDown();
|
||||
const lineChart = sheet.charts.add("line", sheet.getRange("F1:H5"));
|
||||
lineChart.setPosition("J1", "Q15");
|
||||
lineChart.title = "Revenue and EBITDA Trend";
|
||||
lineChart.titleTextStyle.fontSize = 12;
|
||||
lineChart.hasLegend = true;
|
||||
lineChart.xAxis = { axisType: "textAxis" };
|
||||
lineChart.yAxis = { numberFormatCode: "$#,##0" };
|
||||
|
||||
const scatterPlot = sheet.charts.add("scatter", sheet.getRange("F1:H5"));
|
||||
scatterPlot.setPosition("J1", "Q15");
|
||||
scatterPlot.title = "Revenue and EBITDA Trend Scatter";
|
||||
scatterPlot.titleTextStyle.fontSize = 12;
|
||||
scatterPlot.hasLegend = true;
|
||||
scatterPlot.xAxis = { axisType: "textAxis" };
|
||||
scatterPlot.yAxis = { numberFormatCode: "$#,##0" };
|
||||
scatterPlot.dataLabels = new ChartDataLabels({showValue: true, position: 'above' });
|
||||
|
||||
// Advanced path: manually define a single series by formula.
|
||||
const barChart = sheet.charts.add("bar", {
|
||||
title: "EBITDA by Month",
|
||||
hasLegend: false,
|
||||
});
|
||||
const series = barChart.series.add("EBITDA");
|
||||
series.categoryFormula = "'Charts'!$A$2:$A$5";
|
||||
series.formula = "'Charts'!$C$2:$C$5";
|
||||
series.fill = "#F472B6";
|
||||
barChart.setPosition("J18", "Q32");
|
||||
barChart.title = "EBITDA by Month";
|
||||
barChart.titleTextStyle.fontSize = 12;
|
||||
barChart.xAxis = { axisType: "textAxis", textStyle: { fontSize: 10} };
|
||||
barChart.yAxis = { numberFormatCode: "$#,##0", textStyle: { fontSize: 10} };
|
||||
|
||||
barChart.xAxis.title.text = "EBITDA";
|
||||
|
||||
barChart.yAxis.title.text = "Month";
|
||||
barChart.yAxis.min = 10_000;
|
||||
barChart.yAxis.max = 40_000;
|
||||
barChart.yAxis.majorUnit = 5;
|
||||
// TODO @vicky set default title text to be size 12
|
||||
|
||||
// setData replaces the chart source range; use it when a chart exists before
|
||||
// the final source range is known.
|
||||
lineChart.setData(sheet.getRange("F1:H5"));
|
||||
|
||||
const preview = await workbook.render({
|
||||
sheetName: "Charts",
|
||||
autoCrop: "all",
|
||||
scale: 1,
|
||||
format: "png",
|
||||
});
|
||||
await fs.writeFile(
|
||||
`${outputDir}/typescript_chart_suggestions.png`,
|
||||
new Uint8Array(await preview.arrayBuffer()),
|
||||
);
|
||||
|
||||
const xlsx = await SpreadsheetFile.exportXlsx(workbook);
|
||||
await xlsx.save(`${outputDir}/typescript_chart_suggestions.xlsx`);
|
||||
|
||||
console.log(`Rendered ${outputDir}/typescript_chart_suggestions.png`);
|
||||
console.log(`Saved ${outputDir}/typescript_chart_suggestions.xlsx`);
|
||||
}
|
||||
|
||||
const outputDir = process.argv[2] ?? "output/chart_suggestions";
|
||||
buildChartSuggestionWorkbook(outputDir).catch((error: unknown) => {
|
||||
console.error(error);
|
||||
process.exit(1);
|
||||
});
|
||||
Generated
Vendored
+177
@@ -0,0 +1,177 @@
|
||||
import { Workbook } from "@oai/artifact-tool";
|
||||
|
||||
function clip(value: string, maxChars: number): string {
|
||||
return value.length > maxChars ? `${value.slice(0, maxChars)}...` : value;
|
||||
}
|
||||
|
||||
function summarizeTrace(
|
||||
root: any,
|
||||
options: { maxDepth?: number; maxNodes?: number; maxFormulaChars?: number } = {},
|
||||
): string[] {
|
||||
if (!root) return ["(no trace returned)"];
|
||||
|
||||
const maxDepth = options.maxDepth ?? 4;
|
||||
const maxNodes = options.maxNodes ?? 30;
|
||||
const maxFormulaChars = options.maxFormulaChars ?? 120;
|
||||
const lines: string[] = [];
|
||||
let nodeCount = 0;
|
||||
let truncated = false;
|
||||
|
||||
function walk(node: any, depth: number): void {
|
||||
if (nodeCount >= maxNodes) {
|
||||
truncated = true;
|
||||
return;
|
||||
}
|
||||
|
||||
nodeCount += 1;
|
||||
const indent = " ".repeat(depth);
|
||||
const formula = node.formula
|
||||
? ` formula=${clip(String(node.formula), maxFormulaChars)}`
|
||||
: "";
|
||||
const error = node.error ? ` error=${node.error}` : "";
|
||||
lines.push(`${indent}${node.cell} value=${JSON.stringify(node.value)}${formula}${error}`);
|
||||
|
||||
const children = (node.params ?? []) as any[];
|
||||
if (children.length === 0) return;
|
||||
if (depth >= maxDepth) {
|
||||
truncated = true;
|
||||
lines.push(`${indent} ... ${children.length} precedent(s) not shown`);
|
||||
return;
|
||||
}
|
||||
for (const child of children) {
|
||||
walk(child, depth + 1);
|
||||
}
|
||||
}
|
||||
|
||||
walk(root, 0);
|
||||
if (truncated) lines.push(`... trace summary capped at depth ${maxDepth}, ${maxNodes} nodes`);
|
||||
return lines;
|
||||
}
|
||||
|
||||
function findTraceNode(root: any, cell: string): any | null {
|
||||
if (!root) return null;
|
||||
if (root.cell === cell) return root;
|
||||
for (const child of (root.params ?? []) as any[]) {
|
||||
const found = findTraceNode(child, cell);
|
||||
if (found) return found;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function formatNumber(value: unknown): string {
|
||||
if (typeof value !== "number") return String(value);
|
||||
if (value !== 0 && Math.abs(value) < 0.01) return Number(value.toPrecision(3)).toString();
|
||||
return value.toLocaleString("en-US", { maximumFractionDigits: 2 });
|
||||
}
|
||||
|
||||
function formatPercent(value: unknown): string {
|
||||
return typeof value === "number" ? `${(value * 100).toFixed(1)}%` : String(value);
|
||||
}
|
||||
|
||||
function explainRevenueCheck(trace: any): string {
|
||||
const status = findTraceNode(trace, "Checks!F2")?.value;
|
||||
const difference = findTraceNode(trace, "Checks!D2")?.value;
|
||||
const actual = findTraceNode(trace, "Checks!B2")?.value;
|
||||
const expected = findTraceNode(trace, "Checks!C2")?.value;
|
||||
const tolerance = findTraceNode(trace, "Checks!E2")?.value;
|
||||
const baseRevenue = findTraceNode(trace, "Inputs!B2")?.value;
|
||||
const growthRate = findTraceNode(trace, "Inputs!B3")?.value;
|
||||
const revenue2025 = findTraceNode(trace, "Model!B4")?.value;
|
||||
|
||||
return [
|
||||
`Checks!F2 returns "${status}" because the absolute difference is within the tolerance.`,
|
||||
`It compares Checks!D2 (${formatNumber(difference)}) against Checks!E2 (${formatNumber(tolerance)}).`,
|
||||
`Checks!D2 is actual revenue minus expected revenue: Checks!B2 (${formatNumber(actual)}) - Checks!C2 (${formatNumber(expected)}).`,
|
||||
`The actual value comes from Model!B5, which compounds Inputs!B2 (${formatNumber(baseRevenue)}) by the growth rate in Inputs!B3 (${formatPercent(growthRate)}) for two years: first to Model!B4 (${formatNumber(revenue2025)}), then to Model!B5 (${formatNumber(actual)}).`,
|
||||
`Caveat: the tiny difference shown is floating-point rounding noise, not a business variance.`,
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const workbook = Workbook.create();
|
||||
const inputs = workbook.worksheets.add("Inputs");
|
||||
const model = workbook.worksheets.add("Model");
|
||||
const checks = workbook.worksheets.add("Checks");
|
||||
|
||||
inputs.getRange("A1:B4").values = [
|
||||
["Metric", "Value"],
|
||||
["Revenue 2024", 100],
|
||||
["Growth Rate", 0.1],
|
||||
["Expected Revenue 2026", 121],
|
||||
];
|
||||
|
||||
model.getRange("A1:B5").values = [
|
||||
["Metric", "Value"],
|
||||
["Revenue 2024", null],
|
||||
["Growth Rate", null],
|
||||
["Revenue 2025", null],
|
||||
["Revenue 2026", null],
|
||||
];
|
||||
model.getRange("B2:B5").formulas = [
|
||||
["=Inputs!B2"],
|
||||
["=Inputs!B3"],
|
||||
["=B2*(1+B3)"],
|
||||
["=B4*(1+B3)"],
|
||||
];
|
||||
|
||||
checks.getRange("A1:F2").values = [
|
||||
["Check", "Actual", "Expected", "Difference", "Tolerance", "Status"],
|
||||
["Revenue 2026 ties to expected case", null, null, null, 0.001, null],
|
||||
];
|
||||
checks.getRange("B2:D2").formulas = [["=Model!B5", "=Inputs!B4", "=B2-C2"]];
|
||||
checks.getRange("F2").formulas = [["=IF(ABS(D2)<=E2,\"OK\",\"CHECK\")"]];
|
||||
|
||||
workbook.recalculate();
|
||||
const trace = workbook.trace("Checks!F2");
|
||||
|
||||
console.log("=== Formula trace for Checks!F2 ===");
|
||||
console.log(
|
||||
summarizeTrace(trace, {
|
||||
maxDepth: 4,
|
||||
maxNodes: 20,
|
||||
}).join("\n"),
|
||||
);
|
||||
|
||||
console.log("\n=== User-facing answer: How is Checks!F2 calculated? ===");
|
||||
console.log(explainRevenueCheck(trace));
|
||||
|
||||
console.log("\n=== Exact formula help: XLOOKUP ===");
|
||||
console.log(
|
||||
workbook.help("fx.XLOOKUP", {
|
||||
include: "index,examples,notes",
|
||||
maxChars: 2500,
|
||||
}).ndjson,
|
||||
);
|
||||
|
||||
console.log("\n=== Formula category browse: financial ===");
|
||||
console.log(
|
||||
workbook.help("fx.*", {
|
||||
search: "financial",
|
||||
include: "index,examples",
|
||||
maxChars: 2500,
|
||||
}).ndjson,
|
||||
);
|
||||
|
||||
console.log("\n=== Formula category browse: math-trig ===");
|
||||
console.log(
|
||||
workbook.help("fx.*", {
|
||||
search: "math-trig",
|
||||
include: "index,examples",
|
||||
maxChars: 2500,
|
||||
}).ndjson,
|
||||
);
|
||||
|
||||
console.log("\n=== Semantic formula search: lookup with fallback ===");
|
||||
console.log(
|
||||
workbook.help("lookup value with fallback", {
|
||||
search: "XLOOKUP|INDEX|MATCH|IFERROR",
|
||||
include: "index,examples,notes",
|
||||
maxChars: 3000,
|
||||
}).ndjson,
|
||||
);
|
||||
}
|
||||
|
||||
main().catch((error: unknown) => {
|
||||
console.error(error);
|
||||
process.exit(1);
|
||||
});
|
||||
Generated
Vendored
+113
@@ -0,0 +1,113 @@
|
||||
import * as fs from "node:fs/promises";
|
||||
import * as path from "node:path";
|
||||
|
||||
import {
|
||||
FileBlob,
|
||||
SpreadsheetFile,
|
||||
} from "../../../../oai_js_artifact_tool";
|
||||
|
||||
const DEFAULT_WORKBOOK_INPUTS = [
|
||||
"/Users/vicky/code/openai/output/spreadsheet-atv/fitness-tracker-20260409",
|
||||
];
|
||||
|
||||
type InspectResult = {
|
||||
ndjson: string;
|
||||
};
|
||||
|
||||
async function resolveWorkbookPath(inputPath: string): Promise<string> {
|
||||
const expandedPath = inputPath.startsWith("~")
|
||||
? path.join(process.env.HOME ?? "", inputPath.slice(1))
|
||||
: inputPath;
|
||||
const stats = await fs.stat(expandedPath);
|
||||
if (stats.isFile()) {
|
||||
return expandedPath;
|
||||
}
|
||||
if (stats.isDirectory()) {
|
||||
const candidates = (await fs.readdir(expandedPath))
|
||||
.filter((entry) => entry.endsWith(".xlsx"))
|
||||
.sort();
|
||||
if (candidates.length > 0) {
|
||||
return path.join(expandedPath, candidates[0]);
|
||||
}
|
||||
throw new Error(`No .xlsx files found in directory: ${expandedPath}`);
|
||||
}
|
||||
throw new Error(`Workbook path is not a file or directory: ${expandedPath}`);
|
||||
}
|
||||
|
||||
function printInspect(title: string, result: InspectResult): void {
|
||||
console.log(`\n=== ${title} ===`);
|
||||
if (result.ndjson) {
|
||||
console.log(result.ndjson);
|
||||
return;
|
||||
}
|
||||
console.log("(no rows returned)");
|
||||
}
|
||||
|
||||
async function inspectWorkbook(workbookPath: string): Promise<void> {
|
||||
const workbook = await SpreadsheetFile.importXlsx(await FileBlob.load(workbookPath));
|
||||
const firstSheet = workbook.worksheets.getItemAt(0);
|
||||
const firstSheetName = firstSheet.name;
|
||||
|
||||
console.log(`\n########## Inspecting ${workbookPath} ##########`);
|
||||
console.log(`First worksheet: ${firstSheetName}`);
|
||||
|
||||
const summary = await workbook.inspect({
|
||||
kind: "workbook,sheet,table",
|
||||
maxChars: 6000,
|
||||
tableMaxRows: 6,
|
||||
tableMaxCols: 6,
|
||||
tableMaxCellChars: 80,
|
||||
});
|
||||
printInspect("Workbook summary", summary);
|
||||
|
||||
const sheetsIndex = await workbook.inspect({
|
||||
kind: "sheet",
|
||||
include: "id,name",
|
||||
});
|
||||
printInspect("Sheets index", sheetsIndex);
|
||||
|
||||
const firstRegion = await workbook.inspect({
|
||||
kind: "region",
|
||||
sheetId: firstSheetName,
|
||||
range: "A1:Z30",
|
||||
maxChars: 2500,
|
||||
tableMaxRows: 12,
|
||||
tableMaxCols: 8,
|
||||
tableMaxCellChars: 50,
|
||||
});
|
||||
printInspect(`First sheet region preview (${firstSheetName}!A1:Z30)`, firstRegion);
|
||||
|
||||
const formulas = await workbook.inspect({
|
||||
kind: "formula",
|
||||
sheetId: firstSheetName,
|
||||
maxChars: 2000,
|
||||
});
|
||||
printInspect(`Formula snapshot (${firstSheetName})`, formulas);
|
||||
|
||||
const drawings = await workbook.inspect({
|
||||
kind: "drawing",
|
||||
sheetId: firstSheetName,
|
||||
maxChars: 2000,
|
||||
});
|
||||
printInspect(`Drawing snapshot (${firstSheetName})`, drawings);
|
||||
}
|
||||
|
||||
async function inspectExistingWorkbooks(inputPaths: string[]): Promise<void> {
|
||||
for (const inputPath of inputPaths) {
|
||||
const workbookPath = await resolveWorkbookPath(inputPath);
|
||||
await inspectWorkbook(workbookPath);
|
||||
}
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const inputPaths =
|
||||
process.argv.slice(2).length > 0
|
||||
? process.argv.slice(2)
|
||||
: DEFAULT_WORKBOOK_INPUTS;
|
||||
await inspectExistingWorkbooks(inputPaths);
|
||||
}
|
||||
|
||||
main().catch((error: unknown) => {
|
||||
console.error(error);
|
||||
process.exit(1);
|
||||
});
|
||||
Generated
Vendored
+146
@@ -0,0 +1,146 @@
|
||||
import fs from "node:fs/promises";
|
||||
|
||||
import { SpreadsheetFile, Workbook } from "@oai/artifact-tool";
|
||||
|
||||
/**
|
||||
* Quick Start Examples
|
||||
* This runnable TypeScript example mirrors:
|
||||
* lib/agent/tools/artifact_tool_v2/skills/python/spreadsheets/examples/quick_start_example.py
|
||||
*/
|
||||
async function quickApiExample(): Promise<void> {
|
||||
// Creating a workbook and adding sheets with data and basic formatting
|
||||
const workbook = Workbook.create();
|
||||
var sheet = workbook.worksheets.add("ExampleSheet");
|
||||
|
||||
sheet = workbook.worksheets.getItem("ExampleSheet");
|
||||
sheet.getRange("A1:D4").values = [
|
||||
["Name", "Personality Type", "Age", "Birthday"],
|
||||
["John Doe", "Introvert", 30, new Date("1990-01-01T00:00:00Z")],
|
||||
["Jane Smith", "Extrovert", 25, new Date("1995-02-15T00:00:00Z")],
|
||||
["Jim Very Long Name", "Ambivert", 40, new Date("1980-03-20T00:00:00Z")],
|
||||
];
|
||||
sheet.getRange("E1").values = [["Score"]];
|
||||
sheet.getRange("E2").formulas = [["=C2*10"]]; // score is 10 * age
|
||||
sheet.getRange("E2:E4").fillDown();
|
||||
const headerRange = sheet.getRange("A1:E1");
|
||||
|
||||
// Styling
|
||||
const headerFormats = {
|
||||
fill: "#0F766E",
|
||||
font: { bold: true, color: "#FFFFFF" },
|
||||
horizontalAlignment: "center",
|
||||
verticalAlignment: "center",
|
||||
rowHeight: 16,
|
||||
};
|
||||
headerRange.format = headerFormats;
|
||||
headerRange.format.autofitColumns();
|
||||
|
||||
const dataRange = sheet.getRange("A2:D4");
|
||||
dataRange.format.wrapText = true;
|
||||
sheet.showGridLines = false;
|
||||
|
||||
// Format dates properly.
|
||||
sheet.getRange("D2:D4").format.numberFormat = "MM/DD/YYYY";
|
||||
|
||||
// Conditional formatting
|
||||
sheet.getRange("C2:C4").conditionalFormats.add("dataBar", {
|
||||
color: "#704023",
|
||||
gradient: true,
|
||||
});
|
||||
sheet.getRange("E2:E4").conditionalFormats.add("cellIs", {
|
||||
operator: "greaterThan",
|
||||
formula: 300,
|
||||
format: { font: { color: "#B91C1C" } },
|
||||
});
|
||||
sheet.conditionalFormattings.add({
|
||||
range: "B2:B4",
|
||||
rule: {
|
||||
type: "expression",
|
||||
formula: '=B2="Introvert"',
|
||||
format: { fill: "#FCA5A5" },
|
||||
},
|
||||
});
|
||||
|
||||
// Data validation: Since Personality Type is a dropdown category, add data validation.
|
||||
sheet.getRange("B2:B4").dataValidation = {
|
||||
rule: {
|
||||
type: "list",
|
||||
values: ["Introvert", "Extrovert", "Ambivert"],
|
||||
// formula1: "CategoriesSheet!$A$2:$A$4", // Alternative: reference a tunable list
|
||||
},
|
||||
};
|
||||
|
||||
// Tables: Turn it into a table (for example purposes! Make sure table names are unique)
|
||||
// NOTE: If hasHeaders=true, the range must include the header row.
|
||||
const table = sheet.tables.add("A1:E4", true, "PeopleTable");
|
||||
table.getHeaderRowRange();
|
||||
|
||||
// First column is still wide since we only auto-fit the first row. Expand it manually.
|
||||
sheet.getRange("A1:A4").format.columnWidth = 20;
|
||||
|
||||
// Create a compact chart helper range that references the source table.
|
||||
sheet.getRange("H1:I1").merge();
|
||||
sheet.getRange("H1").values = [["Charts"]];
|
||||
sheet.getRange("H1").format = headerFormats;
|
||||
sheet.getRange("H3:I3").values = [["Person", "Score"]];
|
||||
sheet.getRange("H4:I4").formulas = [["=A2", "=E2"]];
|
||||
sheet.getRange("H4:I6").fillDown();
|
||||
const chart = sheet.charts.add("bar", sheet.getRange("H3:I6"));
|
||||
chart.title = "Person by Scores";
|
||||
chart.hasLegend = true;
|
||||
chart.displayBlanksAs = "zero";
|
||||
chart.barOptions.direction = "column";
|
||||
chart.barOptions.grouping = "clustered";
|
||||
chart.setPosition("K2", "R16");
|
||||
|
||||
// Granular control over chart axes
|
||||
chart.xAxis = {
|
||||
axisType: "textAxis",
|
||||
title: { text: "Person", textStyle: { fontSize: 13, bold: true } },
|
||||
position: "bottom",
|
||||
orientation: "minMax",
|
||||
textStyle: { fontSize: 10 },
|
||||
};
|
||||
chart.yAxis = {
|
||||
axisType: "textAxis",
|
||||
title: { text: "Scores", textStyle: { fontSize: 13, bold: true } },
|
||||
numberFormatCode: "0,000",
|
||||
numberFormatSourceLinked: false,
|
||||
};
|
||||
|
||||
// Sparklines: add to the right of table
|
||||
const sparklinesHeader = sheet.getRange("F1");
|
||||
sparklinesHeader.values = [["Sparklines"]];
|
||||
sparklinesHeader.format = headerFormats;
|
||||
sparklinesHeader.format.autofitColumns();
|
||||
|
||||
sheet.sparklines.add({
|
||||
type: "column", // "line" | "column" | "stacked"
|
||||
sourceData: sheet.getRange("E2:E4"),
|
||||
targetRange: sheet.getRange("F2:F4"),
|
||||
seriesColor: "#AAAAAA",
|
||||
});
|
||||
|
||||
// Render
|
||||
await fs.mkdir("output", { recursive: true });
|
||||
const pngBlob = await workbook.render({
|
||||
sheetName: "ExampleSheet",
|
||||
autoCrop: "all",
|
||||
scale: 1,
|
||||
format: "png",
|
||||
});
|
||||
const pngBytes = new Uint8Array(await pngBlob.arrayBuffer());
|
||||
await fs.writeFile("output/example_sheet.png", pngBytes);
|
||||
console.log("Rendered first sheet to 'output/example_sheet.png'");
|
||||
|
||||
// Export
|
||||
const out = "output/example_sheet.xlsx";
|
||||
const xlsx = await SpreadsheetFile.exportXlsx(workbook);
|
||||
await xlsx.save(out);
|
||||
console.log(`Spreadsheet saved to ${out}`);
|
||||
}
|
||||
|
||||
quickApiExample().catch((error: unknown) => {
|
||||
console.error(error);
|
||||
process.exit(1);
|
||||
});
|
||||
Generated
Vendored
+32
@@ -0,0 +1,32 @@
|
||||
# Database Formulas
|
||||
|
||||
Database formulas aggregate rows from headered ranges using criteria ranges.
|
||||
|
||||
## Formula Pattern
|
||||
|
||||
```ts
|
||||
const formulaBlock = sheet.getRange(outputRange).write({
|
||||
formulas: formulaMatrix,
|
||||
});
|
||||
workbook.recalculate();
|
||||
const results = formulaBlock.values;
|
||||
```
|
||||
|
||||
## Common Shapes
|
||||
|
||||
```ts
|
||||
const formulas = [
|
||||
`=DSUM(${databaseRangeRef},${fieldRef},${criteriaRangeRef})`,
|
||||
`=DCOUNT(${databaseRangeRef},${fieldRef},${criteriaRangeRef})`,
|
||||
`=DCOUNTA(${databaseRangeRef},${fieldRef},${criteriaRangeRef})`,
|
||||
`=DAVERAGE(${databaseRangeRef},${fieldRef},${criteriaRangeRef})`,
|
||||
`=DMIN(${databaseRangeRef},${fieldRef},${criteriaRangeRef})`,
|
||||
`=DMAX(${databaseRangeRef},${fieldRef},${criteriaRangeRef})`,
|
||||
`=DSTDEV(${databaseRangeRef},${fieldRef},${criteriaRangeRef})`,
|
||||
`=DVAR(${databaseRangeRef},${fieldRef},${criteriaRangeRef})`,
|
||||
];
|
||||
```
|
||||
|
||||
## Coverage
|
||||
|
||||
Supported families include database sum, count, average, min, max, product, standard deviation, variance, and single-value lookup.
|
||||
Generated
Vendored
+34
@@ -0,0 +1,34 @@
|
||||
# Date And Time Formulas
|
||||
|
||||
Date and time formulas create, parse, extract, and compare serial dates and times.
|
||||
|
||||
## Formula Pattern
|
||||
|
||||
```ts
|
||||
const formulaBlock = sheet.getRange(outputRange).write({
|
||||
formulas: formulaMatrix,
|
||||
});
|
||||
workbook.recalculate();
|
||||
const results = formulaBlock.values;
|
||||
```
|
||||
|
||||
## Common Shapes
|
||||
|
||||
```ts
|
||||
const formulas = [
|
||||
`=DATE(${yearRef},${monthRef},${dayRef})`,
|
||||
`=TIME(${hourRef},${minuteRef},${secondRef})`,
|
||||
`=DATEVALUE(${textRef})`,
|
||||
`=TIMEVALUE(${textRef})`,
|
||||
`=YEAR(${dateRef})`,
|
||||
`=MONTH(${dateRef})`,
|
||||
`=DAY(${dateRef})`,
|
||||
`=WEEKDAY(${dateRef})`,
|
||||
`=WORKDAY(${startDateRef},${daysRef})`,
|
||||
`=NETWORKDAYS(${startDateRef},${endDateRef})`,
|
||||
];
|
||||
```
|
||||
|
||||
## Coverage
|
||||
|
||||
Supported families include date/time construction, extraction, workday and network-day calculations, year fractions, week numbers, today/current time, and end-of-month helpers.
|
||||
Generated
Vendored
+34
@@ -0,0 +1,34 @@
|
||||
# Engineering Formulas
|
||||
|
||||
Engineering formulas cover complex numbers, Bessel functions, bitwise operations, unit conversion, and number-base conversion.
|
||||
|
||||
## Formula Pattern
|
||||
|
||||
```ts
|
||||
const formulaBlock = sheet.getRange(outputRange).write({
|
||||
formulas: formulaMatrix,
|
||||
});
|
||||
workbook.recalculate();
|
||||
const results = formulaBlock.values;
|
||||
```
|
||||
|
||||
## Common Shapes
|
||||
|
||||
```ts
|
||||
const formulas = [
|
||||
`=COMPLEX(${realRef},${imaginaryRef})`,
|
||||
`=IMSUM(${complexRangeRef})`,
|
||||
`=IMPRODUCT(${complexRangeRef})`,
|
||||
`=IMABS(${complexRef})`,
|
||||
`=CONVERT(${valueRef},${fromUnitRef},${toUnitRef})`,
|
||||
`=BIN2DEC(${binaryRef})`,
|
||||
`=DEC2HEX(${decimalRef})`,
|
||||
`=BITAND(${valueRef1},${valueRef2})`,
|
||||
`=BITOR(${valueRef1},${valueRef2})`,
|
||||
`=BESSELJ(${valueRef},${orderRef})`,
|
||||
];
|
||||
```
|
||||
|
||||
## Coverage
|
||||
|
||||
Supported families include complex arithmetic, bitwise functions, base conversions, Bessel functions, error functions, delta/threshold helpers, and unit conversions.
|
||||
Generated
Vendored
+32
@@ -0,0 +1,32 @@
|
||||
# Financial Formulas
|
||||
|
||||
Financial formulas cover loans, rates, cash flows, depreciation, securities, treasury bills, and coupon calculations.
|
||||
|
||||
## Formula Pattern
|
||||
|
||||
```ts
|
||||
const formulaBlock = sheet.getRange(outputRange).write({
|
||||
formulas: formulaMatrix,
|
||||
});
|
||||
workbook.recalculate();
|
||||
const results = formulaBlock.values;
|
||||
```
|
||||
|
||||
## Common Shapes
|
||||
|
||||
```ts
|
||||
const formulas = [
|
||||
`=PMT(${rateRef},${periodsRef},${presentValueRef})`,
|
||||
`=PV(${rateRef},${periodsRef},${paymentRef})`,
|
||||
`=FV(${rateRef},${periodsRef},${paymentRef})`,
|
||||
`=NPV(${rateRef},${cashFlowRangeRef})`,
|
||||
`=IRR(${cashFlowRangeRef})`,
|
||||
`=XNPV(${rateRef},${cashFlowRangeRef},${dateRangeRef})`,
|
||||
`=XIRR(${cashFlowRangeRef},${dateRangeRef})`,
|
||||
`=RATE(${periodsRef},${paymentRef},${presentValueRef})`,
|
||||
];
|
||||
```
|
||||
|
||||
## Coverage
|
||||
|
||||
Supported families include payment and present/future value, net present value, return rate, depreciation, discount/yield, coupon date math, accrued interest, treasury bills, and compatibility variants.
|
||||
Generated
Vendored
+34
@@ -0,0 +1,34 @@
|
||||
# Information Formulas
|
||||
|
||||
Information formulas inspect value types, errors, blank cells, sheet indexes, and references.
|
||||
|
||||
## Formula Pattern
|
||||
|
||||
```ts
|
||||
const formulaBlock = sheet.getRange(outputRange).write({
|
||||
formulas: formulaMatrix,
|
||||
});
|
||||
workbook.recalculate();
|
||||
const results = formulaBlock.values;
|
||||
```
|
||||
|
||||
## Common Shapes
|
||||
|
||||
```ts
|
||||
const formulas = [
|
||||
`=ISBLANK(${valueRef})`,
|
||||
`=ISNUMBER(${valueRef})`,
|
||||
`=ISTEXT(${valueRef})`,
|
||||
`=ISLOGICAL(${valueRef})`,
|
||||
`=ISERROR(${valueRef})`,
|
||||
`=ISNA(${valueRef})`,
|
||||
`=TYPE(${valueRef})`,
|
||||
`=ERROR.TYPE(${valueRef})`,
|
||||
`=SHEET(${referenceRef})`,
|
||||
`=SHEETS(${referenceRef})`,
|
||||
];
|
||||
```
|
||||
|
||||
## Coverage
|
||||
|
||||
Supported families include type predicates, error predicates, blank checks, number/text/logical checks, N conversion, sheet lookup, and error type lookup.
|
||||
Generated
Vendored
+39
@@ -0,0 +1,39 @@
|
||||
# Logical Formulas
|
||||
|
||||
Logical formulas branch, combine conditions, and handle error values. Follow the main skill’s formula policy and the [XLSX compatibility guidance](../API_QUICK_START.md#known-formulaexport-limitations-not-exhaustive).
|
||||
|
||||
## Formula Pattern
|
||||
|
||||
```ts
|
||||
const formulaBlock = sheet.getRange(outputRange).write({
|
||||
formulas: formulaMatrix,
|
||||
});
|
||||
workbook.recalculate();
|
||||
const results = formulaBlock.values;
|
||||
```
|
||||
|
||||
## Boolean And Branching Shapes
|
||||
|
||||
```ts
|
||||
const formulas = [
|
||||
`=TRUE()`,
|
||||
`=FALSE()`,
|
||||
`=NA()`,
|
||||
`=AND(${conditionRef1},${conditionRef2})`,
|
||||
`=OR(${conditionRef1},${conditionRef2})`,
|
||||
`=NOT(${conditionRef})`,
|
||||
`=XOR(${conditionRef1},${conditionRef2})`,
|
||||
`=IF(${conditionRef},${trueValueRef},${falseValueRef})`,
|
||||
`=_xlfn.IFS(${conditionRef1},${valueRef1},${conditionRef2},${valueRef2})`,
|
||||
`=SWITCH(${valueRef},${caseRef1},${resultRef1},${defaultRef})`,
|
||||
];
|
||||
```
|
||||
|
||||
## Error Handling Shapes
|
||||
|
||||
```ts
|
||||
const formulas = [
|
||||
`=IFERROR(${valueRef},${replacementRef})`,
|
||||
`=IFNA(${valueRef},${replacementRef})`,
|
||||
];
|
||||
```
|
||||
Generated
Vendored
+24
@@ -0,0 +1,24 @@
|
||||
# Lookup And Reference Formulas
|
||||
|
||||
Lookup and reference formulas locate values and return addresses or dimensions. Follow the main skill’s scalar-formula policy and the [XLSX compatibility guidance](../API_QUICK_START.md#known-formulaexport-limitations-not-exhaustive).
|
||||
|
||||
## Formula Pattern
|
||||
|
||||
```ts
|
||||
const formulaBlock = sheet.getRange(outputRange).write({
|
||||
formulas: formulaMatrix,
|
||||
});
|
||||
workbook.recalculate();
|
||||
const results = formulaBlock.values;
|
||||
```
|
||||
|
||||
## Common Shapes
|
||||
|
||||
```ts
|
||||
const formulas = [
|
||||
`=_xlfn.XLOOKUP(${lookupRef},${lookupRangeRef},${returnRangeRef})`,
|
||||
`=VLOOKUP(${lookupRef},${tableRangeRef},${columnIndexRef},${exactRef})`,
|
||||
`=INDEX(${rangeRef},${rowIndexRef},${columnIndexRef})`,
|
||||
`=MATCH(${lookupRef},${lookupRangeRef},${matchModeRef})`,
|
||||
];
|
||||
```
|
||||
Generated
Vendored
+33
@@ -0,0 +1,33 @@
|
||||
# Math And Trig Formulas
|
||||
|
||||
Math and trigonometry formulas cover arithmetic, rounding, aggregation, matrix math, random values, base conversion, and trig functions.
|
||||
|
||||
## Formula Pattern
|
||||
|
||||
```ts
|
||||
const formulaBlock = sheet.getRange(outputRange).write({
|
||||
formulas: formulaMatrix,
|
||||
});
|
||||
workbook.recalculate();
|
||||
const results = formulaBlock.values;
|
||||
```
|
||||
|
||||
## Common Shapes
|
||||
|
||||
```ts
|
||||
const formulas = [
|
||||
`=SUM(${rangeRef})`,
|
||||
`=PRODUCT(${rangeRef})`,
|
||||
`=ROUND(${valueRef},${digits})`,
|
||||
`=POWER(${valueRef},${power})`,
|
||||
`=MOD(${valueRef},${divisor})`,
|
||||
`=SIN(${angleRef})`,
|
||||
`=COS(${angleRef})`,
|
||||
`=TAN(${angleRef})`,
|
||||
`=MMULT(${matrixARef},${matrixBRef})`,
|
||||
];
|
||||
```
|
||||
|
||||
## Coverage
|
||||
|
||||
Supported families include aggregate math, rounding, logarithms, powers, matrix functions, random generators, trig, hyperbolic trig, Roman/base conversion, subtotaling, and compatibility variants.
|
||||
Generated
Vendored
+32
@@ -0,0 +1,32 @@
|
||||
# Statistical Formulas
|
||||
|
||||
Statistical formulas summarize, rank, distribute, correlate, and forecast values.
|
||||
|
||||
## Formula Pattern
|
||||
|
||||
```ts
|
||||
const formulaBlock = sheet.getRange(outputRange).write({
|
||||
formulas: formulaMatrix,
|
||||
});
|
||||
workbook.recalculate();
|
||||
const results = formulaBlock.values;
|
||||
```
|
||||
|
||||
## Common Shapes
|
||||
|
||||
```ts
|
||||
const formulas = [
|
||||
`=AVERAGE(${rangeRef})`,
|
||||
`=MEDIAN(${rangeRef})`,
|
||||
`=STDEV.S(${rangeRef})`,
|
||||
`=VAR.P(${rangeRef})`,
|
||||
`=QUARTILE(${rangeRef},${quartileIndex})`,
|
||||
`=CORREL(${xRangeRef},${yRangeRef})`,
|
||||
`=FORECAST.LINEAR(${xRef},${knownYRangeRef},${knownXRangeRef})`,
|
||||
`=FORECAST.ETS(${targetDateRef},${valuesRangeRef},${timelineRangeRef})`,
|
||||
];
|
||||
```
|
||||
|
||||
## Coverage
|
||||
|
||||
Supported families include averages, counts, rank and percentile functions, variance and standard deviation, distributions, regression, covariance/correlation, forecasting, and compatibility names.
|
||||
Generated
Vendored
+33
@@ -0,0 +1,33 @@
|
||||
# Text Formulas
|
||||
|
||||
Text formulas transform, search, split, join, format, and extract strings.
|
||||
|
||||
## Formula Pattern
|
||||
|
||||
```ts
|
||||
const formulaBlock = sheet.getRange(outputRange).write({
|
||||
formulas: formulaMatrix,
|
||||
});
|
||||
workbook.recalculate();
|
||||
const results = formulaBlock.values;
|
||||
```
|
||||
|
||||
## Common Shapes
|
||||
|
||||
```ts
|
||||
const formulas = [
|
||||
`=TEXT(${valueRef},${formatRef})`,
|
||||
`=CONCAT(${rangeRef})`,
|
||||
`=_xlfn.TEXTJOIN(${delimiterRef},${ignoreEmptyRef},${rangeRef})`,
|
||||
`=LEFT(${textRef},${countRef})`,
|
||||
`=RIGHT(${textRef},${countRef})`,
|
||||
`=MID(${textRef},${startRef},${countRef})`,
|
||||
`=FIND(${needleRef},${textRef})`,
|
||||
`=SEARCH(${needleRef},${textRef})`,
|
||||
`=SUBSTITUTE(${textRef},${oldTextRef},${newTextRef})`,
|
||||
];
|
||||
```
|
||||
|
||||
## Coverage
|
||||
|
||||
Supported families include length, casing, replacement, extraction, joining, splitting, number-to-text formatting, Unicode helpers, and regex helpers.
|
||||
Generated
Vendored
+62
@@ -0,0 +1,62 @@
|
||||
# Comments
|
||||
|
||||
Workbook comments use people, threads, replies, reactions, and thread state.
|
||||
|
||||
## Current Author
|
||||
|
||||
```ts
|
||||
workbook.comments.setSelf({
|
||||
displayName,
|
||||
initials,
|
||||
email,
|
||||
});
|
||||
```
|
||||
|
||||
## Person Inline Type
|
||||
|
||||
```ts
|
||||
type PersonConfig = {
|
||||
id?: string;
|
||||
displayName: string;
|
||||
initials?: string;
|
||||
email?: string;
|
||||
avatarUrl?: string;
|
||||
};
|
||||
```
|
||||
|
||||
## Cell And Range Threads
|
||||
|
||||
```ts
|
||||
const cellThread = workbook.comments.addThread(
|
||||
{ cell: sheet.getRange(cellAddress) },
|
||||
bodyText,
|
||||
);
|
||||
|
||||
const rangeThread = workbook.comments.addThread(
|
||||
{ range: sheet.getRange(rangeAddress) },
|
||||
bodyText,
|
||||
);
|
||||
```
|
||||
|
||||
## Thread Inline Types
|
||||
|
||||
```ts
|
||||
type WorkbookCommentTarget =
|
||||
| { cell: Range }
|
||||
| { range: Range };
|
||||
|
||||
type ThreadAddOptions = {
|
||||
author?: Person | PersonConfig | { id: string };
|
||||
createdAt?: string;
|
||||
position?: { x: number; y: number; unit?: "px" | "emu" };
|
||||
};
|
||||
```
|
||||
|
||||
## Replies And State
|
||||
|
||||
```ts
|
||||
const reply = cellThread.addReply(replyText);
|
||||
reply.toggleReaction(reactionText);
|
||||
cellThread.resolve();
|
||||
cellThread.reopen();
|
||||
```
|
||||
Generated
Vendored
+81
@@ -0,0 +1,81 @@
|
||||
# Conditional Formatting
|
||||
|
||||
Use `range.conditionalFormats` to add formatting rules to ranges.
|
||||
|
||||
## Rule Pattern
|
||||
|
||||
```ts
|
||||
range.conditionalFormats.add(ruleType, {
|
||||
operator,
|
||||
formula,
|
||||
format,
|
||||
});
|
||||
```
|
||||
|
||||
Choose `ruleType`, `operator`, color, and style strings from the inline types below.
|
||||
|
||||
## Rule Inline Types
|
||||
|
||||
```ts
|
||||
type ConditionalFormatRuleType =
|
||||
| "cellIs" | "CellValue" | "Custom" | "expression"
|
||||
| "colorScale" | "dataBar" | "iconSet"
|
||||
| "containsText" | "notContainsText" | "beginsWith" | "endsWith"
|
||||
| "containsBlanks" | "notContainsBlanks" | "containsErrors" | "notContainsErrors"
|
||||
| "duplicateValues" | "uniqueValues" | "timePeriod" | "top10" | "aboveAverage";
|
||||
|
||||
type CellIsOperator =
|
||||
| "greaterThan"
|
||||
| "greaterThanOrEqual"
|
||||
| "lessThan"
|
||||
| "lessThanOrEqual"
|
||||
| "equal"
|
||||
| "notEqual"
|
||||
| "between"
|
||||
| "notBetween";
|
||||
|
||||
type ConditionalFormatConfig =
|
||||
| { operator: CellIsOperator; formula: string | number | Array<string | number>; format?: DifferentialFormatConfig }
|
||||
| { formula: string | number; format?: DifferentialFormatConfig }
|
||||
| { colors?: ColorConfig[]; thresholds?: CfvoInput[] }
|
||||
| { color?: ColorConfig; thresholds?: CfvoInput[]; gradient?: boolean }
|
||||
| { iconSet: string; showValue?: boolean; reverse?: boolean; thresholds?: CfvoInput[] }
|
||||
| { text: string; format?: DifferentialFormatConfig }
|
||||
| { timePeriod: "yesterday" | "today" | "tomorrow" | "last7Days" | "lastWeek" | "thisWeek" | "nextWeek" | "lastMonth" | "thisMonth" | "nextMonth"; format?: DifferentialFormatConfig }
|
||||
| { rank?: number; percent?: boolean; bottom?: boolean; format?: DifferentialFormatConfig }
|
||||
| { aboveAverage?: boolean; equalAverage?: boolean; stdDev?: number; format?: DifferentialFormatConfig };
|
||||
|
||||
type DifferentialFormatConfig = {
|
||||
fill?: FillConfig;
|
||||
font?: { bold?: boolean; italic?: boolean; color?: ColorConfig };
|
||||
border?: RangeBordersConfig;
|
||||
numberFormat?: string;
|
||||
};
|
||||
|
||||
type CfvoInput =
|
||||
| "min"
|
||||
| "max"
|
||||
| number
|
||||
| `${number}%`
|
||||
| { type: "min" | "max" | "num" | "percent" | "percentile"; value?: string | number };
|
||||
```
|
||||
|
||||
## Custom Rule
|
||||
|
||||
```ts
|
||||
range.conditionalFormats.addCustom(expression, {
|
||||
fill,
|
||||
font,
|
||||
border,
|
||||
});
|
||||
```
|
||||
|
||||
## Rule Families
|
||||
|
||||
Supported rule families include cell value, custom expression, text, blank/error, duplicate/unique, time period, top/bottom, above/below average, color scale, data bar, and icon set.
|
||||
|
||||
## Clear Rules
|
||||
|
||||
```ts
|
||||
range.conditionalFormats.deleteAll();
|
||||
```
|
||||
Generated
Vendored
+31
@@ -0,0 +1,31 @@
|
||||
## Data tables (`worksheet.dataTables`)
|
||||
|
||||
Use data tables to project a formula across a row/column grid.
|
||||
|
||||
### Two-variable data table
|
||||
|
||||
```ts
|
||||
const sheet = workbook.worksheets.add("TwoVariable");
|
||||
|
||||
sheet.getRange("B3").values = [[0.095]]; // rate
|
||||
sheet.getRange("B4").values = [[360]]; // periods
|
||||
sheet.getRange("B5").values = [[80000]]; // principal
|
||||
|
||||
sheet.getRange("C2").formulas = [[`=PMT(B3/12,B4,-B5)`]];
|
||||
sheet.getRange("C3:C5").values = [[0.09], [0.0925], [0.095]];
|
||||
sheet.getRange("D2:E2").values = [[180, 360]];
|
||||
|
||||
sheet.dataTables.add("D3:E5", {
|
||||
rowInput: "B4",
|
||||
columnInput: "B3",
|
||||
});
|
||||
|
||||
workbook.recalculate();
|
||||
```
|
||||
|
||||
### Single-variable (row input only)
|
||||
|
||||
```ts
|
||||
sheet.dataTables.add("D3:E3", { rowInput: "B4" });
|
||||
workbook.recalculate();
|
||||
```
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user