rolled all files up

This commit is contained in:
2024-09-20 14:01:18 +02:00
parent 087117eb06
commit 6ae7168e87
4655 changed files with 502691 additions and 163478 deletions

1
live2d/node_modules/.bin/gh-pages generated vendored Symbolic link
View File

@@ -0,0 +1 @@
../gh-pages/bin/gh-pages.js

1
live2d/node_modules/.bin/gh-pages-clean generated vendored Symbolic link
View File

@@ -0,0 +1 @@
../gh-pages/bin/gh-pages-clean.js

1
live2d/node_modules/.bin/rollup generated vendored Symbolic link
View File

@@ -0,0 +1 @@
../rollup/dist/bin/rollup

1
live2d/node_modules/.bin/semver generated vendored Symbolic link
View File

@@ -0,0 +1 @@
../semver/bin/semver.js

View File

@@ -1 +0,0 @@
../webpack-cli/bin/cli.js

2147
live2d/node_modules/.package-lock.json generated vendored

File diff suppressed because it is too large Load Diff

View File

@@ -1,21 +0,0 @@
MIT License
Copyright (c) 2020 Roman Dvornov <rdvornov@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.

View File

@@ -1,256 +0,0 @@
# json-ext
[![NPM version](https://img.shields.io/npm/v/@discoveryjs/json-ext.svg)](https://www.npmjs.com/package/@discoveryjs/json-ext)
[![Build Status](https://github.com/discoveryjs/json-ext/actions/workflows/ci.yml/badge.svg)](https://github.com/discoveryjs/json-ext/actions/workflows/ci.yml)
[![Coverage Status](https://coveralls.io/repos/github/discoveryjs/json-ext/badge.svg?branch=master)](https://coveralls.io/github/discoveryjs/json-ext?)
[![NPM Downloads](https://img.shields.io/npm/dm/@discoveryjs/json-ext.svg)](https://www.npmjs.com/package/@discoveryjs/json-ext)
A set of utilities that extend the use of JSON. Designed to be fast and memory efficient
Features:
- [x] `parseChunked()` Parse JSON that comes by chunks (e.g. FS readable stream or fetch response stream)
- [x] `stringifyStream()` Stringify stream (Node.js)
- [x] `stringifyInfo()` Get estimated size and other facts of JSON.stringify() without converting a value to string
- [ ] **TBD** Support for circular references
- [ ] **TBD** Binary representation [branch](https://github.com/discoveryjs/json-ext/tree/binary)
- [ ] **TBD** WHATWG [Streams](https://streams.spec.whatwg.org/) support
## Install
```bash
npm install @discoveryjs/json-ext
```
## API
- [parseChunked(chunkEmitter)](#parsechunkedchunkemitter)
- [stringifyStream(value[, replacer[, space]])](#stringifystreamvalue-replacer-space)
- [stringifyInfo(value[, replacer[, space[, options]]])](#stringifyinfovalue-replacer-space-options)
- [Options](#options)
- [async](#async)
- [continueOnCircular](#continueoncircular)
- [version](#version)
### parseChunked(chunkEmitter)
Works the same as [`JSON.parse()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse) but takes `chunkEmitter` instead of string and returns [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
> NOTE: `reviver` parameter is not supported yet, but will be added in next releases.
> NOTE: WHATWG streams aren't supported yet
When to use:
- It's required to avoid freezing the main thread during big JSON parsing, since this process can be distributed in time
- Huge JSON needs to be parsed (e.g. >500MB on Node.js)
- Needed to reduce memory pressure. `JSON.parse()` needs to receive the entire JSON before parsing it. With `parseChunked()` you may parse JSON as first bytes of it comes. This approach helps to avoid storing a huge string in the memory at a single time point and following GC.
[Benchmark](https://github.com/discoveryjs/json-ext/tree/master/benchmarks#parse-chunked)
Usage:
```js
const { parseChunked } = require('@discoveryjs/json-ext');
// as a regular Promise
parseChunked(chunkEmitter)
.then(data => {
/* data is parsed JSON */
});
// using await (keep in mind that not every runtime has a support for top level await)
const data = await parseChunked(chunkEmitter);
```
Parameter `chunkEmitter` can be:
- [`ReadableStream`](https://nodejs.org/dist/latest-v14.x/docs/api/stream.html#stream_readable_streams) (Node.js only)
```js
const fs = require('fs');
const { parseChunked } = require('@discoveryjs/json-ext');
parseChunked(fs.createReadStream('path/to/file.json'))
```
- Generator, async generator or function that returns iterable (chunks). Chunk might be a `string`, `Uint8Array` or `Buffer` (Node.js only):
```js
const { parseChunked } = require('@discoveryjs/json-ext');
const encoder = new TextEncoder();
// generator
parseChunked(function*() {
yield '{ "hello":';
yield Buffer.from(' "wor'); // Node.js only
yield encoder.encode('ld" }'); // returns Uint8Array(5) [ 108, 100, 34, 32, 125 ]
});
// async generator
parseChunked(async function*() {
for await (const chunk of someAsyncSource) {
yield chunk;
}
});
// function that returns iterable
parseChunked(() => ['{ "hello":', ' "world"}'])
```
Using with [fetch()](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API):
```js
async function loadData(url) {
const response = await fetch(url);
const reader = response.body.getReader();
return parseChunked(async function*() {
while (true) {
const { done, value } = await reader.read();
if (done) {
break;
}
yield value;
}
});
}
loadData('https://example.com/data.json')
.then(data => {
/* data is parsed JSON */
})
```
### stringifyStream(value[, replacer[, space]])
Works the same as [`JSON.stringify()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify), but returns an instance of [`ReadableStream`](https://nodejs.org/dist/latest-v14.x/docs/api/stream.html#stream_readable_streams) instead of string.
> NOTE: WHATWG Streams aren't supported yet, so function available for Node.js only for now
Departs from JSON.stringify():
- Outputs `null` when `JSON.stringify()` returns `undefined` (since streams may not emit `undefined`)
- A promise is resolving and the resulting value is stringifying as a regular one
- A stream in non-object mode is piping to output as is
- A stream in object mode is piping to output as an array of objects
When to use:
- Huge JSON needs to be generated (e.g. >500MB on Node.js)
- Needed to reduce memory pressure. `JSON.stringify()` needs to generate the entire JSON before send or write it to somewhere. With `stringifyStream()` you may send a result to somewhere as first bytes of the result appears. This approach helps to avoid storing a huge string in the memory at a single time point.
- The object being serialized contains Promises or Streams (see Usage for examples)
[Benchmark](https://github.com/discoveryjs/json-ext/tree/master/benchmarks#stream-stringifying)
Usage:
```js
const { stringifyStream } = require('@discoveryjs/json-ext');
// handle events
stringifyStream(data)
.on('data', chunk => console.log(chunk))
.on('error', error => consold.error(error))
.on('finish', () => console.log('DONE!'));
// pipe into a stream
stringifyStream(data)
.pipe(writableStream);
```
Using Promise or ReadableStream in serializing object:
```js
const fs = require('fs');
const { stringifyStream } = require('@discoveryjs/json-ext');
// output will be
// {"name":"example","willSerializeResolvedValue":42,"fromFile":[1, 2, 3],"at":{"any":{"level":"promise!"}}}
stringifyStream({
name: 'example',
willSerializeResolvedValue: Promise.resolve(42),
fromFile: fs.createReadStream('path/to/file.json'), // support file content is "[1, 2, 3]", it'll be inserted as it
at: {
any: {
level: new Promise(resolve => setTimeout(() => resolve('promise!'), 100))
}
}
})
// in case several async requests are used in object, it's prefered
// to put fastest requests first, because in this case
stringifyStream({
foo: fetch('http://example.com/request_takes_2s').then(req => req.json()),
bar: fetch('http://example.com/request_takes_5s').then(req => req.json())
});
```
Using with [`WritableStream`](https://nodejs.org/dist/latest-v14.x/docs/api/stream.html#stream_writable_streams) (Node.js only):
```js
const fs = require('fs');
const { stringifyStream } = require('@discoveryjs/json-ext');
// pipe into a console
stringifyStream(data)
.pipe(process.stdout);
// pipe into a file
stringifyStream(data)
.pipe(fs.createWriteStream('path/to/file.json'));
// wrapping into a Promise
new Promise((resolve, reject) => {
stringifyStream(data)
.on('error', reject)
.pipe(stream)
.on('error', reject)
.on('finish', resolve);
});
```
### stringifyInfo(value[, replacer[, space[, options]]])
`value`, `replacer` and `space` arguments are the same as for `JSON.stringify()`.
Result is an object:
```js
{
minLength: Number, // minimal bytes when values is stringified
circular: [...], // list of circular references
duplicate: [...], // list of objects that occur more than once
async: [...] // list of async values, i.e. promises and streams
}
```
Example:
```js
const { stringifyInfo } = require('@discoveryjs/json-ext');
console.log(
stringifyInfo({ test: true }).minLength
);
// > 13
// that equals '{"test":true}'.length
```
#### Options
##### async
Type: `Boolean`
Default: `false`
Collect async values (promises and streams) or not.
##### continueOnCircular
Type: `Boolean`
Default: `false`
Stop collecting info for a value or not whenever circular reference is found. Setting option to `true` allows to find all circular references.
### version
The version of library, e.g. `"0.3.1"`.
## License
MIT

View File

@@ -1,791 +0,0 @@
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.jsonExt = factory());
})(this, (function () { 'use strict';
var version = "0.5.7";
const PrimitiveType = 1;
const ObjectType = 2;
const ArrayType = 3;
const PromiseType = 4;
const ReadableStringType = 5;
const ReadableObjectType = 6;
// https://tc39.es/ecma262/#table-json-single-character-escapes
const escapableCharCodeSubstitution$1 = { // JSON Single Character Escape Sequences
0x08: '\\b',
0x09: '\\t',
0x0a: '\\n',
0x0c: '\\f',
0x0d: '\\r',
0x22: '\\\"',
0x5c: '\\\\'
};
function isLeadingSurrogate$1(code) {
return code >= 0xD800 && code <= 0xDBFF;
}
function isTrailingSurrogate$1(code) {
return code >= 0xDC00 && code <= 0xDFFF;
}
function isReadableStream$1(value) {
return (
typeof value.pipe === 'function' &&
typeof value._read === 'function' &&
typeof value._readableState === 'object' && value._readableState !== null
);
}
function replaceValue$1(holder, key, value, replacer) {
if (value && typeof value.toJSON === 'function') {
value = value.toJSON();
}
if (replacer !== null) {
value = replacer.call(holder, String(key), value);
}
switch (typeof value) {
case 'function':
case 'symbol':
value = undefined;
break;
case 'object':
if (value !== null) {
const cls = value.constructor;
if (cls === String || cls === Number || cls === Boolean) {
value = value.valueOf();
}
}
break;
}
return value;
}
function getTypeNative$1(value) {
if (value === null || typeof value !== 'object') {
return PrimitiveType;
}
if (Array.isArray(value)) {
return ArrayType;
}
return ObjectType;
}
function getTypeAsync$1(value) {
if (value === null || typeof value !== 'object') {
return PrimitiveType;
}
if (typeof value.then === 'function') {
return PromiseType;
}
if (isReadableStream$1(value)) {
return value._readableState.objectMode ? ReadableObjectType : ReadableStringType;
}
if (Array.isArray(value)) {
return ArrayType;
}
return ObjectType;
}
function normalizeReplacer$1(replacer) {
if (typeof replacer === 'function') {
return replacer;
}
if (Array.isArray(replacer)) {
const allowlist = new Set(replacer
.map(item => {
const cls = item && item.constructor;
return cls === String || cls === Number ? String(item) : null;
})
.filter(item => typeof item === 'string')
);
return [...allowlist];
}
return null;
}
function normalizeSpace$1(space) {
if (typeof space === 'number') {
if (!Number.isFinite(space) || space < 1) {
return false;
}
return ' '.repeat(Math.min(space, 10));
}
if (typeof space === 'string') {
return space.slice(0, 10) || false;
}
return false;
}
var utils = {
escapableCharCodeSubstitution: escapableCharCodeSubstitution$1,
isLeadingSurrogate: isLeadingSurrogate$1,
isTrailingSurrogate: isTrailingSurrogate$1,
type: {
PRIMITIVE: PrimitiveType,
PROMISE: PromiseType,
ARRAY: ArrayType,
OBJECT: ObjectType,
STRING_STREAM: ReadableStringType,
OBJECT_STREAM: ReadableObjectType
},
isReadableStream: isReadableStream$1,
replaceValue: replaceValue$1,
getTypeNative: getTypeNative$1,
getTypeAsync: getTypeAsync$1,
normalizeReplacer: normalizeReplacer$1,
normalizeSpace: normalizeSpace$1
};
const {
normalizeReplacer,
normalizeSpace,
replaceValue,
getTypeNative,
getTypeAsync,
isLeadingSurrogate,
isTrailingSurrogate,
escapableCharCodeSubstitution,
type: {
PRIMITIVE,
OBJECT,
ARRAY,
PROMISE,
STRING_STREAM,
OBJECT_STREAM
}
} = utils;
const charLength2048 = Array.from({ length: 2048 }).map((_, code) => {
if (escapableCharCodeSubstitution.hasOwnProperty(code)) {
return 2; // \X
}
if (code < 0x20) {
return 6; // \uXXXX
}
return code < 128 ? 1 : 2; // UTF8 bytes
});
function stringLength(str) {
let len = 0;
let prevLeadingSurrogate = false;
for (let i = 0; i < str.length; i++) {
const code = str.charCodeAt(i);
if (code < 2048) {
len += charLength2048[code];
} else if (isLeadingSurrogate(code)) {
len += 6; // \uXXXX since no pair with trailing surrogate yet
prevLeadingSurrogate = true;
continue;
} else if (isTrailingSurrogate(code)) {
len = prevLeadingSurrogate
? len - 2 // surrogate pair (4 bytes), since we calculate prev leading surrogate as 6 bytes, substruct 2 bytes
: len + 6; // \uXXXX
} else {
len += 3; // code >= 2048 is 3 bytes length for UTF8
}
prevLeadingSurrogate = false;
}
return len + 2; // +2 for quotes
}
function primitiveLength(value) {
switch (typeof value) {
case 'string':
return stringLength(value);
case 'number':
return Number.isFinite(value) ? String(value).length : 4 /* null */;
case 'boolean':
return value ? 4 /* true */ : 5 /* false */;
case 'undefined':
case 'object':
return 4; /* null */
default:
return 0;
}
}
function spaceLength(space) {
space = normalizeSpace(space);
return typeof space === 'string' ? space.length : 0;
}
var stringifyInfo = function jsonStringifyInfo(value, replacer, space, options) {
function walk(holder, key, value) {
if (stop) {
return;
}
value = replaceValue(holder, key, value, replacer);
let type = getType(value);
// check for circular structure
if (type !== PRIMITIVE && stack.has(value)) {
circular.add(value);
length += 4; // treat as null
if (!options.continueOnCircular) {
stop = true;
}
return;
}
switch (type) {
case PRIMITIVE:
if (value !== undefined || Array.isArray(holder)) {
length += primitiveLength(value);
} else if (holder === root) {
length += 9; // FIXME: that's the length of undefined, should we normalize behaviour to convert it to null?
}
break;
case OBJECT: {
if (visited.has(value)) {
duplicate.add(value);
length += visited.get(value);
break;
}
const valueLength = length;
let entries = 0;
length += 2; // {}
stack.add(value);
for (const key in value) {
if (hasOwnProperty.call(value, key) && (allowlist === null || allowlist.has(key))) {
const prevLength = length;
walk(value, key, value[key]);
if (prevLength !== length) {
// value is printed
length += stringLength(key) + 1; // "key":
entries++;
}
}
}
if (entries > 1) {
length += entries - 1; // commas
}
stack.delete(value);
if (space > 0 && entries > 0) {
length += (1 + (stack.size + 1) * space + 1) * entries; // for each key-value: \n{space}
length += 1 + stack.size * space; // for }
}
visited.set(value, length - valueLength);
break;
}
case ARRAY: {
if (visited.has(value)) {
duplicate.add(value);
length += visited.get(value);
break;
}
const valueLength = length;
length += 2; // []
stack.add(value);
for (let i = 0; i < value.length; i++) {
walk(value, i, value[i]);
}
if (value.length > 1) {
length += value.length - 1; // commas
}
stack.delete(value);
if (space > 0 && value.length > 0) {
length += (1 + (stack.size + 1) * space) * value.length; // for each element: \n{space}
length += 1 + stack.size * space; // for ]
}
visited.set(value, length - valueLength);
break;
}
case PROMISE:
case STRING_STREAM:
async.add(value);
break;
case OBJECT_STREAM:
length += 2; // []
async.add(value);
break;
}
}
let allowlist = null;
replacer = normalizeReplacer(replacer);
if (Array.isArray(replacer)) {
allowlist = new Set(replacer);
replacer = null;
}
space = spaceLength(space);
options = options || {};
const visited = new Map();
const stack = new Set();
const duplicate = new Set();
const circular = new Set();
const async = new Set();
const getType = options.async ? getTypeAsync : getTypeNative;
const root = { '': value };
let stop = false;
let length = 0;
walk(root, '', value);
return {
minLength: isNaN(length) ? Infinity : length,
circular: [...circular],
duplicate: [...duplicate],
async: [...async]
};
};
var stringifyStreamBrowser = () => {
throw new Error('Method is not supported');
};
var textDecoderBrowser = TextDecoder;
const { isReadableStream } = utils;
const STACK_OBJECT = 1;
const STACK_ARRAY = 2;
const decoder = new textDecoderBrowser();
function isObject(value) {
return value !== null && typeof value === 'object';
}
function adjustPosition(error, parser) {
if (error.name === 'SyntaxError' && parser.jsonParseOffset) {
error.message = error.message.replace(/at position (\d+)/, (_, pos) =>
'at position ' + (Number(pos) + parser.jsonParseOffset)
);
}
return error;
}
function append(array, elements) {
// Note: Avoid to use array.push(...elements) since it may lead to
// "RangeError: Maximum call stack size exceeded" for a long arrays
const initialLength = array.length;
array.length += elements.length;
for (let i = 0; i < elements.length; i++) {
array[initialLength + i] = elements[i];
}
}
var parseChunked = function(chunkEmitter) {
let parser = new ChunkParser();
if (isObject(chunkEmitter) && isReadableStream(chunkEmitter)) {
return new Promise((resolve, reject) => {
chunkEmitter
.on('data', chunk => {
try {
parser.push(chunk);
} catch (e) {
reject(adjustPosition(e, parser));
parser = null;
}
})
.on('error', (e) => {
parser = null;
reject(e);
})
.on('end', () => {
try {
resolve(parser.finish());
} catch (e) {
reject(adjustPosition(e, parser));
} finally {
parser = null;
}
});
});
}
if (typeof chunkEmitter === 'function') {
const iterator = chunkEmitter();
if (isObject(iterator) && (Symbol.iterator in iterator || Symbol.asyncIterator in iterator)) {
return new Promise(async (resolve, reject) => {
try {
for await (const chunk of iterator) {
parser.push(chunk);
}
resolve(parser.finish());
} catch (e) {
reject(adjustPosition(e, parser));
} finally {
parser = null;
}
});
}
}
throw new Error(
'Chunk emitter should be readable stream, generator, ' +
'async generator or function returning an iterable object'
);
};
class ChunkParser {
constructor() {
this.value = undefined;
this.valueStack = null;
this.stack = new Array(100);
this.lastFlushDepth = 0;
this.flushDepth = 0;
this.stateString = false;
this.stateStringEscape = false;
this.pendingByteSeq = null;
this.pendingChunk = null;
this.chunkOffset = 0;
this.jsonParseOffset = 0;
}
parseAndAppend(fragment, wrap) {
// Append new entries or elements
if (this.stack[this.lastFlushDepth - 1] === STACK_OBJECT) {
if (wrap) {
this.jsonParseOffset--;
fragment = '{' + fragment + '}';
}
Object.assign(this.valueStack.value, JSON.parse(fragment));
} else {
if (wrap) {
this.jsonParseOffset--;
fragment = '[' + fragment + ']';
}
append(this.valueStack.value, JSON.parse(fragment));
}
}
prepareAddition(fragment) {
const { value } = this.valueStack;
const expectComma = Array.isArray(value)
? value.length !== 0
: Object.keys(value).length !== 0;
if (expectComma) {
// Skip a comma at the beginning of fragment, otherwise it would
// fail to parse
if (fragment[0] === ',') {
this.jsonParseOffset++;
return fragment.slice(1);
}
// When value (an object or array) is not empty and a fragment
// doesn't start with a comma, a single valid fragment starting
// is a closing bracket. If it's not, a prefix is adding to fail
// parsing. Otherwise, the sequence of chunks can be successfully
// parsed, although it should not, e.g. ["[{}", "{}]"]
if (fragment[0] !== '}' && fragment[0] !== ']') {
this.jsonParseOffset -= 3;
return '[[]' + fragment;
}
}
return fragment;
}
flush(chunk, start, end) {
let fragment = chunk.slice(start, end);
// Save position correction an error in JSON.parse() if any
this.jsonParseOffset = this.chunkOffset + start;
// Prepend pending chunk if any
if (this.pendingChunk !== null) {
fragment = this.pendingChunk + fragment;
this.jsonParseOffset -= this.pendingChunk.length;
this.pendingChunk = null;
}
if (this.flushDepth === this.lastFlushDepth) {
// Depth didn't changed, so it's a root value or entry/element set
if (this.flushDepth > 0) {
this.parseAndAppend(this.prepareAddition(fragment), true);
} else {
// That's an entire value on a top level
this.value = JSON.parse(fragment);
this.valueStack = {
value: this.value,
prev: null
};
}
} else if (this.flushDepth > this.lastFlushDepth) {
// Add missed closing brackets/parentheses
for (let i = this.flushDepth - 1; i >= this.lastFlushDepth; i--) {
fragment += this.stack[i] === STACK_OBJECT ? '}' : ']';
}
if (this.lastFlushDepth === 0) {
// That's a root value
this.value = JSON.parse(fragment);
this.valueStack = {
value: this.value,
prev: null
};
} else {
this.parseAndAppend(this.prepareAddition(fragment), true);
}
// Move down to the depths to the last object/array, which is current now
for (let i = this.lastFlushDepth || 1; i < this.flushDepth; i++) {
let value = this.valueStack.value;
if (this.stack[i - 1] === STACK_OBJECT) {
// find last entry
let key;
// eslint-disable-next-line curly
for (key in value);
value = value[key];
} else {
// last element
value = value[value.length - 1];
}
this.valueStack = {
value,
prev: this.valueStack
};
}
} else /* this.flushDepth < this.lastFlushDepth */ {
fragment = this.prepareAddition(fragment);
// Add missed opening brackets/parentheses
for (let i = this.lastFlushDepth - 1; i >= this.flushDepth; i--) {
this.jsonParseOffset--;
fragment = (this.stack[i] === STACK_OBJECT ? '{' : '[') + fragment;
}
this.parseAndAppend(fragment, false);
for (let i = this.lastFlushDepth - 1; i >= this.flushDepth; i--) {
this.valueStack = this.valueStack.prev;
}
}
this.lastFlushDepth = this.flushDepth;
}
push(chunk) {
if (typeof chunk !== 'string') {
// Suppose chunk is Buffer or Uint8Array
// Prepend uncompleted byte sequence if any
if (this.pendingByteSeq !== null) {
const origRawChunk = chunk;
chunk = new Uint8Array(this.pendingByteSeq.length + origRawChunk.length);
chunk.set(this.pendingByteSeq);
chunk.set(origRawChunk, this.pendingByteSeq.length);
this.pendingByteSeq = null;
}
// In case Buffer/Uint8Array, an input is encoded in UTF8
// Seek for parts of uncompleted UTF8 symbol on the ending
// This makes sense only if we expect more chunks and last char is not multi-bytes
if (chunk[chunk.length - 1] > 127) {
for (let seqLength = 0; seqLength < chunk.length; seqLength++) {
const byte = chunk[chunk.length - 1 - seqLength];
// 10xxxxxx - 2nd, 3rd or 4th byte
// 110xxxxx first byte of 2-byte sequence
// 1110xxxx - first byte of 3-byte sequence
// 11110xxx - first byte of 4-byte sequence
if (byte >> 6 === 3) {
seqLength++;
// If the sequence is really incomplete, then preserve it
// for the future chunk and cut off it from the current chunk
if ((seqLength !== 4 && byte >> 3 === 0b11110) ||
(seqLength !== 3 && byte >> 4 === 0b1110) ||
(seqLength !== 2 && byte >> 5 === 0b110)) {
this.pendingByteSeq = chunk.slice(chunk.length - seqLength);
chunk = chunk.slice(0, -seqLength);
}
break;
}
}
}
// Convert chunk to a string, since single decode per chunk
// is much effective than decode multiple small substrings
chunk = decoder.decode(chunk);
}
const chunkLength = chunk.length;
let lastFlushPoint = 0;
let flushPoint = 0;
// Main scan loop
scan: for (let i = 0; i < chunkLength; i++) {
if (this.stateString) {
for (; i < chunkLength; i++) {
if (this.stateStringEscape) {
this.stateStringEscape = false;
} else {
switch (chunk.charCodeAt(i)) {
case 0x22: /* " */
this.stateString = false;
continue scan;
case 0x5C: /* \ */
this.stateStringEscape = true;
}
}
}
break;
}
switch (chunk.charCodeAt(i)) {
case 0x22: /* " */
this.stateString = true;
this.stateStringEscape = false;
break;
case 0x2C: /* , */
flushPoint = i;
break;
case 0x7B: /* { */
// Open an object
flushPoint = i + 1;
this.stack[this.flushDepth++] = STACK_OBJECT;
break;
case 0x5B: /* [ */
// Open an array
flushPoint = i + 1;
this.stack[this.flushDepth++] = STACK_ARRAY;
break;
case 0x5D: /* ] */
case 0x7D: /* } */
// Close an object or array
flushPoint = i + 1;
this.flushDepth--;
if (this.flushDepth < this.lastFlushDepth) {
this.flush(chunk, lastFlushPoint, flushPoint);
lastFlushPoint = flushPoint;
}
break;
case 0x09: /* \t */
case 0x0A: /* \n */
case 0x0D: /* \r */
case 0x20: /* space */
// Move points forward when they points on current position and it's a whitespace
if (lastFlushPoint === i) {
lastFlushPoint++;
}
if (flushPoint === i) {
flushPoint++;
}
break;
}
}
if (flushPoint > lastFlushPoint) {
this.flush(chunk, lastFlushPoint, flushPoint);
}
// Produce pendingChunk if something left
if (flushPoint < chunkLength) {
if (this.pendingChunk !== null) {
// When there is already a pending chunk then no flush happened,
// appending entire chunk to pending one
this.pendingChunk += chunk;
} else {
// Create a pending chunk, it will start with non-whitespace since
// flushPoint was moved forward away from whitespaces on scan
this.pendingChunk = chunk.slice(flushPoint, chunkLength);
}
}
this.chunkOffset += chunkLength;
}
finish() {
if (this.pendingChunk !== null) {
this.flush('', 0, 0);
this.pendingChunk = null;
}
return this.value;
}
}
var src = {
version: version,
stringifyInfo: stringifyInfo,
stringifyStream: stringifyStreamBrowser,
parseChunked: parseChunked
};
return src;
}));

File diff suppressed because one or more lines are too long

View File

@@ -1 +0,0 @@
module.exports = "0.5.7";

View File

@@ -1,31 +0,0 @@
declare module '@discoveryjs/json-ext' {
import { Readable } from 'stream';
type TReplacer =
| ((this: any, key: string, value: any) => any)
| string[]
| number[]
| null;
type TSpace = string | number | null;
type TChunk = string | Buffer | Uint8Array;
export function parseChunked(input: Readable): Promise<any>;
export function parseChunked(input: () => (Iterable<TChunk> | AsyncIterable<TChunk>)): Promise<any>;
export function stringifyStream(value: any, replacer?: TReplacer, space?: TSpace): Readable;
export function stringifyInfo(
value: any,
replacer?: TReplacer,
space?: TSpace,
options?: {
async?: boolean;
continueOnCircular?: boolean;
}
): {
minLength: number;
circular: any[];
duplicate: any[];
async: any[];
};
}

View File

@@ -1,56 +0,0 @@
{
"name": "@discoveryjs/json-ext",
"version": "0.5.7",
"description": "A set of utilities that extend the use of JSON",
"keywords": [
"json",
"utils",
"stream",
"async",
"promise",
"stringify",
"info"
],
"author": "Roman Dvornov <rdvornov@gmail.com> (https://github.com/lahmatiy)",
"license": "MIT",
"repository": "discoveryjs/json-ext",
"main": "./src/index",
"browser": {
"./src/stringify-stream.js": "./src/stringify-stream-browser.js",
"./src/text-decoder.js": "./src/text-decoder-browser.js",
"./src/version.js": "./dist/version.js"
},
"types": "./index.d.ts",
"scripts": {
"test": "mocha --reporter progress",
"lint": "eslint src test",
"lint-and-test": "npm run lint && npm test",
"build": "rollup --config",
"test:all": "npm run test:src && npm run test:dist",
"test:src": "npm test",
"test:dist": "cross-env MODE=dist npm test && cross-env MODE=dist-min npm test",
"build-and-test": "npm run build && npm run test:dist",
"coverage": "c8 --reporter=lcovonly npm test",
"prepublishOnly": "npm run lint && npm test && npm run build-and-test"
},
"devDependencies": {
"@rollup/plugin-commonjs": "^15.1.0",
"@rollup/plugin-json": "^4.1.0",
"@rollup/plugin-node-resolve": "^9.0.0",
"c8": "^7.10.0",
"chalk": "^4.1.0",
"cross-env": "^7.0.3",
"eslint": "^8.10.0",
"mocha": "^8.4.0",
"rollup": "^2.28.2",
"rollup-plugin-terser": "^7.0.2"
},
"engines": {
"node": ">=10.0.0"
},
"files": [
"dist",
"src",
"index.d.ts"
]
}

View File

@@ -1,6 +0,0 @@
module.exports = {
version: require('./version'),
stringifyInfo: require('./stringify-info'),
stringifyStream: require('./stringify-stream'),
parseChunked: require('./parse-chunked')
};

View File

@@ -1,384 +0,0 @@
const { isReadableStream } = require('./utils');
const TextDecoder = require('./text-decoder');
const STACK_OBJECT = 1;
const STACK_ARRAY = 2;
const decoder = new TextDecoder();
function isObject(value) {
return value !== null && typeof value === 'object';
}
function adjustPosition(error, parser) {
if (error.name === 'SyntaxError' && parser.jsonParseOffset) {
error.message = error.message.replace(/at position (\d+)/, (_, pos) =>
'at position ' + (Number(pos) + parser.jsonParseOffset)
);
}
return error;
}
function append(array, elements) {
// Note: Avoid to use array.push(...elements) since it may lead to
// "RangeError: Maximum call stack size exceeded" for a long arrays
const initialLength = array.length;
array.length += elements.length;
for (let i = 0; i < elements.length; i++) {
array[initialLength + i] = elements[i];
}
}
module.exports = function(chunkEmitter) {
let parser = new ChunkParser();
if (isObject(chunkEmitter) && isReadableStream(chunkEmitter)) {
return new Promise((resolve, reject) => {
chunkEmitter
.on('data', chunk => {
try {
parser.push(chunk);
} catch (e) {
reject(adjustPosition(e, parser));
parser = null;
}
})
.on('error', (e) => {
parser = null;
reject(e);
})
.on('end', () => {
try {
resolve(parser.finish());
} catch (e) {
reject(adjustPosition(e, parser));
} finally {
parser = null;
}
});
});
}
if (typeof chunkEmitter === 'function') {
const iterator = chunkEmitter();
if (isObject(iterator) && (Symbol.iterator in iterator || Symbol.asyncIterator in iterator)) {
return new Promise(async (resolve, reject) => {
try {
for await (const chunk of iterator) {
parser.push(chunk);
}
resolve(parser.finish());
} catch (e) {
reject(adjustPosition(e, parser));
} finally {
parser = null;
}
});
}
}
throw new Error(
'Chunk emitter should be readable stream, generator, ' +
'async generator or function returning an iterable object'
);
};
class ChunkParser {
constructor() {
this.value = undefined;
this.valueStack = null;
this.stack = new Array(100);
this.lastFlushDepth = 0;
this.flushDepth = 0;
this.stateString = false;
this.stateStringEscape = false;
this.pendingByteSeq = null;
this.pendingChunk = null;
this.chunkOffset = 0;
this.jsonParseOffset = 0;
}
parseAndAppend(fragment, wrap) {
// Append new entries or elements
if (this.stack[this.lastFlushDepth - 1] === STACK_OBJECT) {
if (wrap) {
this.jsonParseOffset--;
fragment = '{' + fragment + '}';
}
Object.assign(this.valueStack.value, JSON.parse(fragment));
} else {
if (wrap) {
this.jsonParseOffset--;
fragment = '[' + fragment + ']';
}
append(this.valueStack.value, JSON.parse(fragment));
}
}
prepareAddition(fragment) {
const { value } = this.valueStack;
const expectComma = Array.isArray(value)
? value.length !== 0
: Object.keys(value).length !== 0;
if (expectComma) {
// Skip a comma at the beginning of fragment, otherwise it would
// fail to parse
if (fragment[0] === ',') {
this.jsonParseOffset++;
return fragment.slice(1);
}
// When value (an object or array) is not empty and a fragment
// doesn't start with a comma, a single valid fragment starting
// is a closing bracket. If it's not, a prefix is adding to fail
// parsing. Otherwise, the sequence of chunks can be successfully
// parsed, although it should not, e.g. ["[{}", "{}]"]
if (fragment[0] !== '}' && fragment[0] !== ']') {
this.jsonParseOffset -= 3;
return '[[]' + fragment;
}
}
return fragment;
}
flush(chunk, start, end) {
let fragment = chunk.slice(start, end);
// Save position correction an error in JSON.parse() if any
this.jsonParseOffset = this.chunkOffset + start;
// Prepend pending chunk if any
if (this.pendingChunk !== null) {
fragment = this.pendingChunk + fragment;
this.jsonParseOffset -= this.pendingChunk.length;
this.pendingChunk = null;
}
if (this.flushDepth === this.lastFlushDepth) {
// Depth didn't changed, so it's a root value or entry/element set
if (this.flushDepth > 0) {
this.parseAndAppend(this.prepareAddition(fragment), true);
} else {
// That's an entire value on a top level
this.value = JSON.parse(fragment);
this.valueStack = {
value: this.value,
prev: null
};
}
} else if (this.flushDepth > this.lastFlushDepth) {
// Add missed closing brackets/parentheses
for (let i = this.flushDepth - 1; i >= this.lastFlushDepth; i--) {
fragment += this.stack[i] === STACK_OBJECT ? '}' : ']';
}
if (this.lastFlushDepth === 0) {
// That's a root value
this.value = JSON.parse(fragment);
this.valueStack = {
value: this.value,
prev: null
};
} else {
this.parseAndAppend(this.prepareAddition(fragment), true);
}
// Move down to the depths to the last object/array, which is current now
for (let i = this.lastFlushDepth || 1; i < this.flushDepth; i++) {
let value = this.valueStack.value;
if (this.stack[i - 1] === STACK_OBJECT) {
// find last entry
let key;
// eslint-disable-next-line curly
for (key in value);
value = value[key];
} else {
// last element
value = value[value.length - 1];
}
this.valueStack = {
value,
prev: this.valueStack
};
}
} else /* this.flushDepth < this.lastFlushDepth */ {
fragment = this.prepareAddition(fragment);
// Add missed opening brackets/parentheses
for (let i = this.lastFlushDepth - 1; i >= this.flushDepth; i--) {
this.jsonParseOffset--;
fragment = (this.stack[i] === STACK_OBJECT ? '{' : '[') + fragment;
}
this.parseAndAppend(fragment, false);
for (let i = this.lastFlushDepth - 1; i >= this.flushDepth; i--) {
this.valueStack = this.valueStack.prev;
}
}
this.lastFlushDepth = this.flushDepth;
}
push(chunk) {
if (typeof chunk !== 'string') {
// Suppose chunk is Buffer or Uint8Array
// Prepend uncompleted byte sequence if any
if (this.pendingByteSeq !== null) {
const origRawChunk = chunk;
chunk = new Uint8Array(this.pendingByteSeq.length + origRawChunk.length);
chunk.set(this.pendingByteSeq);
chunk.set(origRawChunk, this.pendingByteSeq.length);
this.pendingByteSeq = null;
}
// In case Buffer/Uint8Array, an input is encoded in UTF8
// Seek for parts of uncompleted UTF8 symbol on the ending
// This makes sense only if we expect more chunks and last char is not multi-bytes
if (chunk[chunk.length - 1] > 127) {
for (let seqLength = 0; seqLength < chunk.length; seqLength++) {
const byte = chunk[chunk.length - 1 - seqLength];
// 10xxxxxx - 2nd, 3rd or 4th byte
// 110xxxxx first byte of 2-byte sequence
// 1110xxxx - first byte of 3-byte sequence
// 11110xxx - first byte of 4-byte sequence
if (byte >> 6 === 3) {
seqLength++;
// If the sequence is really incomplete, then preserve it
// for the future chunk and cut off it from the current chunk
if ((seqLength !== 4 && byte >> 3 === 0b11110) ||
(seqLength !== 3 && byte >> 4 === 0b1110) ||
(seqLength !== 2 && byte >> 5 === 0b110)) {
this.pendingByteSeq = chunk.slice(chunk.length - seqLength);
chunk = chunk.slice(0, -seqLength);
}
break;
}
}
}
// Convert chunk to a string, since single decode per chunk
// is much effective than decode multiple small substrings
chunk = decoder.decode(chunk);
}
const chunkLength = chunk.length;
let lastFlushPoint = 0;
let flushPoint = 0;
// Main scan loop
scan: for (let i = 0; i < chunkLength; i++) {
if (this.stateString) {
for (; i < chunkLength; i++) {
if (this.stateStringEscape) {
this.stateStringEscape = false;
} else {
switch (chunk.charCodeAt(i)) {
case 0x22: /* " */
this.stateString = false;
continue scan;
case 0x5C: /* \ */
this.stateStringEscape = true;
}
}
}
break;
}
switch (chunk.charCodeAt(i)) {
case 0x22: /* " */
this.stateString = true;
this.stateStringEscape = false;
break;
case 0x2C: /* , */
flushPoint = i;
break;
case 0x7B: /* { */
// Open an object
flushPoint = i + 1;
this.stack[this.flushDepth++] = STACK_OBJECT;
break;
case 0x5B: /* [ */
// Open an array
flushPoint = i + 1;
this.stack[this.flushDepth++] = STACK_ARRAY;
break;
case 0x5D: /* ] */
case 0x7D: /* } */
// Close an object or array
flushPoint = i + 1;
this.flushDepth--;
if (this.flushDepth < this.lastFlushDepth) {
this.flush(chunk, lastFlushPoint, flushPoint);
lastFlushPoint = flushPoint;
}
break;
case 0x09: /* \t */
case 0x0A: /* \n */
case 0x0D: /* \r */
case 0x20: /* space */
// Move points forward when they points on current position and it's a whitespace
if (lastFlushPoint === i) {
lastFlushPoint++;
}
if (flushPoint === i) {
flushPoint++;
}
break;
}
}
if (flushPoint > lastFlushPoint) {
this.flush(chunk, lastFlushPoint, flushPoint);
}
// Produce pendingChunk if something left
if (flushPoint < chunkLength) {
if (this.pendingChunk !== null) {
// When there is already a pending chunk then no flush happened,
// appending entire chunk to pending one
this.pendingChunk += chunk;
} else {
// Create a pending chunk, it will start with non-whitespace since
// flushPoint was moved forward away from whitespaces on scan
this.pendingChunk = chunk.slice(flushPoint, chunkLength);
}
}
this.chunkOffset += chunkLength;
}
finish() {
if (this.pendingChunk !== null) {
this.flush('', 0, 0);
this.pendingChunk = null;
}
return this.value;
}
};

View File

@@ -1,231 +0,0 @@
const {
normalizeReplacer,
normalizeSpace,
replaceValue,
getTypeNative,
getTypeAsync,
isLeadingSurrogate,
isTrailingSurrogate,
escapableCharCodeSubstitution,
type: {
PRIMITIVE,
OBJECT,
ARRAY,
PROMISE,
STRING_STREAM,
OBJECT_STREAM
}
} = require('./utils');
const charLength2048 = Array.from({ length: 2048 }).map((_, code) => {
if (escapableCharCodeSubstitution.hasOwnProperty(code)) {
return 2; // \X
}
if (code < 0x20) {
return 6; // \uXXXX
}
return code < 128 ? 1 : 2; // UTF8 bytes
});
function stringLength(str) {
let len = 0;
let prevLeadingSurrogate = false;
for (let i = 0; i < str.length; i++) {
const code = str.charCodeAt(i);
if (code < 2048) {
len += charLength2048[code];
} else if (isLeadingSurrogate(code)) {
len += 6; // \uXXXX since no pair with trailing surrogate yet
prevLeadingSurrogate = true;
continue;
} else if (isTrailingSurrogate(code)) {
len = prevLeadingSurrogate
? len - 2 // surrogate pair (4 bytes), since we calculate prev leading surrogate as 6 bytes, substruct 2 bytes
: len + 6; // \uXXXX
} else {
len += 3; // code >= 2048 is 3 bytes length for UTF8
}
prevLeadingSurrogate = false;
}
return len + 2; // +2 for quotes
}
function primitiveLength(value) {
switch (typeof value) {
case 'string':
return stringLength(value);
case 'number':
return Number.isFinite(value) ? String(value).length : 4 /* null */;
case 'boolean':
return value ? 4 /* true */ : 5 /* false */;
case 'undefined':
case 'object':
return 4; /* null */
default:
return 0;
}
}
function spaceLength(space) {
space = normalizeSpace(space);
return typeof space === 'string' ? space.length : 0;
}
module.exports = function jsonStringifyInfo(value, replacer, space, options) {
function walk(holder, key, value) {
if (stop) {
return;
}
value = replaceValue(holder, key, value, replacer);
let type = getType(value);
// check for circular structure
if (type !== PRIMITIVE && stack.has(value)) {
circular.add(value);
length += 4; // treat as null
if (!options.continueOnCircular) {
stop = true;
}
return;
}
switch (type) {
case PRIMITIVE:
if (value !== undefined || Array.isArray(holder)) {
length += primitiveLength(value);
} else if (holder === root) {
length += 9; // FIXME: that's the length of undefined, should we normalize behaviour to convert it to null?
}
break;
case OBJECT: {
if (visited.has(value)) {
duplicate.add(value);
length += visited.get(value);
break;
}
const valueLength = length;
let entries = 0;
length += 2; // {}
stack.add(value);
for (const key in value) {
if (hasOwnProperty.call(value, key) && (allowlist === null || allowlist.has(key))) {
const prevLength = length;
walk(value, key, value[key]);
if (prevLength !== length) {
// value is printed
length += stringLength(key) + 1; // "key":
entries++;
}
}
}
if (entries > 1) {
length += entries - 1; // commas
}
stack.delete(value);
if (space > 0 && entries > 0) {
length += (1 + (stack.size + 1) * space + 1) * entries; // for each key-value: \n{space}
length += 1 + stack.size * space; // for }
}
visited.set(value, length - valueLength);
break;
}
case ARRAY: {
if (visited.has(value)) {
duplicate.add(value);
length += visited.get(value);
break;
}
const valueLength = length;
length += 2; // []
stack.add(value);
for (let i = 0; i < value.length; i++) {
walk(value, i, value[i]);
}
if (value.length > 1) {
length += value.length - 1; // commas
}
stack.delete(value);
if (space > 0 && value.length > 0) {
length += (1 + (stack.size + 1) * space) * value.length; // for each element: \n{space}
length += 1 + stack.size * space; // for ]
}
visited.set(value, length - valueLength);
break;
}
case PROMISE:
case STRING_STREAM:
async.add(value);
break;
case OBJECT_STREAM:
length += 2; // []
async.add(value);
break;
}
}
let allowlist = null;
replacer = normalizeReplacer(replacer);
if (Array.isArray(replacer)) {
allowlist = new Set(replacer);
replacer = null;
}
space = spaceLength(space);
options = options || {};
const visited = new Map();
const stack = new Set();
const duplicate = new Set();
const circular = new Set();
const async = new Set();
const getType = options.async ? getTypeAsync : getTypeNative;
const root = { '': value };
let stop = false;
let length = 0;
walk(root, '', value);
return {
minLength: isNaN(length) ? Infinity : length,
circular: [...circular],
duplicate: [...duplicate],
async: [...async]
};
};

View File

@@ -1,3 +0,0 @@
module.exports = () => {
throw new Error('Method is not supported');
};

View File

@@ -1,408 +0,0 @@
const { Readable } = require('stream');
const {
normalizeReplacer,
normalizeSpace,
replaceValue,
getTypeAsync,
type: {
PRIMITIVE,
OBJECT,
ARRAY,
PROMISE,
STRING_STREAM,
OBJECT_STREAM
}
} = require('./utils');
const noop = () => {};
const hasOwnProperty = Object.prototype.hasOwnProperty;
// TODO: Remove when drop support for Node.js 10
// Node.js 10 has no well-formed JSON.stringify()
// https://github.com/tc39/proposal-well-formed-stringify
// Adopted code from https://bugs.chromium.org/p/v8/issues/detail?id=7782#c12
const wellformedStringStringify = JSON.stringify('\ud800') === '"\\ud800"'
? JSON.stringify
: s => JSON.stringify(s).replace(
/\p{Surrogate}/gu,
m => `\\u${m.charCodeAt(0).toString(16)}`
);
function push() {
this.push(this._stack.value);
this.popStack();
}
function pushPrimitive(value) {
switch (typeof value) {
case 'string':
this.push(this.encodeString(value));
break;
case 'number':
this.push(Number.isFinite(value) ? this.encodeNumber(value) : 'null');
break;
case 'boolean':
this.push(value ? 'true' : 'false');
break;
case 'undefined':
case 'object': // typeof null === 'object'
this.push('null');
break;
default:
this.destroy(new TypeError(`Do not know how to serialize a ${value.constructor && value.constructor.name || typeof value}`));
}
}
function processObjectEntry(key) {
const current = this._stack;
if (!current.first) {
current.first = true;
} else {
this.push(',');
}
if (this.space) {
this.push(`\n${this.space.repeat(this._depth)}${this.encodeString(key)}: `);
} else {
this.push(this.encodeString(key) + ':');
}
}
function processObject() {
const current = this._stack;
// when no keys left, remove obj from stack
if (current.index === current.keys.length) {
if (this.space && current.first) {
this.push(`\n${this.space.repeat(this._depth - 1)}}`);
} else {
this.push('}');
}
this.popStack();
return;
}
const key = current.keys[current.index];
this.processValue(current.value, key, current.value[key], processObjectEntry);
current.index++;
}
function processArrayItem(index) {
if (index !== 0) {
this.push(',');
}
if (this.space) {
this.push(`\n${this.space.repeat(this._depth)}`);
}
}
function processArray() {
const current = this._stack;
if (current.index === current.value.length) {
if (this.space && current.index > 0) {
this.push(`\n${this.space.repeat(this._depth - 1)}]`);
} else {
this.push(']');
}
this.popStack();
return;
}
this.processValue(current.value, current.index, current.value[current.index], processArrayItem);
current.index++;
}
function createStreamReader(fn) {
return function() {
const current = this._stack;
const data = current.value.read(this._readSize);
if (data !== null) {
current.first = false;
fn.call(this, data, current);
} else {
if ((current.first && !current.value._readableState.reading) || current.ended) {
this.popStack();
} else {
current.first = true;
current.awaiting = true;
}
}
};
}
const processReadableObject = createStreamReader(function(data, current) {
this.processValue(current.value, current.index, data, processArrayItem);
current.index++;
});
const processReadableString = createStreamReader(function(data) {
this.push(data);
});
class JsonStringifyStream extends Readable {
constructor(value, replacer, space) {
super({
autoDestroy: true
});
this.getKeys = Object.keys;
this.replacer = normalizeReplacer(replacer);
if (Array.isArray(this.replacer)) {
const allowlist = this.replacer;
this.getKeys = (value) => allowlist.filter(key => hasOwnProperty.call(value, key));
this.replacer = null;
}
this.space = normalizeSpace(space);
this._depth = 0;
this.error = null;
this._processing = false;
this._ended = false;
this._readSize = 0;
this._buffer = '';
this._stack = null;
this._visited = new WeakSet();
this.pushStack({
handler: () => {
this.popStack();
this.processValue({ '': value }, '', value, noop);
}
});
}
encodeString(value) {
if (/[^\x20-\uD799]|[\x22\x5c]/.test(value)) {
return wellformedStringStringify(value);
}
return '"' + value + '"';
}
encodeNumber(value) {
return value;
}
processValue(holder, key, value, callback) {
value = replaceValue(holder, key, value, this.replacer);
let type = getTypeAsync(value);
switch (type) {
case PRIMITIVE:
if (callback !== processObjectEntry || value !== undefined) {
callback.call(this, key);
pushPrimitive.call(this, value);
}
break;
case OBJECT:
callback.call(this, key);
// check for circular structure
if (this._visited.has(value)) {
return this.destroy(new TypeError('Converting circular structure to JSON'));
}
this._visited.add(value);
this._depth++;
this.push('{');
this.pushStack({
handler: processObject,
value,
index: 0,
first: false,
keys: this.getKeys(value)
});
break;
case ARRAY:
callback.call(this, key);
// check for circular structure
if (this._visited.has(value)) {
return this.destroy(new TypeError('Converting circular structure to JSON'));
}
this._visited.add(value);
this.push('[');
this.pushStack({
handler: processArray,
value,
index: 0
});
this._depth++;
break;
case PROMISE:
this.pushStack({
handler: noop,
awaiting: true
});
Promise.resolve(value)
.then(resolved => {
this.popStack();
this.processValue(holder, key, resolved, callback);
this.processStack();
})
.catch(error => {
this.destroy(error);
});
break;
case STRING_STREAM:
case OBJECT_STREAM:
callback.call(this, key);
// TODO: Remove when drop support for Node.js 10
// Used `_readableState.endEmitted` as fallback, since Node.js 10 has no `readableEnded` getter
if (value.readableEnded || value._readableState.endEmitted) {
return this.destroy(new Error('Readable Stream has ended before it was serialized. All stream data have been lost'));
}
if (value.readableFlowing) {
return this.destroy(new Error('Readable Stream is in flowing mode, data may have been lost. Trying to pause stream.'));
}
if (type === OBJECT_STREAM) {
this.push('[');
this.pushStack({
handler: push,
value: this.space ? '\n' + this.space.repeat(this._depth) + ']' : ']'
});
this._depth++;
}
const self = this.pushStack({
handler: type === OBJECT_STREAM ? processReadableObject : processReadableString,
value,
index: 0,
first: false,
ended: false,
awaiting: !value.readable || value.readableLength === 0
});
const continueProcessing = () => {
if (self.awaiting) {
self.awaiting = false;
this.processStack();
}
};
value.once('error', error => this.destroy(error));
value.once('end', () => {
self.ended = true;
continueProcessing();
});
value.on('readable', continueProcessing);
break;
}
}
pushStack(node) {
node.prev = this._stack;
return this._stack = node;
}
popStack() {
const { handler, value } = this._stack;
if (handler === processObject || handler === processArray || handler === processReadableObject) {
this._visited.delete(value);
this._depth--;
}
this._stack = this._stack.prev;
}
processStack() {
if (this._processing || this._ended) {
return;
}
try {
this._processing = true;
while (this._stack !== null && !this._stack.awaiting) {
this._stack.handler.call(this);
if (!this._processing) {
return;
}
}
this._processing = false;
} catch (error) {
this.destroy(error);
return;
}
if (this._stack === null && !this._ended) {
this._finish();
this.push(null);
}
}
push(data) {
if (data !== null) {
this._buffer += data;
// check buffer overflow
if (this._buffer.length < this._readSize) {
return;
}
// flush buffer
data = this._buffer;
this._buffer = '';
this._processing = false;
}
super.push(data);
}
_read(size) {
// start processing
this._readSize = size || this.readableHighWaterMark;
this.processStack();
}
_finish() {
this._ended = true;
this._processing = false;
this._stack = null;
this._visited = null;
if (this._buffer && this._buffer.length) {
super.push(this._buffer); // flush buffer
}
this._buffer = '';
}
_destroy(error, cb) {
this.error = this.error || error;
this._finish();
cb(error);
}
}
module.exports = function createJsonStringifyStream(value, replacer, space) {
return new JsonStringifyStream(value, replacer, space);
};

View File

@@ -1 +0,0 @@
module.exports = TextDecoder;

View File

@@ -1 +0,0 @@
module.exports = require('util').TextDecoder;

View File

@@ -1,149 +0,0 @@
const PrimitiveType = 1;
const ObjectType = 2;
const ArrayType = 3;
const PromiseType = 4;
const ReadableStringType = 5;
const ReadableObjectType = 6;
// https://tc39.es/ecma262/#table-json-single-character-escapes
const escapableCharCodeSubstitution = { // JSON Single Character Escape Sequences
0x08: '\\b',
0x09: '\\t',
0x0a: '\\n',
0x0c: '\\f',
0x0d: '\\r',
0x22: '\\\"',
0x5c: '\\\\'
};
function isLeadingSurrogate(code) {
return code >= 0xD800 && code <= 0xDBFF;
}
function isTrailingSurrogate(code) {
return code >= 0xDC00 && code <= 0xDFFF;
}
function isReadableStream(value) {
return (
typeof value.pipe === 'function' &&
typeof value._read === 'function' &&
typeof value._readableState === 'object' && value._readableState !== null
);
}
function replaceValue(holder, key, value, replacer) {
if (value && typeof value.toJSON === 'function') {
value = value.toJSON();
}
if (replacer !== null) {
value = replacer.call(holder, String(key), value);
}
switch (typeof value) {
case 'function':
case 'symbol':
value = undefined;
break;
case 'object':
if (value !== null) {
const cls = value.constructor;
if (cls === String || cls === Number || cls === Boolean) {
value = value.valueOf();
}
}
break;
}
return value;
}
function getTypeNative(value) {
if (value === null || typeof value !== 'object') {
return PrimitiveType;
}
if (Array.isArray(value)) {
return ArrayType;
}
return ObjectType;
}
function getTypeAsync(value) {
if (value === null || typeof value !== 'object') {
return PrimitiveType;
}
if (typeof value.then === 'function') {
return PromiseType;
}
if (isReadableStream(value)) {
return value._readableState.objectMode ? ReadableObjectType : ReadableStringType;
}
if (Array.isArray(value)) {
return ArrayType;
}
return ObjectType;
}
function normalizeReplacer(replacer) {
if (typeof replacer === 'function') {
return replacer;
}
if (Array.isArray(replacer)) {
const allowlist = new Set(replacer
.map(item => {
const cls = item && item.constructor;
return cls === String || cls === Number ? String(item) : null;
})
.filter(item => typeof item === 'string')
);
return [...allowlist];
}
return null;
}
function normalizeSpace(space) {
if (typeof space === 'number') {
if (!Number.isFinite(space) || space < 1) {
return false;
}
return ' '.repeat(Math.min(space, 10));
}
if (typeof space === 'string') {
return space.slice(0, 10) || false;
}
return false;
}
module.exports = {
escapableCharCodeSubstitution,
isLeadingSurrogate,
isTrailingSurrogate,
type: {
PRIMITIVE: PrimitiveType,
PROMISE: PromiseType,
ARRAY: ArrayType,
OBJECT: ObjectType,
STRING_STREAM: ReadableStringType,
OBJECT_STREAM: ReadableObjectType
},
isReadableStream,
replaceValue,
getTypeNative,
getTypeAsync,
normalizeReplacer,
normalizeSpace
};

View File

@@ -1 +0,0 @@
module.exports = require('../package.json').version;

14
live2d/node_modules/@isaacs/cliui/LICENSE.txt generated vendored Normal file
View File

@@ -0,0 +1,14 @@
Copyright (c) 2015, Contributors
Permission to use, copy, modify, and/or distribute this software
for any purpose with or without fee is hereby granted, provided
that the above copyright notice and this permission notice
appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE
LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES
OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

143
live2d/node_modules/@isaacs/cliui/README.md generated vendored Normal file
View File

@@ -0,0 +1,143 @@
# @isaacs/cliui
Temporary fork of [cliui](http://npm.im/cliui).
![ci](https://github.com/yargs/cliui/workflows/ci/badge.svg)
[![NPM version](https://img.shields.io/npm/v/cliui.svg)](https://www.npmjs.com/package/cliui)
[![Conventional Commits](https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg)](https://conventionalcommits.org)
![nycrc config on GitHub](https://img.shields.io/nycrc/yargs/cliui)
easily create complex multi-column command-line-interfaces.
## Example
```js
const ui = require('cliui')()
ui.div('Usage: $0 [command] [options]')
ui.div({
text: 'Options:',
padding: [2, 0, 1, 0]
})
ui.div(
{
text: "-f, --file",
width: 20,
padding: [0, 4, 0, 4]
},
{
text: "the file to load." +
chalk.green("(if this description is long it wraps).")
,
width: 20
},
{
text: chalk.red("[required]"),
align: 'right'
}
)
console.log(ui.toString())
```
## Deno/ESM Support
As of `v7` `cliui` supports [Deno](https://github.com/denoland/deno) and
[ESM](https://nodejs.org/api/esm.html#esm_ecmascript_modules):
```typescript
import cliui from "https://deno.land/x/cliui/deno.ts";
const ui = cliui({})
ui.div('Usage: $0 [command] [options]')
ui.div({
text: 'Options:',
padding: [2, 0, 1, 0]
})
ui.div({
text: "-f, --file",
width: 20,
padding: [0, 4, 0, 4]
})
console.log(ui.toString())
```
<img width="500" src="screenshot.png">
## Layout DSL
cliui exposes a simple layout DSL:
If you create a single `ui.div`, passing a string rather than an
object:
* `\n`: characters will be interpreted as new rows.
* `\t`: characters will be interpreted as new columns.
* `\s`: characters will be interpreted as padding.
**as an example...**
```js
var ui = require('./')({
width: 60
})
ui.div(
'Usage: node ./bin/foo.js\n' +
' <regex>\t provide a regex\n' +
' <glob>\t provide a glob\t [required]'
)
console.log(ui.toString())
```
**will output:**
```shell
Usage: node ./bin/foo.js
<regex> provide a regex
<glob> provide a glob [required]
```
## Methods
```js
cliui = require('cliui')
```
### cliui({width: integer})
Specify the maximum width of the UI being generated.
If no width is provided, cliui will try to get the current window's width and use it, and if that doesn't work, width will be set to `80`.
### cliui({wrap: boolean})
Enable or disable the wrapping of text in a column.
### cliui.div(column, column, column)
Create a row with any number of columns, a column
can either be a string, or an object with the following
options:
* **text:** some text to place in the column.
* **width:** the width of a column.
* **align:** alignment, `right` or `center`.
* **padding:** `[top, right, bottom, left]`.
* **border:** should a border be placed around the div?
### cliui.span(column, column, column)
Similar to `div`, except the next row will be appended without
a new line being created.
### cliui.resetOutput()
Resets the UI elements of the current cliui instance, maintaining the values
set for `width` and `wrap`.

317
live2d/node_modules/@isaacs/cliui/build/index.cjs generated vendored Normal file
View File

@@ -0,0 +1,317 @@
'use strict';
const align = {
right: alignRight,
center: alignCenter
};
const top = 0;
const right = 1;
const bottom = 2;
const left = 3;
class UI {
constructor(opts) {
var _a;
this.width = opts.width;
/* c8 ignore start */
this.wrap = (_a = opts.wrap) !== null && _a !== void 0 ? _a : true;
/* c8 ignore stop */
this.rows = [];
}
span(...args) {
const cols = this.div(...args);
cols.span = true;
}
resetOutput() {
this.rows = [];
}
div(...args) {
if (args.length === 0) {
this.div('');
}
if (this.wrap && this.shouldApplyLayoutDSL(...args) && typeof args[0] === 'string') {
return this.applyLayoutDSL(args[0]);
}
const cols = args.map(arg => {
if (typeof arg === 'string') {
return this.colFromString(arg);
}
return arg;
});
this.rows.push(cols);
return cols;
}
shouldApplyLayoutDSL(...args) {
return args.length === 1 && typeof args[0] === 'string' &&
/[\t\n]/.test(args[0]);
}
applyLayoutDSL(str) {
const rows = str.split('\n').map(row => row.split('\t'));
let leftColumnWidth = 0;
// simple heuristic for layout, make sure the
// second column lines up along the left-hand.
// don't allow the first column to take up more
// than 50% of the screen.
rows.forEach(columns => {
if (columns.length > 1 && mixin.stringWidth(columns[0]) > leftColumnWidth) {
leftColumnWidth = Math.min(Math.floor(this.width * 0.5), mixin.stringWidth(columns[0]));
}
});
// generate a table:
// replacing ' ' with padding calculations.
// using the algorithmically generated width.
rows.forEach(columns => {
this.div(...columns.map((r, i) => {
return {
text: r.trim(),
padding: this.measurePadding(r),
width: (i === 0 && columns.length > 1) ? leftColumnWidth : undefined
};
}));
});
return this.rows[this.rows.length - 1];
}
colFromString(text) {
return {
text,
padding: this.measurePadding(text)
};
}
measurePadding(str) {
// measure padding without ansi escape codes
const noAnsi = mixin.stripAnsi(str);
return [0, noAnsi.match(/\s*$/)[0].length, 0, noAnsi.match(/^\s*/)[0].length];
}
toString() {
const lines = [];
this.rows.forEach(row => {
this.rowToString(row, lines);
});
// don't display any lines with the
// hidden flag set.
return lines
.filter(line => !line.hidden)
.map(line => line.text)
.join('\n');
}
rowToString(row, lines) {
this.rasterize(row).forEach((rrow, r) => {
let str = '';
rrow.forEach((col, c) => {
const { width } = row[c]; // the width with padding.
const wrapWidth = this.negatePadding(row[c]); // the width without padding.
let ts = col; // temporary string used during alignment/padding.
if (wrapWidth > mixin.stringWidth(col)) {
ts += ' '.repeat(wrapWidth - mixin.stringWidth(col));
}
// align the string within its column.
if (row[c].align && row[c].align !== 'left' && this.wrap) {
const fn = align[row[c].align];
ts = fn(ts, wrapWidth);
if (mixin.stringWidth(ts) < wrapWidth) {
/* c8 ignore start */
const w = width || 0;
/* c8 ignore stop */
ts += ' '.repeat(w - mixin.stringWidth(ts) - 1);
}
}
// apply border and padding to string.
const padding = row[c].padding || [0, 0, 0, 0];
if (padding[left]) {
str += ' '.repeat(padding[left]);
}
str += addBorder(row[c], ts, '| ');
str += ts;
str += addBorder(row[c], ts, ' |');
if (padding[right]) {
str += ' '.repeat(padding[right]);
}
// if prior row is span, try to render the
// current row on the prior line.
if (r === 0 && lines.length > 0) {
str = this.renderInline(str, lines[lines.length - 1]);
}
});
// remove trailing whitespace.
lines.push({
text: str.replace(/ +$/, ''),
span: row.span
});
});
return lines;
}
// if the full 'source' can render in
// the target line, do so.
renderInline(source, previousLine) {
const match = source.match(/^ */);
/* c8 ignore start */
const leadingWhitespace = match ? match[0].length : 0;
/* c8 ignore stop */
const target = previousLine.text;
const targetTextWidth = mixin.stringWidth(target.trimEnd());
if (!previousLine.span) {
return source;
}
// if we're not applying wrapping logic,
// just always append to the span.
if (!this.wrap) {
previousLine.hidden = true;
return target + source;
}
if (leadingWhitespace < targetTextWidth) {
return source;
}
previousLine.hidden = true;
return target.trimEnd() + ' '.repeat(leadingWhitespace - targetTextWidth) + source.trimStart();
}
rasterize(row) {
const rrows = [];
const widths = this.columnWidths(row);
let wrapped;
// word wrap all columns, and create
// a data-structure that is easy to rasterize.
row.forEach((col, c) => {
// leave room for left and right padding.
col.width = widths[c];
if (this.wrap) {
wrapped = mixin.wrap(col.text, this.negatePadding(col), { hard: true }).split('\n');
}
else {
wrapped = col.text.split('\n');
}
if (col.border) {
wrapped.unshift('.' + '-'.repeat(this.negatePadding(col) + 2) + '.');
wrapped.push("'" + '-'.repeat(this.negatePadding(col) + 2) + "'");
}
// add top and bottom padding.
if (col.padding) {
wrapped.unshift(...new Array(col.padding[top] || 0).fill(''));
wrapped.push(...new Array(col.padding[bottom] || 0).fill(''));
}
wrapped.forEach((str, r) => {
if (!rrows[r]) {
rrows.push([]);
}
const rrow = rrows[r];
for (let i = 0; i < c; i++) {
if (rrow[i] === undefined) {
rrow.push('');
}
}
rrow.push(str);
});
});
return rrows;
}
negatePadding(col) {
/* c8 ignore start */
let wrapWidth = col.width || 0;
/* c8 ignore stop */
if (col.padding) {
wrapWidth -= (col.padding[left] || 0) + (col.padding[right] || 0);
}
if (col.border) {
wrapWidth -= 4;
}
return wrapWidth;
}
columnWidths(row) {
if (!this.wrap) {
return row.map(col => {
return col.width || mixin.stringWidth(col.text);
});
}
let unset = row.length;
let remainingWidth = this.width;
// column widths can be set in config.
const widths = row.map(col => {
if (col.width) {
unset--;
remainingWidth -= col.width;
return col.width;
}
return undefined;
});
// any unset widths should be calculated.
/* c8 ignore start */
const unsetWidth = unset ? Math.floor(remainingWidth / unset) : 0;
/* c8 ignore stop */
return widths.map((w, i) => {
if (w === undefined) {
return Math.max(unsetWidth, _minWidth(row[i]));
}
return w;
});
}
}
function addBorder(col, ts, style) {
if (col.border) {
if (/[.']-+[.']/.test(ts)) {
return '';
}
if (ts.trim().length !== 0) {
return style;
}
return ' ';
}
return '';
}
// calculates the minimum width of
// a column, based on padding preferences.
function _minWidth(col) {
const padding = col.padding || [];
const minWidth = 1 + (padding[left] || 0) + (padding[right] || 0);
if (col.border) {
return minWidth + 4;
}
return minWidth;
}
function getWindowWidth() {
/* c8 ignore start */
if (typeof process === 'object' && process.stdout && process.stdout.columns) {
return process.stdout.columns;
}
return 80;
}
/* c8 ignore stop */
function alignRight(str, width) {
str = str.trim();
const strWidth = mixin.stringWidth(str);
if (strWidth < width) {
return ' '.repeat(width - strWidth) + str;
}
return str;
}
function alignCenter(str, width) {
str = str.trim();
const strWidth = mixin.stringWidth(str);
/* c8 ignore start */
if (strWidth >= width) {
return str;
}
/* c8 ignore stop */
return ' '.repeat((width - strWidth) >> 1) + str;
}
let mixin;
function cliui(opts, _mixin) {
mixin = _mixin;
return new UI({
/* c8 ignore start */
width: (opts === null || opts === void 0 ? void 0 : opts.width) || getWindowWidth(),
wrap: opts === null || opts === void 0 ? void 0 : opts.wrap
/* c8 ignore stop */
});
}
// Bootstrap cliui with CommonJS dependencies:
const stringWidth = require('string-width-cjs');
const stripAnsi = require('strip-ansi-cjs');
const wrap = require('wrap-ansi-cjs');
function ui(opts) {
return cliui(opts, {
stringWidth,
stripAnsi,
wrap
});
}
module.exports = ui;

43
live2d/node_modules/@isaacs/cliui/build/index.d.cts generated vendored Normal file
View File

@@ -0,0 +1,43 @@
interface UIOptions {
width: number;
wrap?: boolean;
rows?: string[];
}
interface Column {
text: string;
width?: number;
align?: "right" | "left" | "center";
padding: number[];
border?: boolean;
}
interface ColumnArray extends Array<Column> {
span: boolean;
}
interface Line {
hidden?: boolean;
text: string;
span?: boolean;
}
declare class UI {
width: number;
wrap: boolean;
rows: ColumnArray[];
constructor(opts: UIOptions);
span(...args: ColumnArray): void;
resetOutput(): void;
div(...args: (Column | string)[]): ColumnArray;
private shouldApplyLayoutDSL;
private applyLayoutDSL;
private colFromString;
private measurePadding;
toString(): string;
rowToString(row: ColumnArray, lines: Line[]): Line[];
// if the full 'source' can render in
// the target line, do so.
private renderInline;
private rasterize;
private negatePadding;
private columnWidths;
}
declare function ui(opts: UIOptions): UI;
export { ui as default };

302
live2d/node_modules/@isaacs/cliui/build/lib/index.js generated vendored Normal file
View File

@@ -0,0 +1,302 @@
'use strict';
const align = {
right: alignRight,
center: alignCenter
};
const top = 0;
const right = 1;
const bottom = 2;
const left = 3;
export class UI {
constructor(opts) {
var _a;
this.width = opts.width;
/* c8 ignore start */
this.wrap = (_a = opts.wrap) !== null && _a !== void 0 ? _a : true;
/* c8 ignore stop */
this.rows = [];
}
span(...args) {
const cols = this.div(...args);
cols.span = true;
}
resetOutput() {
this.rows = [];
}
div(...args) {
if (args.length === 0) {
this.div('');
}
if (this.wrap && this.shouldApplyLayoutDSL(...args) && typeof args[0] === 'string') {
return this.applyLayoutDSL(args[0]);
}
const cols = args.map(arg => {
if (typeof arg === 'string') {
return this.colFromString(arg);
}
return arg;
});
this.rows.push(cols);
return cols;
}
shouldApplyLayoutDSL(...args) {
return args.length === 1 && typeof args[0] === 'string' &&
/[\t\n]/.test(args[0]);
}
applyLayoutDSL(str) {
const rows = str.split('\n').map(row => row.split('\t'));
let leftColumnWidth = 0;
// simple heuristic for layout, make sure the
// second column lines up along the left-hand.
// don't allow the first column to take up more
// than 50% of the screen.
rows.forEach(columns => {
if (columns.length > 1 && mixin.stringWidth(columns[0]) > leftColumnWidth) {
leftColumnWidth = Math.min(Math.floor(this.width * 0.5), mixin.stringWidth(columns[0]));
}
});
// generate a table:
// replacing ' ' with padding calculations.
// using the algorithmically generated width.
rows.forEach(columns => {
this.div(...columns.map((r, i) => {
return {
text: r.trim(),
padding: this.measurePadding(r),
width: (i === 0 && columns.length > 1) ? leftColumnWidth : undefined
};
}));
});
return this.rows[this.rows.length - 1];
}
colFromString(text) {
return {
text,
padding: this.measurePadding(text)
};
}
measurePadding(str) {
// measure padding without ansi escape codes
const noAnsi = mixin.stripAnsi(str);
return [0, noAnsi.match(/\s*$/)[0].length, 0, noAnsi.match(/^\s*/)[0].length];
}
toString() {
const lines = [];
this.rows.forEach(row => {
this.rowToString(row, lines);
});
// don't display any lines with the
// hidden flag set.
return lines
.filter(line => !line.hidden)
.map(line => line.text)
.join('\n');
}
rowToString(row, lines) {
this.rasterize(row).forEach((rrow, r) => {
let str = '';
rrow.forEach((col, c) => {
const { width } = row[c]; // the width with padding.
const wrapWidth = this.negatePadding(row[c]); // the width without padding.
let ts = col; // temporary string used during alignment/padding.
if (wrapWidth > mixin.stringWidth(col)) {
ts += ' '.repeat(wrapWidth - mixin.stringWidth(col));
}
// align the string within its column.
if (row[c].align && row[c].align !== 'left' && this.wrap) {
const fn = align[row[c].align];
ts = fn(ts, wrapWidth);
if (mixin.stringWidth(ts) < wrapWidth) {
/* c8 ignore start */
const w = width || 0;
/* c8 ignore stop */
ts += ' '.repeat(w - mixin.stringWidth(ts) - 1);
}
}
// apply border and padding to string.
const padding = row[c].padding || [0, 0, 0, 0];
if (padding[left]) {
str += ' '.repeat(padding[left]);
}
str += addBorder(row[c], ts, '| ');
str += ts;
str += addBorder(row[c], ts, ' |');
if (padding[right]) {
str += ' '.repeat(padding[right]);
}
// if prior row is span, try to render the
// current row on the prior line.
if (r === 0 && lines.length > 0) {
str = this.renderInline(str, lines[lines.length - 1]);
}
});
// remove trailing whitespace.
lines.push({
text: str.replace(/ +$/, ''),
span: row.span
});
});
return lines;
}
// if the full 'source' can render in
// the target line, do so.
renderInline(source, previousLine) {
const match = source.match(/^ */);
/* c8 ignore start */
const leadingWhitespace = match ? match[0].length : 0;
/* c8 ignore stop */
const target = previousLine.text;
const targetTextWidth = mixin.stringWidth(target.trimEnd());
if (!previousLine.span) {
return source;
}
// if we're not applying wrapping logic,
// just always append to the span.
if (!this.wrap) {
previousLine.hidden = true;
return target + source;
}
if (leadingWhitespace < targetTextWidth) {
return source;
}
previousLine.hidden = true;
return target.trimEnd() + ' '.repeat(leadingWhitespace - targetTextWidth) + source.trimStart();
}
rasterize(row) {
const rrows = [];
const widths = this.columnWidths(row);
let wrapped;
// word wrap all columns, and create
// a data-structure that is easy to rasterize.
row.forEach((col, c) => {
// leave room for left and right padding.
col.width = widths[c];
if (this.wrap) {
wrapped = mixin.wrap(col.text, this.negatePadding(col), { hard: true }).split('\n');
}
else {
wrapped = col.text.split('\n');
}
if (col.border) {
wrapped.unshift('.' + '-'.repeat(this.negatePadding(col) + 2) + '.');
wrapped.push("'" + '-'.repeat(this.negatePadding(col) + 2) + "'");
}
// add top and bottom padding.
if (col.padding) {
wrapped.unshift(...new Array(col.padding[top] || 0).fill(''));
wrapped.push(...new Array(col.padding[bottom] || 0).fill(''));
}
wrapped.forEach((str, r) => {
if (!rrows[r]) {
rrows.push([]);
}
const rrow = rrows[r];
for (let i = 0; i < c; i++) {
if (rrow[i] === undefined) {
rrow.push('');
}
}
rrow.push(str);
});
});
return rrows;
}
negatePadding(col) {
/* c8 ignore start */
let wrapWidth = col.width || 0;
/* c8 ignore stop */
if (col.padding) {
wrapWidth -= (col.padding[left] || 0) + (col.padding[right] || 0);
}
if (col.border) {
wrapWidth -= 4;
}
return wrapWidth;
}
columnWidths(row) {
if (!this.wrap) {
return row.map(col => {
return col.width || mixin.stringWidth(col.text);
});
}
let unset = row.length;
let remainingWidth = this.width;
// column widths can be set in config.
const widths = row.map(col => {
if (col.width) {
unset--;
remainingWidth -= col.width;
return col.width;
}
return undefined;
});
// any unset widths should be calculated.
/* c8 ignore start */
const unsetWidth = unset ? Math.floor(remainingWidth / unset) : 0;
/* c8 ignore stop */
return widths.map((w, i) => {
if (w === undefined) {
return Math.max(unsetWidth, _minWidth(row[i]));
}
return w;
});
}
}
function addBorder(col, ts, style) {
if (col.border) {
if (/[.']-+[.']/.test(ts)) {
return '';
}
if (ts.trim().length !== 0) {
return style;
}
return ' ';
}
return '';
}
// calculates the minimum width of
// a column, based on padding preferences.
function _minWidth(col) {
const padding = col.padding || [];
const minWidth = 1 + (padding[left] || 0) + (padding[right] || 0);
if (col.border) {
return minWidth + 4;
}
return minWidth;
}
function getWindowWidth() {
/* c8 ignore start */
if (typeof process === 'object' && process.stdout && process.stdout.columns) {
return process.stdout.columns;
}
return 80;
}
/* c8 ignore stop */
function alignRight(str, width) {
str = str.trim();
const strWidth = mixin.stringWidth(str);
if (strWidth < width) {
return ' '.repeat(width - strWidth) + str;
}
return str;
}
function alignCenter(str, width) {
str = str.trim();
const strWidth = mixin.stringWidth(str);
/* c8 ignore start */
if (strWidth >= width) {
return str;
}
/* c8 ignore stop */
return ' '.repeat((width - strWidth) >> 1) + str;
}
let mixin;
export function cliui(opts, _mixin) {
mixin = _mixin;
return new UI({
/* c8 ignore start */
width: (opts === null || opts === void 0 ? void 0 : opts.width) || getWindowWidth(),
wrap: opts === null || opts === void 0 ? void 0 : opts.wrap
/* c8 ignore stop */
});
}

14
live2d/node_modules/@isaacs/cliui/index.mjs generated vendored Normal file
View File

@@ -0,0 +1,14 @@
// Bootstrap cliui with ESM dependencies:
import { cliui } from './build/lib/index.js'
import stringWidth from 'string-width'
import stripAnsi from 'strip-ansi'
import wrap from 'wrap-ansi'
export default function ui (opts) {
return cliui(opts, {
stringWidth,
stripAnsi,
wrap
})
}

86
live2d/node_modules/@isaacs/cliui/package.json generated vendored Normal file
View File

@@ -0,0 +1,86 @@
{
"name": "@isaacs/cliui",
"version": "8.0.2",
"description": "easily create complex multi-column command-line-interfaces",
"main": "build/index.cjs",
"exports": {
".": [
{
"import": "./index.mjs",
"require": "./build/index.cjs"
},
"./build/index.cjs"
]
},
"type": "module",
"module": "./index.mjs",
"scripts": {
"check": "standardx '**/*.ts' && standardx '**/*.js' && standardx '**/*.cjs'",
"fix": "standardx --fix '**/*.ts' && standardx --fix '**/*.js' && standardx --fix '**/*.cjs'",
"pretest": "rimraf build && tsc -p tsconfig.test.json && cross-env NODE_ENV=test npm run build:cjs",
"test": "c8 mocha ./test/*.cjs",
"test:esm": "c8 mocha ./test/**/*.mjs",
"postest": "check",
"coverage": "c8 report --check-coverage",
"precompile": "rimraf build",
"compile": "tsc",
"postcompile": "npm run build:cjs",
"build:cjs": "rollup -c",
"prepare": "npm run compile"
},
"repository": "yargs/cliui",
"standard": {
"ignore": [
"**/example/**"
],
"globals": [
"it"
]
},
"keywords": [
"cli",
"command-line",
"layout",
"design",
"console",
"wrap",
"table"
],
"author": "Ben Coe <ben@npmjs.com>",
"license": "ISC",
"dependencies": {
"string-width": "^5.1.2",
"string-width-cjs": "npm:string-width@^4.2.0",
"strip-ansi": "^7.0.1",
"strip-ansi-cjs": "npm:strip-ansi@^6.0.1",
"wrap-ansi": "^8.1.0",
"wrap-ansi-cjs": "npm:wrap-ansi@^7.0.0"
},
"devDependencies": {
"@types/node": "^14.0.27",
"@typescript-eslint/eslint-plugin": "^4.0.0",
"@typescript-eslint/parser": "^4.0.0",
"c8": "^7.3.0",
"chai": "^4.2.0",
"chalk": "^4.1.0",
"cross-env": "^7.0.2",
"eslint": "^7.6.0",
"eslint-plugin-import": "^2.22.0",
"eslint-plugin-node": "^11.1.0",
"gts": "^3.0.0",
"mocha": "^10.0.0",
"rimraf": "^3.0.2",
"rollup": "^2.23.1",
"rollup-plugin-ts": "^3.0.2",
"standardx": "^7.0.0",
"typescript": "^4.0.0"
},
"files": [
"build",
"index.mjs",
"!*.d.ts"
],
"engines": {
"node": ">=12"
}
}

View File

@@ -1,6 +1,6 @@
The MIT License
Copyright (c) 2013-2023 Mathew Groves, Chad Engler
Copyright (c) 2013-2018 Mathew Groves, Chad Engler
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
@@ -18,4 +18,4 @@ 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.
THE SOFTWARE.

View File

@@ -9,5 +9,8 @@ npm install @pixi/accessibility
## Usage
```js
import '@pixi/accessibility';
import { AccessibilityManager } from '@pixi/accessibility';
import { extensions } from '@pixi/core';
extensions.add(AccessibilityManager);
```

View File

@@ -0,0 +1,538 @@
/*!
* @pixi/accessibility - v6.5.10
* Compiled Thu, 06 Jul 2023 15:25:11 UTC
*
* @pixi/accessibility is licensed under the MIT License.
* http://www.opensource.org/licenses/mit-license
*/
this.PIXI = this.PIXI || {};
var _pixi_accessibility = (function (exports, display, utils, core) {
'use strict';
/**
* Default property values of accessible objects
* used by {@link PIXI.AccessibilityManager}.
* @private
* @function accessibleTarget
* @memberof PIXI
* @type {object}
* @example
* function MyObject() {}
*
* Object.assign(
* MyObject.prototype,
* PIXI.accessibleTarget
* );
*/
var accessibleTarget = {
/**
* Flag for if the object is accessible. If true AccessibilityManager will overlay a
* shadow div with attributes set
* @member {boolean}
* @memberof PIXI.DisplayObject#
*/
accessible: false,
/**
* Sets the title attribute of the shadow div
* If accessibleTitle AND accessibleHint has not been this will default to 'displayObject [tabIndex]'
* @member {?string}
* @memberof PIXI.DisplayObject#
*/
accessibleTitle: null,
/**
* Sets the aria-label attribute of the shadow div
* @member {string}
* @memberof PIXI.DisplayObject#
*/
accessibleHint: null,
/**
* @member {number}
* @memberof PIXI.DisplayObject#
* @private
* @todo Needs docs.
*/
tabIndex: 0,
/**
* @member {boolean}
* @memberof PIXI.DisplayObject#
* @todo Needs docs.
*/
_accessibleActive: false,
/**
* @member {boolean}
* @memberof PIXI.DisplayObject#
* @todo Needs docs.
*/
_accessibleDiv: null,
/**
* Specify the type of div the accessible layer is. Screen readers treat the element differently
* depending on this type. Defaults to button.
* @member {string}
* @memberof PIXI.DisplayObject#
* @default 'button'
*/
accessibleType: 'button',
/**
* Specify the pointer-events the accessible div will use
* Defaults to auto.
* @member {string}
* @memberof PIXI.DisplayObject#
* @default 'auto'
*/
accessiblePointerEvents: 'auto',
/**
* Setting to false will prevent any children inside this container to
* be accessible. Defaults to true.
* @member {boolean}
* @memberof PIXI.DisplayObject#
* @default true
*/
accessibleChildren: true,
renderId: -1,
};
// add some extra variables to the container..
display.DisplayObject.mixin(accessibleTarget);
var KEY_CODE_TAB = 9;
var DIV_TOUCH_SIZE = 100;
var DIV_TOUCH_POS_X = 0;
var DIV_TOUCH_POS_Y = 0;
var DIV_TOUCH_ZINDEX = 2;
var DIV_HOOK_SIZE = 1;
var DIV_HOOK_POS_X = -1000;
var DIV_HOOK_POS_Y = -1000;
var DIV_HOOK_ZINDEX = 2;
/**
* The Accessibility manager recreates the ability to tab and have content read by screen readers.
* This is very important as it can possibly help people with disabilities access PixiJS content.
*
* A DisplayObject can be made accessible just like it can be made interactive. This manager will map the
* events as if the mouse was being used, minimizing the effort required to implement.
*
* An instance of this class is automatically created by default, and can be found at `renderer.plugins.accessibility`
* @class
* @memberof PIXI
*/
var AccessibilityManager = /** @class */ (function () {
/**
* @param {PIXI.CanvasRenderer|PIXI.Renderer} renderer - A reference to the current renderer
*/
function AccessibilityManager(renderer) {
/** Setting this to true will visually show the divs. */
this.debug = false;
/** Internal variable, see isActive getter. */
this._isActive = false;
/** Internal variable, see isMobileAccessibility getter. */
this._isMobileAccessibility = false;
/** A simple pool for storing divs. */
this.pool = [];
/** This is a tick used to check if an object is no longer being rendered. */
this.renderId = 0;
/** The array of currently active accessible items. */
this.children = [];
/** Count to throttle div updates on android devices. */
this.androidUpdateCount = 0;
/** The frequency to update the div elements. */
this.androidUpdateFrequency = 500; // 2fps
this._hookDiv = null;
if (utils.isMobile.tablet || utils.isMobile.phone) {
this.createTouchHook();
}
// first we create a div that will sit over the PixiJS element. This is where the div overlays will go.
var div = document.createElement('div');
div.style.width = DIV_TOUCH_SIZE + "px";
div.style.height = DIV_TOUCH_SIZE + "px";
div.style.position = 'absolute';
div.style.top = DIV_TOUCH_POS_X + "px";
div.style.left = DIV_TOUCH_POS_Y + "px";
div.style.zIndex = DIV_TOUCH_ZINDEX.toString();
this.div = div;
this.renderer = renderer;
/**
* pre-bind the functions
* @type {Function}
* @private
*/
this._onKeyDown = this._onKeyDown.bind(this);
/**
* pre-bind the functions
* @type {Function}
* @private
*/
this._onMouseMove = this._onMouseMove.bind(this);
// let listen for tab.. once pressed we can fire up and show the accessibility layer
globalThis.addEventListener('keydown', this._onKeyDown, false);
}
Object.defineProperty(AccessibilityManager.prototype, "isActive", {
/**
* Value of `true` if accessibility is currently active and accessibility layers are showing.
* @member {boolean}
* @readonly
*/
get: function () {
return this._isActive;
},
enumerable: false,
configurable: true
});
Object.defineProperty(AccessibilityManager.prototype, "isMobileAccessibility", {
/**
* Value of `true` if accessibility is enabled for touch devices.
* @member {boolean}
* @readonly
*/
get: function () {
return this._isMobileAccessibility;
},
enumerable: false,
configurable: true
});
/**
* Creates the touch hooks.
* @private
*/
AccessibilityManager.prototype.createTouchHook = function () {
var _this = this;
var hookDiv = document.createElement('button');
hookDiv.style.width = DIV_HOOK_SIZE + "px";
hookDiv.style.height = DIV_HOOK_SIZE + "px";
hookDiv.style.position = 'absolute';
hookDiv.style.top = DIV_HOOK_POS_X + "px";
hookDiv.style.left = DIV_HOOK_POS_Y + "px";
hookDiv.style.zIndex = DIV_HOOK_ZINDEX.toString();
hookDiv.style.backgroundColor = '#FF0000';
hookDiv.title = 'select to enable accessibility for this content';
hookDiv.addEventListener('focus', function () {
_this._isMobileAccessibility = true;
_this.activate();
_this.destroyTouchHook();
});
document.body.appendChild(hookDiv);
this._hookDiv = hookDiv;
};
/**
* Destroys the touch hooks.
* @private
*/
AccessibilityManager.prototype.destroyTouchHook = function () {
if (!this._hookDiv) {
return;
}
document.body.removeChild(this._hookDiv);
this._hookDiv = null;
};
/**
* Activating will cause the Accessibility layer to be shown.
* This is called when a user presses the tab key.
* @private
*/
AccessibilityManager.prototype.activate = function () {
var _a;
if (this._isActive) {
return;
}
this._isActive = true;
globalThis.document.addEventListener('mousemove', this._onMouseMove, true);
globalThis.removeEventListener('keydown', this._onKeyDown, false);
this.renderer.on('postrender', this.update, this);
(_a = this.renderer.view.parentNode) === null || _a === void 0 ? void 0 : _a.appendChild(this.div);
};
/**
* Deactivating will cause the Accessibility layer to be hidden.
* This is called when a user moves the mouse.
* @private
*/
AccessibilityManager.prototype.deactivate = function () {
var _a;
if (!this._isActive || this._isMobileAccessibility) {
return;
}
this._isActive = false;
globalThis.document.removeEventListener('mousemove', this._onMouseMove, true);
globalThis.addEventListener('keydown', this._onKeyDown, false);
this.renderer.off('postrender', this.update);
(_a = this.div.parentNode) === null || _a === void 0 ? void 0 : _a.removeChild(this.div);
};
/**
* This recursive function will run through the scene graph and add any new accessible objects to the DOM layer.
* @private
* @param {PIXI.Container} displayObject - The DisplayObject to check.
*/
AccessibilityManager.prototype.updateAccessibleObjects = function (displayObject) {
if (!displayObject.visible || !displayObject.accessibleChildren) {
return;
}
if (displayObject.accessible && displayObject.interactive) {
if (!displayObject._accessibleActive) {
this.addChild(displayObject);
}
displayObject.renderId = this.renderId;
}
var children = displayObject.children;
if (children) {
for (var i = 0; i < children.length; i++) {
this.updateAccessibleObjects(children[i]);
}
}
};
/**
* Before each render this function will ensure that all divs are mapped correctly to their DisplayObjects.
* @private
*/
AccessibilityManager.prototype.update = function () {
/* On Android default web browser, tab order seems to be calculated by position rather than tabIndex,
* moving buttons can cause focus to flicker between two buttons making it hard/impossible to navigate,
* so I am just running update every half a second, seems to fix it.
*/
var now = performance.now();
if (utils.isMobile.android.device && now < this.androidUpdateCount) {
return;
}
this.androidUpdateCount = now + this.androidUpdateFrequency;
if (!this.renderer.renderingToScreen) {
return;
}
// update children...
if (this.renderer._lastObjectRendered) {
this.updateAccessibleObjects(this.renderer._lastObjectRendered);
}
var _a = this.renderer.view.getBoundingClientRect(), left = _a.left, top = _a.top, width = _a.width, height = _a.height;
var _b = this.renderer, viewWidth = _b.width, viewHeight = _b.height, resolution = _b.resolution;
var sx = (width / viewWidth) * resolution;
var sy = (height / viewHeight) * resolution;
var div = this.div;
div.style.left = left + "px";
div.style.top = top + "px";
div.style.width = viewWidth + "px";
div.style.height = viewHeight + "px";
for (var i = 0; i < this.children.length; i++) {
var child = this.children[i];
if (child.renderId !== this.renderId) {
child._accessibleActive = false;
utils.removeItems(this.children, i, 1);
this.div.removeChild(child._accessibleDiv);
this.pool.push(child._accessibleDiv);
child._accessibleDiv = null;
i--;
}
else {
// map div to display..
div = child._accessibleDiv;
var hitArea = child.hitArea;
var wt = child.worldTransform;
if (child.hitArea) {
div.style.left = (wt.tx + (hitArea.x * wt.a)) * sx + "px";
div.style.top = (wt.ty + (hitArea.y * wt.d)) * sy + "px";
div.style.width = hitArea.width * wt.a * sx + "px";
div.style.height = hitArea.height * wt.d * sy + "px";
}
else {
hitArea = child.getBounds();
this.capHitArea(hitArea);
div.style.left = hitArea.x * sx + "px";
div.style.top = hitArea.y * sy + "px";
div.style.width = hitArea.width * sx + "px";
div.style.height = hitArea.height * sy + "px";
// update button titles and hints if they exist and they've changed
if (div.title !== child.accessibleTitle && child.accessibleTitle !== null) {
div.title = child.accessibleTitle;
}
if (div.getAttribute('aria-label') !== child.accessibleHint
&& child.accessibleHint !== null) {
div.setAttribute('aria-label', child.accessibleHint);
}
}
// the title or index may have changed, if so lets update it!
if (child.accessibleTitle !== div.title || child.tabIndex !== div.tabIndex) {
div.title = child.accessibleTitle;
div.tabIndex = child.tabIndex;
if (this.debug)
{ this.updateDebugHTML(div); }
}
}
}
// increment the render id..
this.renderId++;
};
/**
* private function that will visually add the information to the
* accessability div
* @param {HTMLElement} div -
*/
AccessibilityManager.prototype.updateDebugHTML = function (div) {
div.innerHTML = "type: " + div.type + "</br> title : " + div.title + "</br> tabIndex: " + div.tabIndex;
};
/**
* Adjust the hit area based on the bounds of a display object
* @param {PIXI.Rectangle} hitArea - Bounds of the child
*/
AccessibilityManager.prototype.capHitArea = function (hitArea) {
if (hitArea.x < 0) {
hitArea.width += hitArea.x;
hitArea.x = 0;
}
if (hitArea.y < 0) {
hitArea.height += hitArea.y;
hitArea.y = 0;
}
var _a = this.renderer, viewWidth = _a.width, viewHeight = _a.height;
if (hitArea.x + hitArea.width > viewWidth) {
hitArea.width = viewWidth - hitArea.x;
}
if (hitArea.y + hitArea.height > viewHeight) {
hitArea.height = viewHeight - hitArea.y;
}
};
/**
* Adds a DisplayObject to the accessibility manager
* @private
* @param {PIXI.DisplayObject} displayObject - The child to make accessible.
*/
AccessibilityManager.prototype.addChild = function (displayObject) {
// this.activate();
var div = this.pool.pop();
if (!div) {
div = document.createElement('button');
div.style.width = DIV_TOUCH_SIZE + "px";
div.style.height = DIV_TOUCH_SIZE + "px";
div.style.backgroundColor = this.debug ? 'rgba(255,255,255,0.5)' : 'transparent';
div.style.position = 'absolute';
div.style.zIndex = DIV_TOUCH_ZINDEX.toString();
div.style.borderStyle = 'none';
// ARIA attributes ensure that button title and hint updates are announced properly
if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) {
// Chrome doesn't need aria-live to work as intended; in fact it just gets more confused.
div.setAttribute('aria-live', 'off');
}
else {
div.setAttribute('aria-live', 'polite');
}
if (navigator.userAgent.match(/rv:.*Gecko\//)) {
// FireFox needs this to announce only the new button name
div.setAttribute('aria-relevant', 'additions');
}
else {
// required by IE, other browsers don't much care
div.setAttribute('aria-relevant', 'text');
}
div.addEventListener('click', this._onClick.bind(this));
div.addEventListener('focus', this._onFocus.bind(this));
div.addEventListener('focusout', this._onFocusOut.bind(this));
}
// set pointer events
div.style.pointerEvents = displayObject.accessiblePointerEvents;
// set the type, this defaults to button!
div.type = displayObject.accessibleType;
if (displayObject.accessibleTitle && displayObject.accessibleTitle !== null) {
div.title = displayObject.accessibleTitle;
}
else if (!displayObject.accessibleHint
|| displayObject.accessibleHint === null) {
div.title = "displayObject " + displayObject.tabIndex;
}
if (displayObject.accessibleHint
&& displayObject.accessibleHint !== null) {
div.setAttribute('aria-label', displayObject.accessibleHint);
}
if (this.debug)
{ this.updateDebugHTML(div); }
displayObject._accessibleActive = true;
displayObject._accessibleDiv = div;
div.displayObject = displayObject;
this.children.push(displayObject);
this.div.appendChild(displayObject._accessibleDiv);
displayObject._accessibleDiv.tabIndex = displayObject.tabIndex;
};
/**
* Maps the div button press to pixi's InteractionManager (click)
* @private
* @param {MouseEvent} e - The click event.
*/
AccessibilityManager.prototype._onClick = function (e) {
var interactionManager = this.renderer.plugins.interaction;
var displayObject = e.target.displayObject;
var eventData = interactionManager.eventData;
interactionManager.dispatchEvent(displayObject, 'click', eventData);
interactionManager.dispatchEvent(displayObject, 'pointertap', eventData);
interactionManager.dispatchEvent(displayObject, 'tap', eventData);
};
/**
* Maps the div focus events to pixi's InteractionManager (mouseover)
* @private
* @param {FocusEvent} e - The focus event.
*/
AccessibilityManager.prototype._onFocus = function (e) {
if (!e.target.getAttribute('aria-live')) {
e.target.setAttribute('aria-live', 'assertive');
}
var interactionManager = this.renderer.plugins.interaction;
var displayObject = e.target.displayObject;
var eventData = interactionManager.eventData;
interactionManager.dispatchEvent(displayObject, 'mouseover', eventData);
};
/**
* Maps the div focus events to pixi's InteractionManager (mouseout)
* @private
* @param {FocusEvent} e - The focusout event.
*/
AccessibilityManager.prototype._onFocusOut = function (e) {
if (!e.target.getAttribute('aria-live')) {
e.target.setAttribute('aria-live', 'polite');
}
var interactionManager = this.renderer.plugins.interaction;
var displayObject = e.target.displayObject;
var eventData = interactionManager.eventData;
interactionManager.dispatchEvent(displayObject, 'mouseout', eventData);
};
/**
* Is called when a key is pressed
* @private
* @param {KeyboardEvent} e - The keydown event.
*/
AccessibilityManager.prototype._onKeyDown = function (e) {
if (e.keyCode !== KEY_CODE_TAB) {
return;
}
this.activate();
};
/**
* Is called when the mouse moves across the renderer element
* @private
* @param {MouseEvent} e - The mouse event.
*/
AccessibilityManager.prototype._onMouseMove = function (e) {
if (e.movementX === 0 && e.movementY === 0) {
return;
}
this.deactivate();
};
/** Destroys the accessibility manager */
AccessibilityManager.prototype.destroy = function () {
this.destroyTouchHook();
this.div = null;
globalThis.document.removeEventListener('mousemove', this._onMouseMove, true);
globalThis.removeEventListener('keydown', this._onKeyDown);
this.pool = null;
this.children = null;
this.renderer = null;
};
/** @ignore */
AccessibilityManager.extension = {
name: 'accessibility',
type: [
core.ExtensionType.RendererPlugin,
core.ExtensionType.CanvasRendererPlugin ],
};
return AccessibilityManager;
}());
exports.AccessibilityManager = AccessibilityManager;
exports.accessibleTarget = accessibleTarget;
Object.defineProperty(exports, '__esModule', { value: true });
return exports;
})({}, PIXI, PIXI.utils, PIXI);
Object.assign(this.PIXI, _pixi_accessibility);
//# sourceMappingURL=accessibility.js.map

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,535 @@
/*!
* @pixi/accessibility - v6.5.10
* Compiled Thu, 06 Jul 2023 15:25:11 UTC
*
* @pixi/accessibility is licensed under the MIT License.
* http://www.opensource.org/licenses/mit-license
*/
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var display = require('@pixi/display');
var utils = require('@pixi/utils');
var core = require('@pixi/core');
/**
* Default property values of accessible objects
* used by {@link PIXI.AccessibilityManager}.
* @private
* @function accessibleTarget
* @memberof PIXI
* @type {object}
* @example
* function MyObject() {}
*
* Object.assign(
* MyObject.prototype,
* PIXI.accessibleTarget
* );
*/
var accessibleTarget = {
/**
* Flag for if the object is accessible. If true AccessibilityManager will overlay a
* shadow div with attributes set
* @member {boolean}
* @memberof PIXI.DisplayObject#
*/
accessible: false,
/**
* Sets the title attribute of the shadow div
* If accessibleTitle AND accessibleHint has not been this will default to 'displayObject [tabIndex]'
* @member {?string}
* @memberof PIXI.DisplayObject#
*/
accessibleTitle: null,
/**
* Sets the aria-label attribute of the shadow div
* @member {string}
* @memberof PIXI.DisplayObject#
*/
accessibleHint: null,
/**
* @member {number}
* @memberof PIXI.DisplayObject#
* @private
* @todo Needs docs.
*/
tabIndex: 0,
/**
* @member {boolean}
* @memberof PIXI.DisplayObject#
* @todo Needs docs.
*/
_accessibleActive: false,
/**
* @member {boolean}
* @memberof PIXI.DisplayObject#
* @todo Needs docs.
*/
_accessibleDiv: null,
/**
* Specify the type of div the accessible layer is. Screen readers treat the element differently
* depending on this type. Defaults to button.
* @member {string}
* @memberof PIXI.DisplayObject#
* @default 'button'
*/
accessibleType: 'button',
/**
* Specify the pointer-events the accessible div will use
* Defaults to auto.
* @member {string}
* @memberof PIXI.DisplayObject#
* @default 'auto'
*/
accessiblePointerEvents: 'auto',
/**
* Setting to false will prevent any children inside this container to
* be accessible. Defaults to true.
* @member {boolean}
* @memberof PIXI.DisplayObject#
* @default true
*/
accessibleChildren: true,
renderId: -1,
};
// add some extra variables to the container..
display.DisplayObject.mixin(accessibleTarget);
var KEY_CODE_TAB = 9;
var DIV_TOUCH_SIZE = 100;
var DIV_TOUCH_POS_X = 0;
var DIV_TOUCH_POS_Y = 0;
var DIV_TOUCH_ZINDEX = 2;
var DIV_HOOK_SIZE = 1;
var DIV_HOOK_POS_X = -1000;
var DIV_HOOK_POS_Y = -1000;
var DIV_HOOK_ZINDEX = 2;
/**
* The Accessibility manager recreates the ability to tab and have content read by screen readers.
* This is very important as it can possibly help people with disabilities access PixiJS content.
*
* A DisplayObject can be made accessible just like it can be made interactive. This manager will map the
* events as if the mouse was being used, minimizing the effort required to implement.
*
* An instance of this class is automatically created by default, and can be found at `renderer.plugins.accessibility`
* @class
* @memberof PIXI
*/
var AccessibilityManager = /** @class */ (function () {
/**
* @param {PIXI.CanvasRenderer|PIXI.Renderer} renderer - A reference to the current renderer
*/
function AccessibilityManager(renderer) {
/** Setting this to true will visually show the divs. */
this.debug = false;
/** Internal variable, see isActive getter. */
this._isActive = false;
/** Internal variable, see isMobileAccessibility getter. */
this._isMobileAccessibility = false;
/** A simple pool for storing divs. */
this.pool = [];
/** This is a tick used to check if an object is no longer being rendered. */
this.renderId = 0;
/** The array of currently active accessible items. */
this.children = [];
/** Count to throttle div updates on android devices. */
this.androidUpdateCount = 0;
/** The frequency to update the div elements. */
this.androidUpdateFrequency = 500; // 2fps
this._hookDiv = null;
if (utils.isMobile.tablet || utils.isMobile.phone) {
this.createTouchHook();
}
// first we create a div that will sit over the PixiJS element. This is where the div overlays will go.
var div = document.createElement('div');
div.style.width = DIV_TOUCH_SIZE + "px";
div.style.height = DIV_TOUCH_SIZE + "px";
div.style.position = 'absolute';
div.style.top = DIV_TOUCH_POS_X + "px";
div.style.left = DIV_TOUCH_POS_Y + "px";
div.style.zIndex = DIV_TOUCH_ZINDEX.toString();
this.div = div;
this.renderer = renderer;
/**
* pre-bind the functions
* @type {Function}
* @private
*/
this._onKeyDown = this._onKeyDown.bind(this);
/**
* pre-bind the functions
* @type {Function}
* @private
*/
this._onMouseMove = this._onMouseMove.bind(this);
// let listen for tab.. once pressed we can fire up and show the accessibility layer
globalThis.addEventListener('keydown', this._onKeyDown, false);
}
Object.defineProperty(AccessibilityManager.prototype, "isActive", {
/**
* Value of `true` if accessibility is currently active and accessibility layers are showing.
* @member {boolean}
* @readonly
*/
get: function () {
return this._isActive;
},
enumerable: false,
configurable: true
});
Object.defineProperty(AccessibilityManager.prototype, "isMobileAccessibility", {
/**
* Value of `true` if accessibility is enabled for touch devices.
* @member {boolean}
* @readonly
*/
get: function () {
return this._isMobileAccessibility;
},
enumerable: false,
configurable: true
});
/**
* Creates the touch hooks.
* @private
*/
AccessibilityManager.prototype.createTouchHook = function () {
var _this = this;
var hookDiv = document.createElement('button');
hookDiv.style.width = DIV_HOOK_SIZE + "px";
hookDiv.style.height = DIV_HOOK_SIZE + "px";
hookDiv.style.position = 'absolute';
hookDiv.style.top = DIV_HOOK_POS_X + "px";
hookDiv.style.left = DIV_HOOK_POS_Y + "px";
hookDiv.style.zIndex = DIV_HOOK_ZINDEX.toString();
hookDiv.style.backgroundColor = '#FF0000';
hookDiv.title = 'select to enable accessibility for this content';
hookDiv.addEventListener('focus', function () {
_this._isMobileAccessibility = true;
_this.activate();
_this.destroyTouchHook();
});
document.body.appendChild(hookDiv);
this._hookDiv = hookDiv;
};
/**
* Destroys the touch hooks.
* @private
*/
AccessibilityManager.prototype.destroyTouchHook = function () {
if (!this._hookDiv) {
return;
}
document.body.removeChild(this._hookDiv);
this._hookDiv = null;
};
/**
* Activating will cause the Accessibility layer to be shown.
* This is called when a user presses the tab key.
* @private
*/
AccessibilityManager.prototype.activate = function () {
var _a;
if (this._isActive) {
return;
}
this._isActive = true;
globalThis.document.addEventListener('mousemove', this._onMouseMove, true);
globalThis.removeEventListener('keydown', this._onKeyDown, false);
this.renderer.on('postrender', this.update, this);
(_a = this.renderer.view.parentNode) === null || _a === void 0 ? void 0 : _a.appendChild(this.div);
};
/**
* Deactivating will cause the Accessibility layer to be hidden.
* This is called when a user moves the mouse.
* @private
*/
AccessibilityManager.prototype.deactivate = function () {
var _a;
if (!this._isActive || this._isMobileAccessibility) {
return;
}
this._isActive = false;
globalThis.document.removeEventListener('mousemove', this._onMouseMove, true);
globalThis.addEventListener('keydown', this._onKeyDown, false);
this.renderer.off('postrender', this.update);
(_a = this.div.parentNode) === null || _a === void 0 ? void 0 : _a.removeChild(this.div);
};
/**
* This recursive function will run through the scene graph and add any new accessible objects to the DOM layer.
* @private
* @param {PIXI.Container} displayObject - The DisplayObject to check.
*/
AccessibilityManager.prototype.updateAccessibleObjects = function (displayObject) {
if (!displayObject.visible || !displayObject.accessibleChildren) {
return;
}
if (displayObject.accessible && displayObject.interactive) {
if (!displayObject._accessibleActive) {
this.addChild(displayObject);
}
displayObject.renderId = this.renderId;
}
var children = displayObject.children;
if (children) {
for (var i = 0; i < children.length; i++) {
this.updateAccessibleObjects(children[i]);
}
}
};
/**
* Before each render this function will ensure that all divs are mapped correctly to their DisplayObjects.
* @private
*/
AccessibilityManager.prototype.update = function () {
/* On Android default web browser, tab order seems to be calculated by position rather than tabIndex,
* moving buttons can cause focus to flicker between two buttons making it hard/impossible to navigate,
* so I am just running update every half a second, seems to fix it.
*/
var now = performance.now();
if (utils.isMobile.android.device && now < this.androidUpdateCount) {
return;
}
this.androidUpdateCount = now + this.androidUpdateFrequency;
if (!this.renderer.renderingToScreen) {
return;
}
// update children...
if (this.renderer._lastObjectRendered) {
this.updateAccessibleObjects(this.renderer._lastObjectRendered);
}
var _a = this.renderer.view.getBoundingClientRect(), left = _a.left, top = _a.top, width = _a.width, height = _a.height;
var _b = this.renderer, viewWidth = _b.width, viewHeight = _b.height, resolution = _b.resolution;
var sx = (width / viewWidth) * resolution;
var sy = (height / viewHeight) * resolution;
var div = this.div;
div.style.left = left + "px";
div.style.top = top + "px";
div.style.width = viewWidth + "px";
div.style.height = viewHeight + "px";
for (var i = 0; i < this.children.length; i++) {
var child = this.children[i];
if (child.renderId !== this.renderId) {
child._accessibleActive = false;
utils.removeItems(this.children, i, 1);
this.div.removeChild(child._accessibleDiv);
this.pool.push(child._accessibleDiv);
child._accessibleDiv = null;
i--;
}
else {
// map div to display..
div = child._accessibleDiv;
var hitArea = child.hitArea;
var wt = child.worldTransform;
if (child.hitArea) {
div.style.left = (wt.tx + (hitArea.x * wt.a)) * sx + "px";
div.style.top = (wt.ty + (hitArea.y * wt.d)) * sy + "px";
div.style.width = hitArea.width * wt.a * sx + "px";
div.style.height = hitArea.height * wt.d * sy + "px";
}
else {
hitArea = child.getBounds();
this.capHitArea(hitArea);
div.style.left = hitArea.x * sx + "px";
div.style.top = hitArea.y * sy + "px";
div.style.width = hitArea.width * sx + "px";
div.style.height = hitArea.height * sy + "px";
// update button titles and hints if they exist and they've changed
if (div.title !== child.accessibleTitle && child.accessibleTitle !== null) {
div.title = child.accessibleTitle;
}
if (div.getAttribute('aria-label') !== child.accessibleHint
&& child.accessibleHint !== null) {
div.setAttribute('aria-label', child.accessibleHint);
}
}
// the title or index may have changed, if so lets update it!
if (child.accessibleTitle !== div.title || child.tabIndex !== div.tabIndex) {
div.title = child.accessibleTitle;
div.tabIndex = child.tabIndex;
if (this.debug)
{ this.updateDebugHTML(div); }
}
}
}
// increment the render id..
this.renderId++;
};
/**
* private function that will visually add the information to the
* accessability div
* @param {HTMLElement} div -
*/
AccessibilityManager.prototype.updateDebugHTML = function (div) {
div.innerHTML = "type: " + div.type + "</br> title : " + div.title + "</br> tabIndex: " + div.tabIndex;
};
/**
* Adjust the hit area based on the bounds of a display object
* @param {PIXI.Rectangle} hitArea - Bounds of the child
*/
AccessibilityManager.prototype.capHitArea = function (hitArea) {
if (hitArea.x < 0) {
hitArea.width += hitArea.x;
hitArea.x = 0;
}
if (hitArea.y < 0) {
hitArea.height += hitArea.y;
hitArea.y = 0;
}
var _a = this.renderer, viewWidth = _a.width, viewHeight = _a.height;
if (hitArea.x + hitArea.width > viewWidth) {
hitArea.width = viewWidth - hitArea.x;
}
if (hitArea.y + hitArea.height > viewHeight) {
hitArea.height = viewHeight - hitArea.y;
}
};
/**
* Adds a DisplayObject to the accessibility manager
* @private
* @param {PIXI.DisplayObject} displayObject - The child to make accessible.
*/
AccessibilityManager.prototype.addChild = function (displayObject) {
// this.activate();
var div = this.pool.pop();
if (!div) {
div = document.createElement('button');
div.style.width = DIV_TOUCH_SIZE + "px";
div.style.height = DIV_TOUCH_SIZE + "px";
div.style.backgroundColor = this.debug ? 'rgba(255,255,255,0.5)' : 'transparent';
div.style.position = 'absolute';
div.style.zIndex = DIV_TOUCH_ZINDEX.toString();
div.style.borderStyle = 'none';
// ARIA attributes ensure that button title and hint updates are announced properly
if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) {
// Chrome doesn't need aria-live to work as intended; in fact it just gets more confused.
div.setAttribute('aria-live', 'off');
}
else {
div.setAttribute('aria-live', 'polite');
}
if (navigator.userAgent.match(/rv:.*Gecko\//)) {
// FireFox needs this to announce only the new button name
div.setAttribute('aria-relevant', 'additions');
}
else {
// required by IE, other browsers don't much care
div.setAttribute('aria-relevant', 'text');
}
div.addEventListener('click', this._onClick.bind(this));
div.addEventListener('focus', this._onFocus.bind(this));
div.addEventListener('focusout', this._onFocusOut.bind(this));
}
// set pointer events
div.style.pointerEvents = displayObject.accessiblePointerEvents;
// set the type, this defaults to button!
div.type = displayObject.accessibleType;
if (displayObject.accessibleTitle && displayObject.accessibleTitle !== null) {
div.title = displayObject.accessibleTitle;
}
else if (!displayObject.accessibleHint
|| displayObject.accessibleHint === null) {
div.title = "displayObject " + displayObject.tabIndex;
}
if (displayObject.accessibleHint
&& displayObject.accessibleHint !== null) {
div.setAttribute('aria-label', displayObject.accessibleHint);
}
if (this.debug)
{ this.updateDebugHTML(div); }
displayObject._accessibleActive = true;
displayObject._accessibleDiv = div;
div.displayObject = displayObject;
this.children.push(displayObject);
this.div.appendChild(displayObject._accessibleDiv);
displayObject._accessibleDiv.tabIndex = displayObject.tabIndex;
};
/**
* Maps the div button press to pixi's InteractionManager (click)
* @private
* @param {MouseEvent} e - The click event.
*/
AccessibilityManager.prototype._onClick = function (e) {
var interactionManager = this.renderer.plugins.interaction;
var displayObject = e.target.displayObject;
var eventData = interactionManager.eventData;
interactionManager.dispatchEvent(displayObject, 'click', eventData);
interactionManager.dispatchEvent(displayObject, 'pointertap', eventData);
interactionManager.dispatchEvent(displayObject, 'tap', eventData);
};
/**
* Maps the div focus events to pixi's InteractionManager (mouseover)
* @private
* @param {FocusEvent} e - The focus event.
*/
AccessibilityManager.prototype._onFocus = function (e) {
if (!e.target.getAttribute('aria-live')) {
e.target.setAttribute('aria-live', 'assertive');
}
var interactionManager = this.renderer.plugins.interaction;
var displayObject = e.target.displayObject;
var eventData = interactionManager.eventData;
interactionManager.dispatchEvent(displayObject, 'mouseover', eventData);
};
/**
* Maps the div focus events to pixi's InteractionManager (mouseout)
* @private
* @param {FocusEvent} e - The focusout event.
*/
AccessibilityManager.prototype._onFocusOut = function (e) {
if (!e.target.getAttribute('aria-live')) {
e.target.setAttribute('aria-live', 'polite');
}
var interactionManager = this.renderer.plugins.interaction;
var displayObject = e.target.displayObject;
var eventData = interactionManager.eventData;
interactionManager.dispatchEvent(displayObject, 'mouseout', eventData);
};
/**
* Is called when a key is pressed
* @private
* @param {KeyboardEvent} e - The keydown event.
*/
AccessibilityManager.prototype._onKeyDown = function (e) {
if (e.keyCode !== KEY_CODE_TAB) {
return;
}
this.activate();
};
/**
* Is called when the mouse moves across the renderer element
* @private
* @param {MouseEvent} e - The mouse event.
*/
AccessibilityManager.prototype._onMouseMove = function (e) {
if (e.movementX === 0 && e.movementY === 0) {
return;
}
this.deactivate();
};
/** Destroys the accessibility manager */
AccessibilityManager.prototype.destroy = function () {
this.destroyTouchHook();
this.div = null;
globalThis.document.removeEventListener('mousemove', this._onMouseMove, true);
globalThis.removeEventListener('keydown', this._onKeyDown);
this.pool = null;
this.children = null;
this.renderer = null;
};
/** @ignore */
AccessibilityManager.extension = {
name: 'accessibility',
type: [
core.ExtensionType.RendererPlugin,
core.ExtensionType.CanvasRendererPlugin ],
};
return AccessibilityManager;
}());
exports.AccessibilityManager = AccessibilityManager;
exports.accessibleTarget = accessibleTarget;
//# sourceMappingURL=accessibility.js.map

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,530 @@
/*!
* @pixi/accessibility - v6.5.10
* Compiled Thu, 06 Jul 2023 15:25:11 UTC
*
* @pixi/accessibility is licensed under the MIT License.
* http://www.opensource.org/licenses/mit-license
*/
import { DisplayObject } from '@pixi/display';
import { isMobile, removeItems } from '@pixi/utils';
import { ExtensionType } from '@pixi/core';
/**
* Default property values of accessible objects
* used by {@link PIXI.AccessibilityManager}.
* @private
* @function accessibleTarget
* @memberof PIXI
* @type {object}
* @example
* function MyObject() {}
*
* Object.assign(
* MyObject.prototype,
* PIXI.accessibleTarget
* );
*/
var accessibleTarget = {
/**
* Flag for if the object is accessible. If true AccessibilityManager will overlay a
* shadow div with attributes set
* @member {boolean}
* @memberof PIXI.DisplayObject#
*/
accessible: false,
/**
* Sets the title attribute of the shadow div
* If accessibleTitle AND accessibleHint has not been this will default to 'displayObject [tabIndex]'
* @member {?string}
* @memberof PIXI.DisplayObject#
*/
accessibleTitle: null,
/**
* Sets the aria-label attribute of the shadow div
* @member {string}
* @memberof PIXI.DisplayObject#
*/
accessibleHint: null,
/**
* @member {number}
* @memberof PIXI.DisplayObject#
* @private
* @todo Needs docs.
*/
tabIndex: 0,
/**
* @member {boolean}
* @memberof PIXI.DisplayObject#
* @todo Needs docs.
*/
_accessibleActive: false,
/**
* @member {boolean}
* @memberof PIXI.DisplayObject#
* @todo Needs docs.
*/
_accessibleDiv: null,
/**
* Specify the type of div the accessible layer is. Screen readers treat the element differently
* depending on this type. Defaults to button.
* @member {string}
* @memberof PIXI.DisplayObject#
* @default 'button'
*/
accessibleType: 'button',
/**
* Specify the pointer-events the accessible div will use
* Defaults to auto.
* @member {string}
* @memberof PIXI.DisplayObject#
* @default 'auto'
*/
accessiblePointerEvents: 'auto',
/**
* Setting to false will prevent any children inside this container to
* be accessible. Defaults to true.
* @member {boolean}
* @memberof PIXI.DisplayObject#
* @default true
*/
accessibleChildren: true,
renderId: -1,
};
// add some extra variables to the container..
DisplayObject.mixin(accessibleTarget);
var KEY_CODE_TAB = 9;
var DIV_TOUCH_SIZE = 100;
var DIV_TOUCH_POS_X = 0;
var DIV_TOUCH_POS_Y = 0;
var DIV_TOUCH_ZINDEX = 2;
var DIV_HOOK_SIZE = 1;
var DIV_HOOK_POS_X = -1000;
var DIV_HOOK_POS_Y = -1000;
var DIV_HOOK_ZINDEX = 2;
/**
* The Accessibility manager recreates the ability to tab and have content read by screen readers.
* This is very important as it can possibly help people with disabilities access PixiJS content.
*
* A DisplayObject can be made accessible just like it can be made interactive. This manager will map the
* events as if the mouse was being used, minimizing the effort required to implement.
*
* An instance of this class is automatically created by default, and can be found at `renderer.plugins.accessibility`
* @class
* @memberof PIXI
*/
var AccessibilityManager = /** @class */ (function () {
/**
* @param {PIXI.CanvasRenderer|PIXI.Renderer} renderer - A reference to the current renderer
*/
function AccessibilityManager(renderer) {
/** Setting this to true will visually show the divs. */
this.debug = false;
/** Internal variable, see isActive getter. */
this._isActive = false;
/** Internal variable, see isMobileAccessibility getter. */
this._isMobileAccessibility = false;
/** A simple pool for storing divs. */
this.pool = [];
/** This is a tick used to check if an object is no longer being rendered. */
this.renderId = 0;
/** The array of currently active accessible items. */
this.children = [];
/** Count to throttle div updates on android devices. */
this.androidUpdateCount = 0;
/** The frequency to update the div elements. */
this.androidUpdateFrequency = 500; // 2fps
this._hookDiv = null;
if (isMobile.tablet || isMobile.phone) {
this.createTouchHook();
}
// first we create a div that will sit over the PixiJS element. This is where the div overlays will go.
var div = document.createElement('div');
div.style.width = DIV_TOUCH_SIZE + "px";
div.style.height = DIV_TOUCH_SIZE + "px";
div.style.position = 'absolute';
div.style.top = DIV_TOUCH_POS_X + "px";
div.style.left = DIV_TOUCH_POS_Y + "px";
div.style.zIndex = DIV_TOUCH_ZINDEX.toString();
this.div = div;
this.renderer = renderer;
/**
* pre-bind the functions
* @type {Function}
* @private
*/
this._onKeyDown = this._onKeyDown.bind(this);
/**
* pre-bind the functions
* @type {Function}
* @private
*/
this._onMouseMove = this._onMouseMove.bind(this);
// let listen for tab.. once pressed we can fire up and show the accessibility layer
globalThis.addEventListener('keydown', this._onKeyDown, false);
}
Object.defineProperty(AccessibilityManager.prototype, "isActive", {
/**
* Value of `true` if accessibility is currently active and accessibility layers are showing.
* @member {boolean}
* @readonly
*/
get: function () {
return this._isActive;
},
enumerable: false,
configurable: true
});
Object.defineProperty(AccessibilityManager.prototype, "isMobileAccessibility", {
/**
* Value of `true` if accessibility is enabled for touch devices.
* @member {boolean}
* @readonly
*/
get: function () {
return this._isMobileAccessibility;
},
enumerable: false,
configurable: true
});
/**
* Creates the touch hooks.
* @private
*/
AccessibilityManager.prototype.createTouchHook = function () {
var _this = this;
var hookDiv = document.createElement('button');
hookDiv.style.width = DIV_HOOK_SIZE + "px";
hookDiv.style.height = DIV_HOOK_SIZE + "px";
hookDiv.style.position = 'absolute';
hookDiv.style.top = DIV_HOOK_POS_X + "px";
hookDiv.style.left = DIV_HOOK_POS_Y + "px";
hookDiv.style.zIndex = DIV_HOOK_ZINDEX.toString();
hookDiv.style.backgroundColor = '#FF0000';
hookDiv.title = 'select to enable accessibility for this content';
hookDiv.addEventListener('focus', function () {
_this._isMobileAccessibility = true;
_this.activate();
_this.destroyTouchHook();
});
document.body.appendChild(hookDiv);
this._hookDiv = hookDiv;
};
/**
* Destroys the touch hooks.
* @private
*/
AccessibilityManager.prototype.destroyTouchHook = function () {
if (!this._hookDiv) {
return;
}
document.body.removeChild(this._hookDiv);
this._hookDiv = null;
};
/**
* Activating will cause the Accessibility layer to be shown.
* This is called when a user presses the tab key.
* @private
*/
AccessibilityManager.prototype.activate = function () {
var _a;
if (this._isActive) {
return;
}
this._isActive = true;
globalThis.document.addEventListener('mousemove', this._onMouseMove, true);
globalThis.removeEventListener('keydown', this._onKeyDown, false);
this.renderer.on('postrender', this.update, this);
(_a = this.renderer.view.parentNode) === null || _a === void 0 ? void 0 : _a.appendChild(this.div);
};
/**
* Deactivating will cause the Accessibility layer to be hidden.
* This is called when a user moves the mouse.
* @private
*/
AccessibilityManager.prototype.deactivate = function () {
var _a;
if (!this._isActive || this._isMobileAccessibility) {
return;
}
this._isActive = false;
globalThis.document.removeEventListener('mousemove', this._onMouseMove, true);
globalThis.addEventListener('keydown', this._onKeyDown, false);
this.renderer.off('postrender', this.update);
(_a = this.div.parentNode) === null || _a === void 0 ? void 0 : _a.removeChild(this.div);
};
/**
* This recursive function will run through the scene graph and add any new accessible objects to the DOM layer.
* @private
* @param {PIXI.Container} displayObject - The DisplayObject to check.
*/
AccessibilityManager.prototype.updateAccessibleObjects = function (displayObject) {
if (!displayObject.visible || !displayObject.accessibleChildren) {
return;
}
if (displayObject.accessible && displayObject.interactive) {
if (!displayObject._accessibleActive) {
this.addChild(displayObject);
}
displayObject.renderId = this.renderId;
}
var children = displayObject.children;
if (children) {
for (var i = 0; i < children.length; i++) {
this.updateAccessibleObjects(children[i]);
}
}
};
/**
* Before each render this function will ensure that all divs are mapped correctly to their DisplayObjects.
* @private
*/
AccessibilityManager.prototype.update = function () {
/* On Android default web browser, tab order seems to be calculated by position rather than tabIndex,
* moving buttons can cause focus to flicker between two buttons making it hard/impossible to navigate,
* so I am just running update every half a second, seems to fix it.
*/
var now = performance.now();
if (isMobile.android.device && now < this.androidUpdateCount) {
return;
}
this.androidUpdateCount = now + this.androidUpdateFrequency;
if (!this.renderer.renderingToScreen) {
return;
}
// update children...
if (this.renderer._lastObjectRendered) {
this.updateAccessibleObjects(this.renderer._lastObjectRendered);
}
var _a = this.renderer.view.getBoundingClientRect(), left = _a.left, top = _a.top, width = _a.width, height = _a.height;
var _b = this.renderer, viewWidth = _b.width, viewHeight = _b.height, resolution = _b.resolution;
var sx = (width / viewWidth) * resolution;
var sy = (height / viewHeight) * resolution;
var div = this.div;
div.style.left = left + "px";
div.style.top = top + "px";
div.style.width = viewWidth + "px";
div.style.height = viewHeight + "px";
for (var i = 0; i < this.children.length; i++) {
var child = this.children[i];
if (child.renderId !== this.renderId) {
child._accessibleActive = false;
removeItems(this.children, i, 1);
this.div.removeChild(child._accessibleDiv);
this.pool.push(child._accessibleDiv);
child._accessibleDiv = null;
i--;
}
else {
// map div to display..
div = child._accessibleDiv;
var hitArea = child.hitArea;
var wt = child.worldTransform;
if (child.hitArea) {
div.style.left = (wt.tx + (hitArea.x * wt.a)) * sx + "px";
div.style.top = (wt.ty + (hitArea.y * wt.d)) * sy + "px";
div.style.width = hitArea.width * wt.a * sx + "px";
div.style.height = hitArea.height * wt.d * sy + "px";
}
else {
hitArea = child.getBounds();
this.capHitArea(hitArea);
div.style.left = hitArea.x * sx + "px";
div.style.top = hitArea.y * sy + "px";
div.style.width = hitArea.width * sx + "px";
div.style.height = hitArea.height * sy + "px";
// update button titles and hints if they exist and they've changed
if (div.title !== child.accessibleTitle && child.accessibleTitle !== null) {
div.title = child.accessibleTitle;
}
if (div.getAttribute('aria-label') !== child.accessibleHint
&& child.accessibleHint !== null) {
div.setAttribute('aria-label', child.accessibleHint);
}
}
// the title or index may have changed, if so lets update it!
if (child.accessibleTitle !== div.title || child.tabIndex !== div.tabIndex) {
div.title = child.accessibleTitle;
div.tabIndex = child.tabIndex;
if (this.debug)
{ this.updateDebugHTML(div); }
}
}
}
// increment the render id..
this.renderId++;
};
/**
* private function that will visually add the information to the
* accessability div
* @param {HTMLElement} div -
*/
AccessibilityManager.prototype.updateDebugHTML = function (div) {
div.innerHTML = "type: " + div.type + "</br> title : " + div.title + "</br> tabIndex: " + div.tabIndex;
};
/**
* Adjust the hit area based on the bounds of a display object
* @param {PIXI.Rectangle} hitArea - Bounds of the child
*/
AccessibilityManager.prototype.capHitArea = function (hitArea) {
if (hitArea.x < 0) {
hitArea.width += hitArea.x;
hitArea.x = 0;
}
if (hitArea.y < 0) {
hitArea.height += hitArea.y;
hitArea.y = 0;
}
var _a = this.renderer, viewWidth = _a.width, viewHeight = _a.height;
if (hitArea.x + hitArea.width > viewWidth) {
hitArea.width = viewWidth - hitArea.x;
}
if (hitArea.y + hitArea.height > viewHeight) {
hitArea.height = viewHeight - hitArea.y;
}
};
/**
* Adds a DisplayObject to the accessibility manager
* @private
* @param {PIXI.DisplayObject} displayObject - The child to make accessible.
*/
AccessibilityManager.prototype.addChild = function (displayObject) {
// this.activate();
var div = this.pool.pop();
if (!div) {
div = document.createElement('button');
div.style.width = DIV_TOUCH_SIZE + "px";
div.style.height = DIV_TOUCH_SIZE + "px";
div.style.backgroundColor = this.debug ? 'rgba(255,255,255,0.5)' : 'transparent';
div.style.position = 'absolute';
div.style.zIndex = DIV_TOUCH_ZINDEX.toString();
div.style.borderStyle = 'none';
// ARIA attributes ensure that button title and hint updates are announced properly
if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) {
// Chrome doesn't need aria-live to work as intended; in fact it just gets more confused.
div.setAttribute('aria-live', 'off');
}
else {
div.setAttribute('aria-live', 'polite');
}
if (navigator.userAgent.match(/rv:.*Gecko\//)) {
// FireFox needs this to announce only the new button name
div.setAttribute('aria-relevant', 'additions');
}
else {
// required by IE, other browsers don't much care
div.setAttribute('aria-relevant', 'text');
}
div.addEventListener('click', this._onClick.bind(this));
div.addEventListener('focus', this._onFocus.bind(this));
div.addEventListener('focusout', this._onFocusOut.bind(this));
}
// set pointer events
div.style.pointerEvents = displayObject.accessiblePointerEvents;
// set the type, this defaults to button!
div.type = displayObject.accessibleType;
if (displayObject.accessibleTitle && displayObject.accessibleTitle !== null) {
div.title = displayObject.accessibleTitle;
}
else if (!displayObject.accessibleHint
|| displayObject.accessibleHint === null) {
div.title = "displayObject " + displayObject.tabIndex;
}
if (displayObject.accessibleHint
&& displayObject.accessibleHint !== null) {
div.setAttribute('aria-label', displayObject.accessibleHint);
}
if (this.debug)
{ this.updateDebugHTML(div); }
displayObject._accessibleActive = true;
displayObject._accessibleDiv = div;
div.displayObject = displayObject;
this.children.push(displayObject);
this.div.appendChild(displayObject._accessibleDiv);
displayObject._accessibleDiv.tabIndex = displayObject.tabIndex;
};
/**
* Maps the div button press to pixi's InteractionManager (click)
* @private
* @param {MouseEvent} e - The click event.
*/
AccessibilityManager.prototype._onClick = function (e) {
var interactionManager = this.renderer.plugins.interaction;
var displayObject = e.target.displayObject;
var eventData = interactionManager.eventData;
interactionManager.dispatchEvent(displayObject, 'click', eventData);
interactionManager.dispatchEvent(displayObject, 'pointertap', eventData);
interactionManager.dispatchEvent(displayObject, 'tap', eventData);
};
/**
* Maps the div focus events to pixi's InteractionManager (mouseover)
* @private
* @param {FocusEvent} e - The focus event.
*/
AccessibilityManager.prototype._onFocus = function (e) {
if (!e.target.getAttribute('aria-live')) {
e.target.setAttribute('aria-live', 'assertive');
}
var interactionManager = this.renderer.plugins.interaction;
var displayObject = e.target.displayObject;
var eventData = interactionManager.eventData;
interactionManager.dispatchEvent(displayObject, 'mouseover', eventData);
};
/**
* Maps the div focus events to pixi's InteractionManager (mouseout)
* @private
* @param {FocusEvent} e - The focusout event.
*/
AccessibilityManager.prototype._onFocusOut = function (e) {
if (!e.target.getAttribute('aria-live')) {
e.target.setAttribute('aria-live', 'polite');
}
var interactionManager = this.renderer.plugins.interaction;
var displayObject = e.target.displayObject;
var eventData = interactionManager.eventData;
interactionManager.dispatchEvent(displayObject, 'mouseout', eventData);
};
/**
* Is called when a key is pressed
* @private
* @param {KeyboardEvent} e - The keydown event.
*/
AccessibilityManager.prototype._onKeyDown = function (e) {
if (e.keyCode !== KEY_CODE_TAB) {
return;
}
this.activate();
};
/**
* Is called when the mouse moves across the renderer element
* @private
* @param {MouseEvent} e - The mouse event.
*/
AccessibilityManager.prototype._onMouseMove = function (e) {
if (e.movementX === 0 && e.movementY === 0) {
return;
}
this.deactivate();
};
/** Destroys the accessibility manager */
AccessibilityManager.prototype.destroy = function () {
this.destroyTouchHook();
this.div = null;
globalThis.document.removeEventListener('mousemove', this._onMouseMove, true);
globalThis.removeEventListener('keydown', this._onKeyDown);
this.pool = null;
this.children = null;
this.renderer = null;
};
/** @ignore */
AccessibilityManager.extension = {
name: 'accessibility',
type: [
ExtensionType.RendererPlugin,
ExtensionType.CanvasRendererPlugin ],
};
return AccessibilityManager;
}());
export { AccessibilityManager, accessibleTarget };
//# sourceMappingURL=accessibility.mjs.map

File diff suppressed because one or more lines are too long

185
live2d/node_modules/@pixi/accessibility/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,185 @@
/// <reference path="./global.d.ts" />
import type { AbstractRenderer } from '@pixi/core';
import type { DisplayObject } from '@pixi/display';
import type { ExtensionMetadata } from '@pixi/core';
import type { Rectangle } from '@pixi/math';
import type { Renderer } from '@pixi/core';
/**
* The Accessibility manager recreates the ability to tab and have content read by screen readers.
* This is very important as it can possibly help people with disabilities access PixiJS content.
*
* A DisplayObject can be made accessible just like it can be made interactive. This manager will map the
* events as if the mouse was being used, minimizing the effort required to implement.
*
* An instance of this class is automatically created by default, and can be found at `renderer.plugins.accessibility`
* @class
* @memberof PIXI
*/
export declare class AccessibilityManager {
/** @ignore */
static extension: ExtensionMetadata;
/** Setting this to true will visually show the divs. */
debug: boolean;
/**
* The renderer this accessibility manager works for.
* @type {PIXI.CanvasRenderer|PIXI.Renderer}
*/
renderer: AbstractRenderer | Renderer;
/** Internal variable, see isActive getter. */
private _isActive;
/** Internal variable, see isMobileAccessibility getter. */
private _isMobileAccessibility;
/** Button element for handling touch hooks. */
private _hookDiv;
/** This is the dom element that will sit over the PixiJS element. This is where the div overlays will go. */
private div;
/** A simple pool for storing divs. */
private pool;
/** This is a tick used to check if an object is no longer being rendered. */
private renderId;
/** The array of currently active accessible items. */
private children;
/** Count to throttle div updates on android devices. */
private androidUpdateCount;
/** The frequency to update the div elements. */
private androidUpdateFrequency;
/**
* @param {PIXI.CanvasRenderer|PIXI.Renderer} renderer - A reference to the current renderer
*/
constructor(renderer: AbstractRenderer | Renderer);
/**
* Value of `true` if accessibility is currently active and accessibility layers are showing.
* @member {boolean}
* @readonly
*/
get isActive(): boolean;
/**
* Value of `true` if accessibility is enabled for touch devices.
* @member {boolean}
* @readonly
*/
get isMobileAccessibility(): boolean;
/**
* Creates the touch hooks.
* @private
*/
private createTouchHook;
/**
* Destroys the touch hooks.
* @private
*/
private destroyTouchHook;
/**
* Activating will cause the Accessibility layer to be shown.
* This is called when a user presses the tab key.
* @private
*/
private activate;
/**
* Deactivating will cause the Accessibility layer to be hidden.
* This is called when a user moves the mouse.
* @private
*/
private deactivate;
/**
* This recursive function will run through the scene graph and add any new accessible objects to the DOM layer.
* @private
* @param {PIXI.Container} displayObject - The DisplayObject to check.
*/
private updateAccessibleObjects;
/**
* Before each render this function will ensure that all divs are mapped correctly to their DisplayObjects.
* @private
*/
private update;
/**
* private function that will visually add the information to the
* accessability div
* @param {HTMLElement} div -
*/
updateDebugHTML(div: IAccessibleHTMLElement): void;
/**
* Adjust the hit area based on the bounds of a display object
* @param {PIXI.Rectangle} hitArea - Bounds of the child
*/
capHitArea(hitArea: Rectangle): void;
/**
* Adds a DisplayObject to the accessibility manager
* @private
* @param {PIXI.DisplayObject} displayObject - The child to make accessible.
*/
private addChild;
/**
* Maps the div button press to pixi's InteractionManager (click)
* @private
* @param {MouseEvent} e - The click event.
*/
private _onClick;
/**
* Maps the div focus events to pixi's InteractionManager (mouseover)
* @private
* @param {FocusEvent} e - The focus event.
*/
private _onFocus;
/**
* Maps the div focus events to pixi's InteractionManager (mouseout)
* @private
* @param {FocusEvent} e - The focusout event.
*/
private _onFocusOut;
/**
* Is called when a key is pressed
* @private
* @param {KeyboardEvent} e - The keydown event.
*/
private _onKeyDown;
/**
* Is called when the mouse moves across the renderer element
* @private
* @param {MouseEvent} e - The mouse event.
*/
private _onMouseMove;
/** Destroys the accessibility manager */
destroy(): void;
}
/**
* Default property values of accessible objects
* used by {@link PIXI.AccessibilityManager}.
* @private
* @function accessibleTarget
* @memberof PIXI
* @type {object}
* @example
* function MyObject() {}
*
* Object.assign(
* MyObject.prototype,
* PIXI.accessibleTarget
* );
*/
export declare const accessibleTarget: IAccessibleTarget;
export declare interface IAccessibleHTMLElement extends HTMLElement {
type?: string;
displayObject?: DisplayObject;
}
export declare interface IAccessibleTarget {
accessible: boolean;
accessibleTitle: string;
accessibleHint: string;
tabIndex: number;
_accessibleActive: boolean;
_accessibleDiv: IAccessibleHTMLElement;
accessibleType: string;
accessiblePointerEvents: PointerEvents;
accessibleChildren: boolean;
renderId: number;
}
export declare type PointerEvents = 'auto' | 'none' | 'visiblePainted' | 'visibleFill' | 'visibleStroke' | 'visible' | 'painted' | 'fill' | 'stroke' | 'all' | 'inherit';
export { }

View File

@@ -1,147 +0,0 @@
import type { ExtensionMetadata, IRenderer, Rectangle } from '@pixi/core';
import type { IAccessibleHTMLElement } from './accessibleTarget';
/**
* The Accessibility manager recreates the ability to tab and have content read by screen readers.
* This is very important as it can possibly help people with disabilities access PixiJS content.
*
* A DisplayObject can be made accessible just like it can be made interactive. This manager will map the
* events as if the mouse was being used, minimizing the effort required to implement.
*
* An instance of this class is automatically created by default, and can be found at `renderer.plugins.accessibility`
* @class
* @memberof PIXI
*/
export declare class AccessibilityManager {
/** @ignore */
static extension: ExtensionMetadata;
/** Setting this to true will visually show the divs. */
debug: boolean;
/**
* The renderer this accessibility manager works for.
* @type {PIXI.CanvasRenderer|PIXI.Renderer}
*/
renderer: IRenderer;
/** Internal variable, see isActive getter. */
private _isActive;
/** Internal variable, see isMobileAccessibility getter. */
private _isMobileAccessibility;
/** Button element for handling touch hooks. */
private _hookDiv;
/** This is the dom element that will sit over the PixiJS element. This is where the div overlays will go. */
private div;
/** A simple pool for storing divs. */
private pool;
/** This is a tick used to check if an object is no longer being rendered. */
private renderId;
/** The array of currently active accessible items. */
private children;
/** Count to throttle div updates on android devices. */
private androidUpdateCount;
/** The frequency to update the div elements. */
private androidUpdateFrequency;
/**
* @param {PIXI.CanvasRenderer|PIXI.Renderer} renderer - A reference to the current renderer
*/
constructor(renderer: IRenderer);
/**
* Value of `true` if accessibility is currently active and accessibility layers are showing.
* @member {boolean}
* @readonly
*/
get isActive(): boolean;
/**
* Value of `true` if accessibility is enabled for touch devices.
* @member {boolean}
* @readonly
*/
get isMobileAccessibility(): boolean;
/**
* Creates the touch hooks.
* @private
*/
private createTouchHook;
/**
* Destroys the touch hooks.
* @private
*/
private destroyTouchHook;
/**
* Activating will cause the Accessibility layer to be shown.
* This is called when a user presses the tab key.
* @private
*/
private activate;
/**
* Deactivating will cause the Accessibility layer to be hidden.
* This is called when a user moves the mouse.
* @private
*/
private deactivate;
/**
* This recursive function will run through the scene graph and add any new accessible objects to the DOM layer.
* @private
* @param {PIXI.Container} displayObject - The DisplayObject to check.
*/
private updateAccessibleObjects;
/**
* Before each render this function will ensure that all divs are mapped correctly to their DisplayObjects.
* @private
*/
private update;
/**
* private function that will visually add the information to the
* accessability div
* @param {HTMLElement} div -
*/
updateDebugHTML(div: IAccessibleHTMLElement): void;
/**
* Adjust the hit area based on the bounds of a display object
* @param {PIXI.Rectangle} hitArea - Bounds of the child
*/
capHitArea(hitArea: Rectangle): void;
/**
* Adds a DisplayObject to the accessibility manager
* @private
* @param {PIXI.DisplayObject} displayObject - The child to make accessible.
*/
private addChild;
/**
* Dispatch events with the EventSystem.
* @param e
* @param type
* @private
*/
private _dispatchEvent;
/**
* Maps the div button press to pixi's EventSystem (click)
* @private
* @param {MouseEvent} e - The click event.
*/
private _onClick;
/**
* Maps the div focus events to pixi's EventSystem (mouseover)
* @private
* @param {FocusEvent} e - The focus event.
*/
private _onFocus;
/**
* Maps the div focus events to pixi's EventSystem (mouseout)
* @private
* @param {FocusEvent} e - The focusout event.
*/
private _onFocusOut;
/**
* Is called when a key is pressed
* @private
* @param {KeyboardEvent} e - The keydown event.
*/
private _onKeyDown;
/**
* Is called when the mouse moves across the renderer element
* @private
* @param {MouseEvent} e - The mouse event.
*/
private _onMouseMove;
/** Destroys the accessibility manager */
destroy(): void;
}

View File

@@ -1,193 +0,0 @@
"use strict";
var core = require("@pixi/core"), display = require("@pixi/display"), events = require("@pixi/events"), accessibleTarget = require("./accessibleTarget.js");
display.DisplayObject.mixin(accessibleTarget.accessibleTarget);
const KEY_CODE_TAB = 9, DIV_TOUCH_SIZE = 100, DIV_TOUCH_POS_X = 0, DIV_TOUCH_POS_Y = 0, DIV_TOUCH_ZINDEX = 2, DIV_HOOK_SIZE = 1, DIV_HOOK_POS_X = -1e3, DIV_HOOK_POS_Y = -1e3, DIV_HOOK_ZINDEX = 2;
class AccessibilityManager {
// 2fps
/**
* @param {PIXI.CanvasRenderer|PIXI.Renderer} renderer - A reference to the current renderer
*/
constructor(renderer) {
this.debug = !1, this._isActive = !1, this._isMobileAccessibility = !1, this.pool = [], this.renderId = 0, this.children = [], this.androidUpdateCount = 0, this.androidUpdateFrequency = 500, this._hookDiv = null, (core.utils.isMobile.tablet || core.utils.isMobile.phone) && this.createTouchHook();
const div = document.createElement("div");
div.style.width = `${DIV_TOUCH_SIZE}px`, div.style.height = `${DIV_TOUCH_SIZE}px`, div.style.position = "absolute", div.style.top = `${DIV_TOUCH_POS_X}px`, div.style.left = `${DIV_TOUCH_POS_Y}px`, div.style.zIndex = DIV_TOUCH_ZINDEX.toString(), this.div = div, this.renderer = renderer, this._onKeyDown = this._onKeyDown.bind(this), this._onMouseMove = this._onMouseMove.bind(this), globalThis.addEventListener("keydown", this._onKeyDown, !1);
}
/**
* Value of `true` if accessibility is currently active and accessibility layers are showing.
* @member {boolean}
* @readonly
*/
get isActive() {
return this._isActive;
}
/**
* Value of `true` if accessibility is enabled for touch devices.
* @member {boolean}
* @readonly
*/
get isMobileAccessibility() {
return this._isMobileAccessibility;
}
/**
* Creates the touch hooks.
* @private
*/
createTouchHook() {
const hookDiv = document.createElement("button");
hookDiv.style.width = `${DIV_HOOK_SIZE}px`, hookDiv.style.height = `${DIV_HOOK_SIZE}px`, hookDiv.style.position = "absolute", hookDiv.style.top = `${DIV_HOOK_POS_X}px`, hookDiv.style.left = `${DIV_HOOK_POS_Y}px`, hookDiv.style.zIndex = DIV_HOOK_ZINDEX.toString(), hookDiv.style.backgroundColor = "#FF0000", hookDiv.title = "select to enable accessibility for this content", hookDiv.addEventListener("focus", () => {
this._isMobileAccessibility = !0, this.activate(), this.destroyTouchHook();
}), document.body.appendChild(hookDiv), this._hookDiv = hookDiv;
}
/**
* Destroys the touch hooks.
* @private
*/
destroyTouchHook() {
this._hookDiv && (document.body.removeChild(this._hookDiv), this._hookDiv = null);
}
/**
* Activating will cause the Accessibility layer to be shown.
* This is called when a user presses the tab key.
* @private
*/
activate() {
this._isActive || (this._isActive = !0, globalThis.document.addEventListener("mousemove", this._onMouseMove, !0), globalThis.removeEventListener("keydown", this._onKeyDown, !1), this.renderer.on("postrender", this.update, this), this.renderer.view.parentNode?.appendChild(this.div));
}
/**
* Deactivating will cause the Accessibility layer to be hidden.
* This is called when a user moves the mouse.
* @private
*/
deactivate() {
!this._isActive || this._isMobileAccessibility || (this._isActive = !1, globalThis.document.removeEventListener("mousemove", this._onMouseMove, !0), globalThis.addEventListener("keydown", this._onKeyDown, !1), this.renderer.off("postrender", this.update), this.div.parentNode?.removeChild(this.div));
}
/**
* This recursive function will run through the scene graph and add any new accessible objects to the DOM layer.
* @private
* @param {PIXI.Container} displayObject - The DisplayObject to check.
*/
updateAccessibleObjects(displayObject) {
if (!displayObject.visible || !displayObject.accessibleChildren)
return;
displayObject.accessible && displayObject.isInteractive() && (displayObject._accessibleActive || this.addChild(displayObject), displayObject.renderId = this.renderId);
const children = displayObject.children;
if (children)
for (let i = 0; i < children.length; i++)
this.updateAccessibleObjects(children[i]);
}
/**
* Before each render this function will ensure that all divs are mapped correctly to their DisplayObjects.
* @private
*/
update() {
const now = performance.now();
if (core.utils.isMobile.android.device && now < this.androidUpdateCount || (this.androidUpdateCount = now + this.androidUpdateFrequency, !this.renderer.renderingToScreen))
return;
this.renderer.lastObjectRendered && this.updateAccessibleObjects(this.renderer.lastObjectRendered);
const { x, y, width, height } = this.renderer.view.getBoundingClientRect(), { width: viewWidth, height: viewHeight, resolution } = this.renderer, sx = width / viewWidth * resolution, sy = height / viewHeight * resolution;
let div = this.div;
div.style.left = `${x}px`, div.style.top = `${y}px`, div.style.width = `${viewWidth}px`, div.style.height = `${viewHeight}px`;
for (let i = 0; i < this.children.length; i++) {
const child = this.children[i];
if (child.renderId !== this.renderId)
child._accessibleActive = !1, core.utils.removeItems(this.children, i, 1), this.div.removeChild(child._accessibleDiv), this.pool.push(child._accessibleDiv), child._accessibleDiv = null, i--;
else {
div = child._accessibleDiv;
let hitArea = child.hitArea;
const wt = child.worldTransform;
child.hitArea ? (div.style.left = `${(wt.tx + hitArea.x * wt.a) * sx}px`, div.style.top = `${(wt.ty + hitArea.y * wt.d) * sy}px`, div.style.width = `${hitArea.width * wt.a * sx}px`, div.style.height = `${hitArea.height * wt.d * sy}px`) : (hitArea = child.getBounds(), this.capHitArea(hitArea), div.style.left = `${hitArea.x * sx}px`, div.style.top = `${hitArea.y * sy}px`, div.style.width = `${hitArea.width * sx}px`, div.style.height = `${hitArea.height * sy}px`, div.title !== child.accessibleTitle && child.accessibleTitle !== null && (div.title = child.accessibleTitle), div.getAttribute("aria-label") !== child.accessibleHint && child.accessibleHint !== null && div.setAttribute("aria-label", child.accessibleHint)), (child.accessibleTitle !== div.title || child.tabIndex !== div.tabIndex) && (div.title = child.accessibleTitle, div.tabIndex = child.tabIndex, this.debug && this.updateDebugHTML(div));
}
}
this.renderId++;
}
/**
* private function that will visually add the information to the
* accessability div
* @param {HTMLElement} div -
*/
updateDebugHTML(div) {
div.innerHTML = `type: ${div.type}</br> title : ${div.title}</br> tabIndex: ${div.tabIndex}`;
}
/**
* Adjust the hit area based on the bounds of a display object
* @param {PIXI.Rectangle} hitArea - Bounds of the child
*/
capHitArea(hitArea) {
hitArea.x < 0 && (hitArea.width += hitArea.x, hitArea.x = 0), hitArea.y < 0 && (hitArea.height += hitArea.y, hitArea.y = 0);
const { width: viewWidth, height: viewHeight } = this.renderer;
hitArea.x + hitArea.width > viewWidth && (hitArea.width = viewWidth - hitArea.x), hitArea.y + hitArea.height > viewHeight && (hitArea.height = viewHeight - hitArea.y);
}
/**
* Adds a DisplayObject to the accessibility manager
* @private
* @param {PIXI.DisplayObject} displayObject - The child to make accessible.
*/
addChild(displayObject) {
let div = this.pool.pop();
div || (div = document.createElement("button"), div.style.width = `${DIV_TOUCH_SIZE}px`, div.style.height = `${DIV_TOUCH_SIZE}px`, div.style.backgroundColor = this.debug ? "rgba(255,255,255,0.5)" : "transparent", div.style.position = "absolute", div.style.zIndex = DIV_TOUCH_ZINDEX.toString(), div.style.borderStyle = "none", navigator.userAgent.toLowerCase().includes("chrome") ? div.setAttribute("aria-live", "off") : div.setAttribute("aria-live", "polite"), navigator.userAgent.match(/rv:.*Gecko\//) ? div.setAttribute("aria-relevant", "additions") : div.setAttribute("aria-relevant", "text"), div.addEventListener("click", this._onClick.bind(this)), div.addEventListener("focus", this._onFocus.bind(this)), div.addEventListener("focusout", this._onFocusOut.bind(this))), div.style.pointerEvents = displayObject.accessiblePointerEvents, div.type = displayObject.accessibleType, displayObject.accessibleTitle && displayObject.accessibleTitle !== null ? div.title = displayObject.accessibleTitle : (!displayObject.accessibleHint || displayObject.accessibleHint === null) && (div.title = `displayObject ${displayObject.tabIndex}`), displayObject.accessibleHint && displayObject.accessibleHint !== null && div.setAttribute("aria-label", displayObject.accessibleHint), this.debug && this.updateDebugHTML(div), displayObject._accessibleActive = !0, displayObject._accessibleDiv = div, div.displayObject = displayObject, this.children.push(displayObject), this.div.appendChild(displayObject._accessibleDiv), displayObject._accessibleDiv.tabIndex = displayObject.tabIndex;
}
/**
* Dispatch events with the EventSystem.
* @param e
* @param type
* @private
*/
_dispatchEvent(e, type) {
const { displayObject: target } = e.target, boundry = this.renderer.events.rootBoundary, event = Object.assign(new events.FederatedEvent(boundry), { target });
boundry.rootTarget = this.renderer.lastObjectRendered, type.forEach((type2) => boundry.dispatchEvent(event, type2));
}
/**
* Maps the div button press to pixi's EventSystem (click)
* @private
* @param {MouseEvent} e - The click event.
*/
_onClick(e) {
this._dispatchEvent(e, ["click", "pointertap", "tap"]);
}
/**
* Maps the div focus events to pixi's EventSystem (mouseover)
* @private
* @param {FocusEvent} e - The focus event.
*/
_onFocus(e) {
e.target.getAttribute("aria-live") || e.target.setAttribute("aria-live", "assertive"), this._dispatchEvent(e, ["mouseover"]);
}
/**
* Maps the div focus events to pixi's EventSystem (mouseout)
* @private
* @param {FocusEvent} e - The focusout event.
*/
_onFocusOut(e) {
e.target.getAttribute("aria-live") || e.target.setAttribute("aria-live", "polite"), this._dispatchEvent(e, ["mouseout"]);
}
/**
* Is called when a key is pressed
* @private
* @param {KeyboardEvent} e - The keydown event.
*/
_onKeyDown(e) {
e.keyCode === KEY_CODE_TAB && this.activate();
}
/**
* Is called when the mouse moves across the renderer element
* @private
* @param {MouseEvent} e - The mouse event.
*/
_onMouseMove(e) {
e.movementX === 0 && e.movementY === 0 || this.deactivate();
}
/** Destroys the accessibility manager */
destroy() {
this.destroyTouchHook(), this.div = null, globalThis.document.removeEventListener("mousemove", this._onMouseMove, !0), globalThis.removeEventListener("keydown", this._onKeyDown), this.pool = null, this.children = null, this.renderer = null;
}
}
AccessibilityManager.extension = {
name: "accessibility",
type: [
core.ExtensionType.RendererPlugin,
core.ExtensionType.CanvasRendererPlugin
]
};
core.extensions.add(AccessibilityManager);
exports.AccessibilityManager = AccessibilityManager;
//# sourceMappingURL=AccessibilityManager.js.map

File diff suppressed because one or more lines are too long

View File

@@ -1,197 +0,0 @@
import { utils, ExtensionType, extensions } from "@pixi/core";
import { DisplayObject } from "@pixi/display";
import { FederatedEvent } from "@pixi/events";
import { accessibleTarget } from "./accessibleTarget.mjs";
DisplayObject.mixin(accessibleTarget);
const KEY_CODE_TAB = 9, DIV_TOUCH_SIZE = 100, DIV_TOUCH_POS_X = 0, DIV_TOUCH_POS_Y = 0, DIV_TOUCH_ZINDEX = 2, DIV_HOOK_SIZE = 1, DIV_HOOK_POS_X = -1e3, DIV_HOOK_POS_Y = -1e3, DIV_HOOK_ZINDEX = 2;
class AccessibilityManager {
// 2fps
/**
* @param {PIXI.CanvasRenderer|PIXI.Renderer} renderer - A reference to the current renderer
*/
constructor(renderer) {
this.debug = !1, this._isActive = !1, this._isMobileAccessibility = !1, this.pool = [], this.renderId = 0, this.children = [], this.androidUpdateCount = 0, this.androidUpdateFrequency = 500, this._hookDiv = null, (utils.isMobile.tablet || utils.isMobile.phone) && this.createTouchHook();
const div = document.createElement("div");
div.style.width = `${DIV_TOUCH_SIZE}px`, div.style.height = `${DIV_TOUCH_SIZE}px`, div.style.position = "absolute", div.style.top = `${DIV_TOUCH_POS_X}px`, div.style.left = `${DIV_TOUCH_POS_Y}px`, div.style.zIndex = DIV_TOUCH_ZINDEX.toString(), this.div = div, this.renderer = renderer, this._onKeyDown = this._onKeyDown.bind(this), this._onMouseMove = this._onMouseMove.bind(this), globalThis.addEventListener("keydown", this._onKeyDown, !1);
}
/**
* Value of `true` if accessibility is currently active and accessibility layers are showing.
* @member {boolean}
* @readonly
*/
get isActive() {
return this._isActive;
}
/**
* Value of `true` if accessibility is enabled for touch devices.
* @member {boolean}
* @readonly
*/
get isMobileAccessibility() {
return this._isMobileAccessibility;
}
/**
* Creates the touch hooks.
* @private
*/
createTouchHook() {
const hookDiv = document.createElement("button");
hookDiv.style.width = `${DIV_HOOK_SIZE}px`, hookDiv.style.height = `${DIV_HOOK_SIZE}px`, hookDiv.style.position = "absolute", hookDiv.style.top = `${DIV_HOOK_POS_X}px`, hookDiv.style.left = `${DIV_HOOK_POS_Y}px`, hookDiv.style.zIndex = DIV_HOOK_ZINDEX.toString(), hookDiv.style.backgroundColor = "#FF0000", hookDiv.title = "select to enable accessibility for this content", hookDiv.addEventListener("focus", () => {
this._isMobileAccessibility = !0, this.activate(), this.destroyTouchHook();
}), document.body.appendChild(hookDiv), this._hookDiv = hookDiv;
}
/**
* Destroys the touch hooks.
* @private
*/
destroyTouchHook() {
this._hookDiv && (document.body.removeChild(this._hookDiv), this._hookDiv = null);
}
/**
* Activating will cause the Accessibility layer to be shown.
* This is called when a user presses the tab key.
* @private
*/
activate() {
this._isActive || (this._isActive = !0, globalThis.document.addEventListener("mousemove", this._onMouseMove, !0), globalThis.removeEventListener("keydown", this._onKeyDown, !1), this.renderer.on("postrender", this.update, this), this.renderer.view.parentNode?.appendChild(this.div));
}
/**
* Deactivating will cause the Accessibility layer to be hidden.
* This is called when a user moves the mouse.
* @private
*/
deactivate() {
!this._isActive || this._isMobileAccessibility || (this._isActive = !1, globalThis.document.removeEventListener("mousemove", this._onMouseMove, !0), globalThis.addEventListener("keydown", this._onKeyDown, !1), this.renderer.off("postrender", this.update), this.div.parentNode?.removeChild(this.div));
}
/**
* This recursive function will run through the scene graph and add any new accessible objects to the DOM layer.
* @private
* @param {PIXI.Container} displayObject - The DisplayObject to check.
*/
updateAccessibleObjects(displayObject) {
if (!displayObject.visible || !displayObject.accessibleChildren)
return;
displayObject.accessible && displayObject.isInteractive() && (displayObject._accessibleActive || this.addChild(displayObject), displayObject.renderId = this.renderId);
const children = displayObject.children;
if (children)
for (let i = 0; i < children.length; i++)
this.updateAccessibleObjects(children[i]);
}
/**
* Before each render this function will ensure that all divs are mapped correctly to their DisplayObjects.
* @private
*/
update() {
const now = performance.now();
if (utils.isMobile.android.device && now < this.androidUpdateCount || (this.androidUpdateCount = now + this.androidUpdateFrequency, !this.renderer.renderingToScreen))
return;
this.renderer.lastObjectRendered && this.updateAccessibleObjects(this.renderer.lastObjectRendered);
const { x, y, width, height } = this.renderer.view.getBoundingClientRect(), { width: viewWidth, height: viewHeight, resolution } = this.renderer, sx = width / viewWidth * resolution, sy = height / viewHeight * resolution;
let div = this.div;
div.style.left = `${x}px`, div.style.top = `${y}px`, div.style.width = `${viewWidth}px`, div.style.height = `${viewHeight}px`;
for (let i = 0; i < this.children.length; i++) {
const child = this.children[i];
if (child.renderId !== this.renderId)
child._accessibleActive = !1, utils.removeItems(this.children, i, 1), this.div.removeChild(child._accessibleDiv), this.pool.push(child._accessibleDiv), child._accessibleDiv = null, i--;
else {
div = child._accessibleDiv;
let hitArea = child.hitArea;
const wt = child.worldTransform;
child.hitArea ? (div.style.left = `${(wt.tx + hitArea.x * wt.a) * sx}px`, div.style.top = `${(wt.ty + hitArea.y * wt.d) * sy}px`, div.style.width = `${hitArea.width * wt.a * sx}px`, div.style.height = `${hitArea.height * wt.d * sy}px`) : (hitArea = child.getBounds(), this.capHitArea(hitArea), div.style.left = `${hitArea.x * sx}px`, div.style.top = `${hitArea.y * sy}px`, div.style.width = `${hitArea.width * sx}px`, div.style.height = `${hitArea.height * sy}px`, div.title !== child.accessibleTitle && child.accessibleTitle !== null && (div.title = child.accessibleTitle), div.getAttribute("aria-label") !== child.accessibleHint && child.accessibleHint !== null && div.setAttribute("aria-label", child.accessibleHint)), (child.accessibleTitle !== div.title || child.tabIndex !== div.tabIndex) && (div.title = child.accessibleTitle, div.tabIndex = child.tabIndex, this.debug && this.updateDebugHTML(div));
}
}
this.renderId++;
}
/**
* private function that will visually add the information to the
* accessability div
* @param {HTMLElement} div -
*/
updateDebugHTML(div) {
div.innerHTML = `type: ${div.type}</br> title : ${div.title}</br> tabIndex: ${div.tabIndex}`;
}
/**
* Adjust the hit area based on the bounds of a display object
* @param {PIXI.Rectangle} hitArea - Bounds of the child
*/
capHitArea(hitArea) {
hitArea.x < 0 && (hitArea.width += hitArea.x, hitArea.x = 0), hitArea.y < 0 && (hitArea.height += hitArea.y, hitArea.y = 0);
const { width: viewWidth, height: viewHeight } = this.renderer;
hitArea.x + hitArea.width > viewWidth && (hitArea.width = viewWidth - hitArea.x), hitArea.y + hitArea.height > viewHeight && (hitArea.height = viewHeight - hitArea.y);
}
/**
* Adds a DisplayObject to the accessibility manager
* @private
* @param {PIXI.DisplayObject} displayObject - The child to make accessible.
*/
addChild(displayObject) {
let div = this.pool.pop();
div || (div = document.createElement("button"), div.style.width = `${DIV_TOUCH_SIZE}px`, div.style.height = `${DIV_TOUCH_SIZE}px`, div.style.backgroundColor = this.debug ? "rgba(255,255,255,0.5)" : "transparent", div.style.position = "absolute", div.style.zIndex = DIV_TOUCH_ZINDEX.toString(), div.style.borderStyle = "none", navigator.userAgent.toLowerCase().includes("chrome") ? div.setAttribute("aria-live", "off") : div.setAttribute("aria-live", "polite"), navigator.userAgent.match(/rv:.*Gecko\//) ? div.setAttribute("aria-relevant", "additions") : div.setAttribute("aria-relevant", "text"), div.addEventListener("click", this._onClick.bind(this)), div.addEventListener("focus", this._onFocus.bind(this)), div.addEventListener("focusout", this._onFocusOut.bind(this))), div.style.pointerEvents = displayObject.accessiblePointerEvents, div.type = displayObject.accessibleType, displayObject.accessibleTitle && displayObject.accessibleTitle !== null ? div.title = displayObject.accessibleTitle : (!displayObject.accessibleHint || displayObject.accessibleHint === null) && (div.title = `displayObject ${displayObject.tabIndex}`), displayObject.accessibleHint && displayObject.accessibleHint !== null && div.setAttribute("aria-label", displayObject.accessibleHint), this.debug && this.updateDebugHTML(div), displayObject._accessibleActive = !0, displayObject._accessibleDiv = div, div.displayObject = displayObject, this.children.push(displayObject), this.div.appendChild(displayObject._accessibleDiv), displayObject._accessibleDiv.tabIndex = displayObject.tabIndex;
}
/**
* Dispatch events with the EventSystem.
* @param e
* @param type
* @private
*/
_dispatchEvent(e, type) {
const { displayObject: target } = e.target, boundry = this.renderer.events.rootBoundary, event = Object.assign(new FederatedEvent(boundry), { target });
boundry.rootTarget = this.renderer.lastObjectRendered, type.forEach((type2) => boundry.dispatchEvent(event, type2));
}
/**
* Maps the div button press to pixi's EventSystem (click)
* @private
* @param {MouseEvent} e - The click event.
*/
_onClick(e) {
this._dispatchEvent(e, ["click", "pointertap", "tap"]);
}
/**
* Maps the div focus events to pixi's EventSystem (mouseover)
* @private
* @param {FocusEvent} e - The focus event.
*/
_onFocus(e) {
e.target.getAttribute("aria-live") || e.target.setAttribute("aria-live", "assertive"), this._dispatchEvent(e, ["mouseover"]);
}
/**
* Maps the div focus events to pixi's EventSystem (mouseout)
* @private
* @param {FocusEvent} e - The focusout event.
*/
_onFocusOut(e) {
e.target.getAttribute("aria-live") || e.target.setAttribute("aria-live", "polite"), this._dispatchEvent(e, ["mouseout"]);
}
/**
* Is called when a key is pressed
* @private
* @param {KeyboardEvent} e - The keydown event.
*/
_onKeyDown(e) {
e.keyCode === KEY_CODE_TAB && this.activate();
}
/**
* Is called when the mouse moves across the renderer element
* @private
* @param {MouseEvent} e - The mouse event.
*/
_onMouseMove(e) {
e.movementX === 0 && e.movementY === 0 || this.deactivate();
}
/** Destroys the accessibility manager */
destroy() {
this.destroyTouchHook(), this.div = null, globalThis.document.removeEventListener("mousemove", this._onMouseMove, !0), globalThis.removeEventListener("keydown", this._onKeyDown), this.pool = null, this.children = null, this.renderer = null;
}
}
AccessibilityManager.extension = {
name: "accessibility",
type: [
ExtensionType.RendererPlugin,
ExtensionType.CanvasRendererPlugin
]
};
extensions.add(AccessibilityManager);
export {
AccessibilityManager
};
//# sourceMappingURL=AccessibilityManager.mjs.map

File diff suppressed because one or more lines are too long

View File

@@ -1,32 +0,0 @@
import type { DisplayObject } from '@pixi/display';
export type PointerEvents = 'auto' | 'none' | 'visiblePainted' | 'visibleFill' | 'visibleStroke' | 'visible' | 'painted' | 'fill' | 'stroke' | 'all' | 'inherit';
export interface IAccessibleTarget {
accessible: boolean;
accessibleTitle: string;
accessibleHint: string;
tabIndex: number;
_accessibleActive: boolean;
_accessibleDiv: IAccessibleHTMLElement;
accessibleType: string;
accessiblePointerEvents: PointerEvents;
accessibleChildren: boolean;
renderId: number;
}
export interface IAccessibleHTMLElement extends HTMLElement {
type?: string;
displayObject?: DisplayObject;
}
/**
* Default property values of accessible objects
* used by {@link PIXI.AccessibilityManager}.
* @private
* @function accessibleTarget
* @memberof PIXI
* @type {object}
* @example
* import { accessibleTarget } from 'pixi.js';
*
* function MyObject() {}
* Object.assign(MyObject.prototype, accessibleTarget);
*/
export declare const accessibleTarget: IAccessibleTarget;

View File

@@ -1,69 +0,0 @@
"use strict";
const accessibleTarget = {
/**
* Flag for if the object is accessible. If true AccessibilityManager will overlay a
* shadow div with attributes set
* @member {boolean}
* @memberof PIXI.DisplayObject#
*/
accessible: !1,
/**
* Sets the title attribute of the shadow div
* If accessibleTitle AND accessibleHint has not been this will default to 'displayObject [tabIndex]'
* @member {?string}
* @memberof PIXI.DisplayObject#
*/
accessibleTitle: null,
/**
* Sets the aria-label attribute of the shadow div
* @member {string}
* @memberof PIXI.DisplayObject#
*/
accessibleHint: null,
/**
* @member {number}
* @memberof PIXI.DisplayObject#
* @private
* @todo Needs docs.
*/
tabIndex: 0,
/**
* @member {boolean}
* @memberof PIXI.DisplayObject#
* @todo Needs docs.
*/
_accessibleActive: !1,
/**
* @member {boolean}
* @memberof PIXI.DisplayObject#
* @todo Needs docs.
*/
_accessibleDiv: null,
/**
* Specify the type of div the accessible layer is. Screen readers treat the element differently
* depending on this type. Defaults to button.
* @member {string}
* @memberof PIXI.DisplayObject#
* @default 'button'
*/
accessibleType: "button",
/**
* Specify the pointer-events the accessible div will use
* Defaults to auto.
* @member {string}
* @memberof PIXI.DisplayObject#
* @default 'auto'
*/
accessiblePointerEvents: "auto",
/**
* Setting to false will prevent any children inside this container to
* be accessible. Defaults to true.
* @member {boolean}
* @memberof PIXI.DisplayObject#
* @default true
*/
accessibleChildren: !0,
renderId: -1
};
exports.accessibleTarget = accessibleTarget;
//# sourceMappingURL=accessibleTarget.js.map

View File

@@ -1 +0,0 @@
{"version":3,"file":"accessibleTarget.js","sources":["../src/accessibleTarget.ts"],"sourcesContent":["import type { DisplayObject } from '@pixi/display';\n\nexport type PointerEvents = 'auto'\n| 'none'\n| 'visiblePainted'\n| 'visibleFill'\n| 'visibleStroke'\n| 'visible'\n| 'painted'\n| 'fill'\n| 'stroke'\n| 'all'\n| 'inherit';\n\nexport interface IAccessibleTarget\n{\n accessible: boolean;\n accessibleTitle: string;\n accessibleHint: string;\n tabIndex: number;\n _accessibleActive: boolean;\n _accessibleDiv: IAccessibleHTMLElement;\n accessibleType: string;\n accessiblePointerEvents: PointerEvents;\n accessibleChildren: boolean;\n renderId: number;\n}\n\nexport interface IAccessibleHTMLElement extends HTMLElement\n{\n type?: string;\n displayObject?: DisplayObject;\n}\n\n/**\n * Default property values of accessible objects\n * used by {@link PIXI.AccessibilityManager}.\n * @private\n * @function accessibleTarget\n * @memberof PIXI\n * @type {object}\n * @example\n * import { accessibleTarget } from 'pixi.js';\n *\n * function MyObject() {}\n * Object.assign(MyObject.prototype, accessibleTarget);\n */\nexport const accessibleTarget: IAccessibleTarget = {\n /**\n * Flag for if the object is accessible. If true AccessibilityManager will overlay a\n * shadow div with attributes set\n * @member {boolean}\n * @memberof PIXI.DisplayObject#\n */\n accessible: false,\n\n /**\n * Sets the title attribute of the shadow div\n * If accessibleTitle AND accessibleHint has not been this will default to 'displayObject [tabIndex]'\n * @member {?string}\n * @memberof PIXI.DisplayObject#\n */\n accessibleTitle: null,\n\n /**\n * Sets the aria-label attribute of the shadow div\n * @member {string}\n * @memberof PIXI.DisplayObject#\n */\n accessibleHint: null,\n\n /**\n * @member {number}\n * @memberof PIXI.DisplayObject#\n * @private\n * @todo Needs docs.\n */\n tabIndex: 0,\n\n /**\n * @member {boolean}\n * @memberof PIXI.DisplayObject#\n * @todo Needs docs.\n */\n _accessibleActive: false,\n\n /**\n * @member {boolean}\n * @memberof PIXI.DisplayObject#\n * @todo Needs docs.\n */\n _accessibleDiv: null,\n\n /**\n * Specify the type of div the accessible layer is. Screen readers treat the element differently\n * depending on this type. Defaults to button.\n * @member {string}\n * @memberof PIXI.DisplayObject#\n * @default 'button'\n */\n accessibleType: 'button',\n\n /**\n * Specify the pointer-events the accessible div will use\n * Defaults to auto.\n * @member {string}\n * @memberof PIXI.DisplayObject#\n * @default 'auto'\n */\n accessiblePointerEvents: 'auto',\n\n /**\n * Setting to false will prevent any children inside this container to\n * be accessible. Defaults to true.\n * @member {boolean}\n * @memberof PIXI.DisplayObject#\n * @default true\n */\n accessibleChildren: true,\n\n renderId: -1,\n};\n"],"names":[],"mappings":";AA+CO,MAAM,mBAAsC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAO/C,YAAY;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQZ,iBAAiB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOjB,gBAAgB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQhB,UAAU;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOV,mBAAmB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOnB,gBAAgB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAShB,gBAAgB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAShB,yBAAyB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASzB,oBAAoB;AAAA,EAEpB,UAAU;AACd;;"}

View File

@@ -1,70 +0,0 @@
const accessibleTarget = {
/**
* Flag for if the object is accessible. If true AccessibilityManager will overlay a
* shadow div with attributes set
* @member {boolean}
* @memberof PIXI.DisplayObject#
*/
accessible: !1,
/**
* Sets the title attribute of the shadow div
* If accessibleTitle AND accessibleHint has not been this will default to 'displayObject [tabIndex]'
* @member {?string}
* @memberof PIXI.DisplayObject#
*/
accessibleTitle: null,
/**
* Sets the aria-label attribute of the shadow div
* @member {string}
* @memberof PIXI.DisplayObject#
*/
accessibleHint: null,
/**
* @member {number}
* @memberof PIXI.DisplayObject#
* @private
* @todo Needs docs.
*/
tabIndex: 0,
/**
* @member {boolean}
* @memberof PIXI.DisplayObject#
* @todo Needs docs.
*/
_accessibleActive: !1,
/**
* @member {boolean}
* @memberof PIXI.DisplayObject#
* @todo Needs docs.
*/
_accessibleDiv: null,
/**
* Specify the type of div the accessible layer is. Screen readers treat the element differently
* depending on this type. Defaults to button.
* @member {string}
* @memberof PIXI.DisplayObject#
* @default 'button'
*/
accessibleType: "button",
/**
* Specify the pointer-events the accessible div will use
* Defaults to auto.
* @member {string}
* @memberof PIXI.DisplayObject#
* @default 'auto'
*/
accessiblePointerEvents: "auto",
/**
* Setting to false will prevent any children inside this container to
* be accessible. Defaults to true.
* @member {boolean}
* @memberof PIXI.DisplayObject#
* @default true
*/
accessibleChildren: !0,
renderId: -1
};
export {
accessibleTarget
};
//# sourceMappingURL=accessibleTarget.mjs.map

View File

@@ -1 +0,0 @@
{"version":3,"file":"accessibleTarget.mjs","sources":["../src/accessibleTarget.ts"],"sourcesContent":["import type { DisplayObject } from '@pixi/display';\n\nexport type PointerEvents = 'auto'\n| 'none'\n| 'visiblePainted'\n| 'visibleFill'\n| 'visibleStroke'\n| 'visible'\n| 'painted'\n| 'fill'\n| 'stroke'\n| 'all'\n| 'inherit';\n\nexport interface IAccessibleTarget\n{\n accessible: boolean;\n accessibleTitle: string;\n accessibleHint: string;\n tabIndex: number;\n _accessibleActive: boolean;\n _accessibleDiv: IAccessibleHTMLElement;\n accessibleType: string;\n accessiblePointerEvents: PointerEvents;\n accessibleChildren: boolean;\n renderId: number;\n}\n\nexport interface IAccessibleHTMLElement extends HTMLElement\n{\n type?: string;\n displayObject?: DisplayObject;\n}\n\n/**\n * Default property values of accessible objects\n * used by {@link PIXI.AccessibilityManager}.\n * @private\n * @function accessibleTarget\n * @memberof PIXI\n * @type {object}\n * @example\n * import { accessibleTarget } from 'pixi.js';\n *\n * function MyObject() {}\n * Object.assign(MyObject.prototype, accessibleTarget);\n */\nexport const accessibleTarget: IAccessibleTarget = {\n /**\n * Flag for if the object is accessible. If true AccessibilityManager will overlay a\n * shadow div with attributes set\n * @member {boolean}\n * @memberof PIXI.DisplayObject#\n */\n accessible: false,\n\n /**\n * Sets the title attribute of the shadow div\n * If accessibleTitle AND accessibleHint has not been this will default to 'displayObject [tabIndex]'\n * @member {?string}\n * @memberof PIXI.DisplayObject#\n */\n accessibleTitle: null,\n\n /**\n * Sets the aria-label attribute of the shadow div\n * @member {string}\n * @memberof PIXI.DisplayObject#\n */\n accessibleHint: null,\n\n /**\n * @member {number}\n * @memberof PIXI.DisplayObject#\n * @private\n * @todo Needs docs.\n */\n tabIndex: 0,\n\n /**\n * @member {boolean}\n * @memberof PIXI.DisplayObject#\n * @todo Needs docs.\n */\n _accessibleActive: false,\n\n /**\n * @member {boolean}\n * @memberof PIXI.DisplayObject#\n * @todo Needs docs.\n */\n _accessibleDiv: null,\n\n /**\n * Specify the type of div the accessible layer is. Screen readers treat the element differently\n * depending on this type. Defaults to button.\n * @member {string}\n * @memberof PIXI.DisplayObject#\n * @default 'button'\n */\n accessibleType: 'button',\n\n /**\n * Specify the pointer-events the accessible div will use\n * Defaults to auto.\n * @member {string}\n * @memberof PIXI.DisplayObject#\n * @default 'auto'\n */\n accessiblePointerEvents: 'auto',\n\n /**\n * Setting to false will prevent any children inside this container to\n * be accessible. Defaults to true.\n * @member {boolean}\n * @memberof PIXI.DisplayObject#\n * @default true\n */\n accessibleChildren: true,\n\n renderId: -1,\n};\n"],"names":[],"mappings":"AA+CO,MAAM,mBAAsC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAO/C,YAAY;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQZ,iBAAiB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOjB,gBAAgB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQhB,UAAU;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOV,mBAAmB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOnB,gBAAgB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAShB,gBAAgB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAShB,yBAAyB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASzB,oBAAoB;AAAA,EAEpB,UAAU;AACd;"}

View File

@@ -1,3 +0,0 @@
/// <reference path="../global.d.ts" />
export * from './AccessibilityManager';
export * from './accessibleTarget';

View File

@@ -1,5 +0,0 @@
"use strict";
var AccessibilityManager = require("./AccessibilityManager.js"), accessibleTarget = require("./accessibleTarget.js");
exports.AccessibilityManager = AccessibilityManager.AccessibilityManager;
exports.accessibleTarget = accessibleTarget.accessibleTarget;
//# sourceMappingURL=index.js.map

View File

@@ -1 +0,0 @@
{"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;"}

View File

@@ -1,7 +0,0 @@
import { AccessibilityManager } from "./AccessibilityManager.mjs";
import { accessibleTarget } from "./accessibleTarget.mjs";
export {
AccessibilityManager,
accessibleTarget
};
//# sourceMappingURL=index.mjs.map

View File

@@ -1 +0,0 @@
{"version":3,"file":"index.mjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;"}

View File

@@ -1,18 +1,19 @@
{
"name": "@pixi/accessibility",
"version": "7.4.2",
"main": "lib/index.js",
"module": "lib/index.mjs",
"types": "lib/index.d.ts",
"version": "6.5.10",
"main": "dist/cjs/accessibility.js",
"module": "dist/esm/accessibility.mjs",
"bundle": "dist/browser/accessibility.js",
"types": "index.d.ts",
"exports": {
".": {
"import": {
"types": "./lib/index.d.ts",
"default": "./lib/index.mjs"
"types": "./index.d.ts",
"default": "./dist/esm/accessibility.mjs"
},
"require": {
"types": "./lib/index.d.ts",
"default": "./lib/index.js"
"types": "./index.d.ts",
"default": "./dist/cjs/accessibility.js"
}
}
},
@@ -22,22 +23,24 @@
"Matt Karl <matt@mattkarl.com>"
],
"homepage": "http://pixijs.com/",
"bugs": "https://github.com/pixijs/pixijs/issues",
"bugs": "https://github.com/pixijs/pixi.js/issues",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/pixijs/pixijs.git"
"url": "https://github.com/pixijs/pixi.js.git"
},
"publishConfig": {
"access": "public"
},
"files": [
"lib",
"dist",
"*.d.ts"
],
"peerDependencies": {
"@pixi/core": "7.4.2",
"@pixi/display": "7.4.2",
"@pixi/events": "7.4.2"
}
"@pixi/core": "6.5.10",
"@pixi/display": "6.5.10",
"@pixi/utils": "6.5.10"
},
"gitHead": "8cdbf55064b7adc05f65c51e177f1c22f7329f0f"
}

View File

@@ -1,6 +1,6 @@
The MIT License
Copyright (c) 2013-2023 Mathew Groves, Chad Engler
Copyright (c) 2013-2018 Mathew Groves, Chad Engler
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
@@ -18,4 +18,4 @@ 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.
THE SOFTWARE.

View File

@@ -19,4 +19,5 @@ document.body.appendChild(app.view);
PixiJS provides a few plugins to add features to the Application. These can be installed from the following packages. Use `extensions.add` to use these plugins. _Note: if you are using pixi.js or pixi.js-legacy bundles, this is unnecessary since plugins are installed automatically by default._
* **TickerPlugin** from `@pixi/ticker`
* **LoaderPlugin** from `@pixi/loaders`
* **TickerPlugin** from `@pixi/ticker`

294
live2d/node_modules/@pixi/app/dist/browser/app.js generated vendored Normal file
View File

@@ -0,0 +1,294 @@
/*!
* @pixi/app - v6.5.10
* Compiled Thu, 06 Jul 2023 15:25:11 UTC
*
* @pixi/app is licensed under the MIT License.
* http://www.opensource.org/licenses/mit-license
*/
this.PIXI = this.PIXI || {};
var _pixi_app = (function (exports, core, display, utils) {
'use strict';
/**
* Middleware for for Application's resize functionality
* @private
* @class
*/
var ResizePlugin = /** @class */ (function () {
function ResizePlugin() {
}
/**
* Initialize the plugin with scope of application instance
* @static
* @private
* @param {object} [options] - See application options
*/
ResizePlugin.init = function (options) {
var _this = this;
Object.defineProperty(this, 'resizeTo',
/**
* The HTML element or window to automatically resize the
* renderer's view element to match width and height.
* @member {Window|HTMLElement}
* @name resizeTo
* @memberof PIXI.Application#
*/
{
set: function (dom) {
globalThis.removeEventListener('resize', this.queueResize);
this._resizeTo = dom;
if (dom) {
globalThis.addEventListener('resize', this.queueResize);
this.resize();
}
},
get: function () {
return this._resizeTo;
},
});
/**
* Resize is throttled, so it's safe to call this multiple times per frame and it'll
* only be called once.
* @memberof PIXI.Application#
* @method queueResize
* @private
*/
this.queueResize = function () {
if (!_this._resizeTo) {
return;
}
_this.cancelResize();
// // Throttle resize events per raf
_this._resizeId = requestAnimationFrame(function () { return _this.resize(); });
};
/**
* Cancel the resize queue.
* @memberof PIXI.Application#
* @method cancelResize
* @private
*/
this.cancelResize = function () {
if (_this._resizeId) {
cancelAnimationFrame(_this._resizeId);
_this._resizeId = null;
}
};
/**
* Execute an immediate resize on the renderer, this is not
* throttled and can be expensive to call many times in a row.
* Will resize only if `resizeTo` property is set.
* @memberof PIXI.Application#
* @method resize
*/
this.resize = function () {
if (!_this._resizeTo) {
return;
}
// clear queue resize
_this.cancelResize();
var width;
var height;
// Resize to the window
if (_this._resizeTo === globalThis.window) {
width = globalThis.innerWidth;
height = globalThis.innerHeight;
}
// Resize to other HTML entities
else {
var _a = _this._resizeTo, clientWidth = _a.clientWidth, clientHeight = _a.clientHeight;
width = clientWidth;
height = clientHeight;
}
_this.renderer.resize(width, height);
};
// On resize
this._resizeId = null;
this._resizeTo = null;
this.resizeTo = options.resizeTo || null;
};
/**
* Clean up the ticker, scoped to application
* @static
* @private
*/
ResizePlugin.destroy = function () {
globalThis.removeEventListener('resize', this.queueResize);
this.cancelResize();
this.cancelResize = null;
this.queueResize = null;
this.resizeTo = null;
this.resize = null;
};
/** @ignore */
ResizePlugin.extension = core.ExtensionType.Application;
return ResizePlugin;
}());
/**
* Convenience class to create a new PIXI application.
*
* This class automatically creates the renderer, ticker and root container.
* @example
* // Create the application
* const app = new PIXI.Application();
*
* // Add the view to the DOM
* document.body.appendChild(app.view);
*
* // ex, add display objects
* app.stage.addChild(PIXI.Sprite.from('something.png'));
* @class
* @memberof PIXI
*/
var Application = /** @class */ (function () {
/**
* @param {PIXI.IApplicationOptions} [options] - The optional application and renderer parameters.
* @param {boolean} [options.antialias=false] -
* **WebGL Only.** Whether to enable anti-aliasing. This may affect performance.
* @param {boolean} [options.autoDensity=false] -
* Whether the CSS dimensions of the renderer's view should be resized automatically.
* @param {boolean} [options.autoStart=true] - Automatically starts the rendering after the construction.
* **Note**: Setting this parameter to false does NOT stop the shared ticker even if you set
* `options.sharedTicker` to `true` in case that it is already started. Stop it by your own.
* @param {number} [options.backgroundAlpha=1] -
* Transparency of the background color, value from `0` (fully transparent) to `1` (fully opaque).
* @param {number} [options.backgroundColor=0x000000] -
* The background color used to clear the canvas. It accepts hex numbers (e.g. `0xff0000`).
* @param {boolean} [options.clearBeforeRender=true] - Whether to clear the canvas before new render passes.
* @param {PIXI.IRenderingContext} [options.context] - **WebGL Only.** User-provided WebGL rendering context object.
* @param {boolean} [options.forceCanvas=false] -
* Force using {@link PIXI.CanvasRenderer}, even if WebGL is available. This option only is available when
* using **pixi.js-legacy** or **@pixi/canvas-renderer** packages, otherwise it is ignored.
* @param {number} [options.height=600] - The height of the renderer's view.
* @param {string} [options.powerPreference] -
* **WebGL Only.** A hint indicating what configuration of GPU is suitable for the WebGL context,
* can be `'default'`, `'high-performance'` or `'low-power'`.
* Setting to `'high-performance'` will prioritize rendering performance over power consumption,
* while setting to `'low-power'` will prioritize power saving over rendering performance.
* @param {boolean} [options.premultipliedAlpha=true] -
* **WebGL Only.** Whether the compositor will assume the drawing buffer contains colors with premultiplied alpha.
* @param {boolean} [options.preserveDrawingBuffer=false] -
* **WebGL Only.** Whether to enable drawing buffer preservation. If enabled, the drawing buffer will preserve
* its value until cleared or overwritten. Enable this if you need to call `toDataUrl` on the WebGL context.
* @param {Window|HTMLElement} [options.resizeTo] - Element to automatically resize stage to.
* @param {number} [options.resolution=PIXI.settings.RESOLUTION] -
* The resolution / device pixel ratio of the renderer.
* @param {boolean} [options.sharedLoader=false] - `true` to use PIXI.Loader.shared, `false` to create new Loader.
* @param {boolean} [options.sharedTicker=false] - `true` to use PIXI.Ticker.shared, `false` to create new ticker.
* If set to `false`, you cannot register a handler to occur before anything that runs on the shared ticker.
* The system ticker will always run before both the shared ticker and the app ticker.
* @param {boolean} [options.transparent] -
* **Deprecated since 6.0.0, Use `backgroundAlpha` instead.** \
* `true` sets `backgroundAlpha` to `0`, `false` sets `backgroundAlpha` to `1`.
* @param {boolean|'notMultiplied'} [options.useContextAlpha=true] -
* Pass-through value for canvas' context attribute `alpha`. This option is for cases where the
* canvas needs to be opaque, possibly for performance reasons on some older devices.
* If you want to set transparency, please use `backgroundAlpha`. \
* **WebGL Only:** When set to `'notMultiplied'`, the canvas' context attribute `alpha` will be
* set to `true` and `premultipliedAlpha` will be to `false`.
* @param {HTMLCanvasElement} [options.view=null] -
* The canvas to use as the view. If omitted, a new canvas will be created.
* @param {number} [options.width=800] - The width of the renderer's view.
*/
function Application(options) {
var _this = this;
/**
* The root display container that's rendered.
* @member {PIXI.Container}
*/
this.stage = new display.Container();
// The default options
options = Object.assign({
forceCanvas: false,
}, options);
this.renderer = core.autoDetectRenderer(options);
// install plugins here
Application._plugins.forEach(function (plugin) {
plugin.init.call(_this, options);
});
}
/**
* Use the {@link PIXI.extensions.add} API to register plugins.
* @deprecated since 6.5.0
* @static
* @param {PIXI.IApplicationPlugin} plugin - Plugin being installed
*/
Application.registerPlugin = function (plugin) {
utils.deprecation('6.5.0', 'Application.registerPlugin() is deprecated, use extensions.add()');
core.extensions.add({
type: core.ExtensionType.Application,
ref: plugin,
});
};
/** Render the current stage. */
Application.prototype.render = function () {
this.renderer.render(this.stage);
};
Object.defineProperty(Application.prototype, "view", {
/**
* Reference to the renderer's canvas element.
* @member {HTMLCanvasElement}
* @readonly
*/
get: function () {
return this.renderer.view;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Application.prototype, "screen", {
/**
* Reference to the renderer's screen rectangle. Its safe to use as `filterArea` or `hitArea` for the whole screen.
* @member {PIXI.Rectangle}
* @readonly
*/
get: function () {
return this.renderer.screen;
},
enumerable: false,
configurable: true
});
/**
* Destroy and don't use after this.
* @param {boolean} [removeView=false] - Automatically remove canvas from DOM.
* @param {object|boolean} [stageOptions] - Options parameter. A boolean will act as if all options
* have been set to that value
* @param {boolean} [stageOptions.children=false] - if set to true, all the children will have their destroy
* method called as well. 'stageOptions' will be passed on to those calls.
* @param {boolean} [stageOptions.texture=false] - Only used for child Sprites if stageOptions.children is set
* to true. Should it destroy the texture of the child sprite
* @param {boolean} [stageOptions.baseTexture=false] - Only used for child Sprites if stageOptions.children is set
* to true. Should it destroy the base texture of the child sprite
*/
Application.prototype.destroy = function (removeView, stageOptions) {
var _this = this;
// Destroy plugins in the opposite order
// which they were constructed
var plugins = Application._plugins.slice(0);
plugins.reverse();
plugins.forEach(function (plugin) {
plugin.destroy.call(_this);
});
this.stage.destroy(stageOptions);
this.stage = null;
this.renderer.destroy(removeView);
this.renderer = null;
};
/** Collection of installed plugins. */
Application._plugins = [];
return Application;
}());
core.extensions.handleByList(core.ExtensionType.Application, Application._plugins);
core.extensions.add(ResizePlugin);
exports.Application = Application;
exports.ResizePlugin = ResizePlugin;
Object.defineProperty(exports, '__esModule', { value: true });
return exports;
})({}, PIXI, PIXI, PIXI.utils);
Object.assign(this.PIXI, _pixi_app);
//# sourceMappingURL=app.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,9 @@
/*!
* @pixi/app - v6.5.10
* Compiled Thu, 06 Jul 2023 15:25:11 UTC
*
* @pixi/app is licensed under the MIT License.
* http://www.opensource.org/licenses/mit-license
*/
this.PIXI=this.PIXI||{};var _pixi_app=function(e,i,n){"use strict";var t=function(){function e(){}return e.init=function(e){var i=this;Object.defineProperty(this,"resizeTo",{set:function(e){globalThis.removeEventListener("resize",this.queueResize),this._resizeTo=e,e&&(globalThis.addEventListener("resize",this.queueResize),this.resize())},get:function(){return this._resizeTo}}),this.queueResize=function(){i._resizeTo&&(i.cancelResize(),i._resizeId=requestAnimationFrame((function(){return i.resize()})))},this.cancelResize=function(){i._resizeId&&(cancelAnimationFrame(i._resizeId),i._resizeId=null)},this.resize=function(){if(i._resizeTo){var e,n;if(i.cancelResize(),i._resizeTo===globalThis.window)e=globalThis.innerWidth,n=globalThis.innerHeight;else{var t=i._resizeTo;e=t.clientWidth,n=t.clientHeight}i.renderer.resize(e,n)}},this._resizeId=null,this._resizeTo=null,this.resizeTo=e.resizeTo||null},e.destroy=function(){globalThis.removeEventListener("resize",this.queueResize),this.cancelResize(),this.cancelResize=null,this.queueResize=null,this.resizeTo=null,this.resize=null},e.extension=i.ExtensionType.Application,e}(),s=function(){function e(t){var s=this;this.stage=new n.Container,t=Object.assign({forceCanvas:!1},t),this.renderer=i.autoDetectRenderer(t),e._plugins.forEach((function(e){e.init.call(s,t)}))}return e.registerPlugin=function(e){i.extensions.add({type:i.ExtensionType.Application,ref:e})},e.prototype.render=function(){this.renderer.render(this.stage)},Object.defineProperty(e.prototype,"view",{get:function(){return this.renderer.view},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"screen",{get:function(){return this.renderer.screen},enumerable:!1,configurable:!0}),e.prototype.destroy=function(i,n){var t=this,s=e._plugins.slice(0);s.reverse(),s.forEach((function(e){e.destroy.call(t)})),this.stage.destroy(n),this.stage=null,this.renderer.destroy(i),this.renderer=null},e._plugins=[],e}();return i.extensions.handleByList(i.ExtensionType.Application,s._plugins),i.extensions.add(t),e.Application=s,e.ResizePlugin=t,Object.defineProperty(e,"__esModule",{value:!0}),e}({},PIXI,PIXI);Object.assign(this.PIXI,_pixi_app);
//# sourceMappingURL=app.min.js.map

File diff suppressed because one or more lines are too long

291
live2d/node_modules/@pixi/app/dist/cjs/app.js generated vendored Normal file
View File

@@ -0,0 +1,291 @@
/*!
* @pixi/app - v6.5.10
* Compiled Thu, 06 Jul 2023 15:25:11 UTC
*
* @pixi/app is licensed under the MIT License.
* http://www.opensource.org/licenses/mit-license
*/
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var core = require('@pixi/core');
var display = require('@pixi/display');
var utils = require('@pixi/utils');
/**
* Middleware for for Application's resize functionality
* @private
* @class
*/
var ResizePlugin = /** @class */ (function () {
function ResizePlugin() {
}
/**
* Initialize the plugin with scope of application instance
* @static
* @private
* @param {object} [options] - See application options
*/
ResizePlugin.init = function (options) {
var _this = this;
Object.defineProperty(this, 'resizeTo',
/**
* The HTML element or window to automatically resize the
* renderer's view element to match width and height.
* @member {Window|HTMLElement}
* @name resizeTo
* @memberof PIXI.Application#
*/
{
set: function (dom) {
globalThis.removeEventListener('resize', this.queueResize);
this._resizeTo = dom;
if (dom) {
globalThis.addEventListener('resize', this.queueResize);
this.resize();
}
},
get: function () {
return this._resizeTo;
},
});
/**
* Resize is throttled, so it's safe to call this multiple times per frame and it'll
* only be called once.
* @memberof PIXI.Application#
* @method queueResize
* @private
*/
this.queueResize = function () {
if (!_this._resizeTo) {
return;
}
_this.cancelResize();
// // Throttle resize events per raf
_this._resizeId = requestAnimationFrame(function () { return _this.resize(); });
};
/**
* Cancel the resize queue.
* @memberof PIXI.Application#
* @method cancelResize
* @private
*/
this.cancelResize = function () {
if (_this._resizeId) {
cancelAnimationFrame(_this._resizeId);
_this._resizeId = null;
}
};
/**
* Execute an immediate resize on the renderer, this is not
* throttled and can be expensive to call many times in a row.
* Will resize only if `resizeTo` property is set.
* @memberof PIXI.Application#
* @method resize
*/
this.resize = function () {
if (!_this._resizeTo) {
return;
}
// clear queue resize
_this.cancelResize();
var width;
var height;
// Resize to the window
if (_this._resizeTo === globalThis.window) {
width = globalThis.innerWidth;
height = globalThis.innerHeight;
}
// Resize to other HTML entities
else {
var _a = _this._resizeTo, clientWidth = _a.clientWidth, clientHeight = _a.clientHeight;
width = clientWidth;
height = clientHeight;
}
_this.renderer.resize(width, height);
};
// On resize
this._resizeId = null;
this._resizeTo = null;
this.resizeTo = options.resizeTo || null;
};
/**
* Clean up the ticker, scoped to application
* @static
* @private
*/
ResizePlugin.destroy = function () {
globalThis.removeEventListener('resize', this.queueResize);
this.cancelResize();
this.cancelResize = null;
this.queueResize = null;
this.resizeTo = null;
this.resize = null;
};
/** @ignore */
ResizePlugin.extension = core.ExtensionType.Application;
return ResizePlugin;
}());
/**
* Convenience class to create a new PIXI application.
*
* This class automatically creates the renderer, ticker and root container.
* @example
* // Create the application
* const app = new PIXI.Application();
*
* // Add the view to the DOM
* document.body.appendChild(app.view);
*
* // ex, add display objects
* app.stage.addChild(PIXI.Sprite.from('something.png'));
* @class
* @memberof PIXI
*/
var Application = /** @class */ (function () {
/**
* @param {PIXI.IApplicationOptions} [options] - The optional application and renderer parameters.
* @param {boolean} [options.antialias=false] -
* **WebGL Only.** Whether to enable anti-aliasing. This may affect performance.
* @param {boolean} [options.autoDensity=false] -
* Whether the CSS dimensions of the renderer's view should be resized automatically.
* @param {boolean} [options.autoStart=true] - Automatically starts the rendering after the construction.
* **Note**: Setting this parameter to false does NOT stop the shared ticker even if you set
* `options.sharedTicker` to `true` in case that it is already started. Stop it by your own.
* @param {number} [options.backgroundAlpha=1] -
* Transparency of the background color, value from `0` (fully transparent) to `1` (fully opaque).
* @param {number} [options.backgroundColor=0x000000] -
* The background color used to clear the canvas. It accepts hex numbers (e.g. `0xff0000`).
* @param {boolean} [options.clearBeforeRender=true] - Whether to clear the canvas before new render passes.
* @param {PIXI.IRenderingContext} [options.context] - **WebGL Only.** User-provided WebGL rendering context object.
* @param {boolean} [options.forceCanvas=false] -
* Force using {@link PIXI.CanvasRenderer}, even if WebGL is available. This option only is available when
* using **pixi.js-legacy** or **@pixi/canvas-renderer** packages, otherwise it is ignored.
* @param {number} [options.height=600] - The height of the renderer's view.
* @param {string} [options.powerPreference] -
* **WebGL Only.** A hint indicating what configuration of GPU is suitable for the WebGL context,
* can be `'default'`, `'high-performance'` or `'low-power'`.
* Setting to `'high-performance'` will prioritize rendering performance over power consumption,
* while setting to `'low-power'` will prioritize power saving over rendering performance.
* @param {boolean} [options.premultipliedAlpha=true] -
* **WebGL Only.** Whether the compositor will assume the drawing buffer contains colors with premultiplied alpha.
* @param {boolean} [options.preserveDrawingBuffer=false] -
* **WebGL Only.** Whether to enable drawing buffer preservation. If enabled, the drawing buffer will preserve
* its value until cleared or overwritten. Enable this if you need to call `toDataUrl` on the WebGL context.
* @param {Window|HTMLElement} [options.resizeTo] - Element to automatically resize stage to.
* @param {number} [options.resolution=PIXI.settings.RESOLUTION] -
* The resolution / device pixel ratio of the renderer.
* @param {boolean} [options.sharedLoader=false] - `true` to use PIXI.Loader.shared, `false` to create new Loader.
* @param {boolean} [options.sharedTicker=false] - `true` to use PIXI.Ticker.shared, `false` to create new ticker.
* If set to `false`, you cannot register a handler to occur before anything that runs on the shared ticker.
* The system ticker will always run before both the shared ticker and the app ticker.
* @param {boolean} [options.transparent] -
* **Deprecated since 6.0.0, Use `backgroundAlpha` instead.** \
* `true` sets `backgroundAlpha` to `0`, `false` sets `backgroundAlpha` to `1`.
* @param {boolean|'notMultiplied'} [options.useContextAlpha=true] -
* Pass-through value for canvas' context attribute `alpha`. This option is for cases where the
* canvas needs to be opaque, possibly for performance reasons on some older devices.
* If you want to set transparency, please use `backgroundAlpha`. \
* **WebGL Only:** When set to `'notMultiplied'`, the canvas' context attribute `alpha` will be
* set to `true` and `premultipliedAlpha` will be to `false`.
* @param {HTMLCanvasElement} [options.view=null] -
* The canvas to use as the view. If omitted, a new canvas will be created.
* @param {number} [options.width=800] - The width of the renderer's view.
*/
function Application(options) {
var _this = this;
/**
* The root display container that's rendered.
* @member {PIXI.Container}
*/
this.stage = new display.Container();
// The default options
options = Object.assign({
forceCanvas: false,
}, options);
this.renderer = core.autoDetectRenderer(options);
// install plugins here
Application._plugins.forEach(function (plugin) {
plugin.init.call(_this, options);
});
}
/**
* Use the {@link PIXI.extensions.add} API to register plugins.
* @deprecated since 6.5.0
* @static
* @param {PIXI.IApplicationPlugin} plugin - Plugin being installed
*/
Application.registerPlugin = function (plugin) {
utils.deprecation('6.5.0', 'Application.registerPlugin() is deprecated, use extensions.add()');
core.extensions.add({
type: core.ExtensionType.Application,
ref: plugin,
});
};
/** Render the current stage. */
Application.prototype.render = function () {
this.renderer.render(this.stage);
};
Object.defineProperty(Application.prototype, "view", {
/**
* Reference to the renderer's canvas element.
* @member {HTMLCanvasElement}
* @readonly
*/
get: function () {
return this.renderer.view;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Application.prototype, "screen", {
/**
* Reference to the renderer's screen rectangle. Its safe to use as `filterArea` or `hitArea` for the whole screen.
* @member {PIXI.Rectangle}
* @readonly
*/
get: function () {
return this.renderer.screen;
},
enumerable: false,
configurable: true
});
/**
* Destroy and don't use after this.
* @param {boolean} [removeView=false] - Automatically remove canvas from DOM.
* @param {object|boolean} [stageOptions] - Options parameter. A boolean will act as if all options
* have been set to that value
* @param {boolean} [stageOptions.children=false] - if set to true, all the children will have their destroy
* method called as well. 'stageOptions' will be passed on to those calls.
* @param {boolean} [stageOptions.texture=false] - Only used for child Sprites if stageOptions.children is set
* to true. Should it destroy the texture of the child sprite
* @param {boolean} [stageOptions.baseTexture=false] - Only used for child Sprites if stageOptions.children is set
* to true. Should it destroy the base texture of the child sprite
*/
Application.prototype.destroy = function (removeView, stageOptions) {
var _this = this;
// Destroy plugins in the opposite order
// which they were constructed
var plugins = Application._plugins.slice(0);
plugins.reverse();
plugins.forEach(function (plugin) {
plugin.destroy.call(_this);
});
this.stage.destroy(stageOptions);
this.stage = null;
this.renderer.destroy(removeView);
this.renderer = null;
};
/** Collection of installed plugins. */
Application._plugins = [];
return Application;
}());
core.extensions.handleByList(core.ExtensionType.Application, Application._plugins);
core.extensions.add(ResizePlugin);
exports.Application = Application;
exports.ResizePlugin = ResizePlugin;
//# sourceMappingURL=app.js.map

1
live2d/node_modules/@pixi/app/dist/cjs/app.js.map generated vendored Normal file

File diff suppressed because one or more lines are too long

9
live2d/node_modules/@pixi/app/dist/cjs/app.min.js generated vendored Normal file
View File

@@ -0,0 +1,9 @@
/*!
* @pixi/app - v6.5.10
* Compiled Thu, 06 Jul 2023 15:25:11 UTC
*
* @pixi/app is licensed under the MIT License.
* http://www.opensource.org/licenses/mit-license
*/
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("@pixi/core"),i=require("@pixi/display"),n=function(){function i(){}return i.init=function(e){var i=this;Object.defineProperty(this,"resizeTo",{set:function(e){globalThis.removeEventListener("resize",this.queueResize),this._resizeTo=e,e&&(globalThis.addEventListener("resize",this.queueResize),this.resize())},get:function(){return this._resizeTo}}),this.queueResize=function(){i._resizeTo&&(i.cancelResize(),i._resizeId=requestAnimationFrame((function(){return i.resize()})))},this.cancelResize=function(){i._resizeId&&(cancelAnimationFrame(i._resizeId),i._resizeId=null)},this.resize=function(){if(i._resizeTo){var e,n;if(i.cancelResize(),i._resizeTo===globalThis.window)e=globalThis.innerWidth,n=globalThis.innerHeight;else{var t=i._resizeTo;e=t.clientWidth,n=t.clientHeight}i.renderer.resize(e,n)}},this._resizeId=null,this._resizeTo=null,this.resizeTo=e.resizeTo||null},i.destroy=function(){globalThis.removeEventListener("resize",this.queueResize),this.cancelResize(),this.cancelResize=null,this.queueResize=null,this.resizeTo=null,this.resize=null},i.extension=e.ExtensionType.Application,i}(),t=function(){function n(t){var r=this;this.stage=new i.Container,t=Object.assign({forceCanvas:!1},t),this.renderer=e.autoDetectRenderer(t),n._plugins.forEach((function(e){e.init.call(r,t)}))}return n.registerPlugin=function(i){e.extensions.add({type:e.ExtensionType.Application,ref:i})},n.prototype.render=function(){this.renderer.render(this.stage)},Object.defineProperty(n.prototype,"view",{get:function(){return this.renderer.view},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"screen",{get:function(){return this.renderer.screen},enumerable:!1,configurable:!0}),n.prototype.destroy=function(e,i){var t=this,r=n._plugins.slice(0);r.reverse(),r.forEach((function(e){e.destroy.call(t)})),this.stage.destroy(i),this.stage=null,this.renderer.destroy(e),this.renderer=null},n._plugins=[],n}();e.extensions.handleByList(e.ExtensionType.Application,t._plugins),e.extensions.add(n),exports.Application=t,exports.ResizePlugin=n;
//# sourceMappingURL=app.min.js.map

File diff suppressed because one or more lines are too long

9
live2d/node_modules/@pixi/app/dist/esm/app.min.mjs generated vendored Normal file
View File

@@ -0,0 +1,9 @@
/*!
* @pixi/app - v6.5.10
* Compiled Thu, 06 Jul 2023 15:25:11 UTC
*
* @pixi/app is licensed under the MIT License.
* http://www.opensource.org/licenses/mit-license
*/
import{ExtensionType as e,extensions as i,autoDetectRenderer as r}from"@pixi/core";import{Container as n}from"@pixi/display";var t=function(){function i(){}return i.init=function(e){var i=this;Object.defineProperty(this,"resizeTo",{set:function(e){globalThis.removeEventListener("resize",this.queueResize),this._resizeTo=e,e&&(globalThis.addEventListener("resize",this.queueResize),this.resize())},get:function(){return this._resizeTo}}),this.queueResize=function(){i._resizeTo&&(i.cancelResize(),i._resizeId=requestAnimationFrame((function(){return i.resize()})))},this.cancelResize=function(){i._resizeId&&(cancelAnimationFrame(i._resizeId),i._resizeId=null)},this.resize=function(){if(i._resizeTo){var e,r;if(i.cancelResize(),i._resizeTo===globalThis.window)e=globalThis.innerWidth,r=globalThis.innerHeight;else{var n=i._resizeTo;e=n.clientWidth,r=n.clientHeight}i.renderer.resize(e,r)}},this._resizeId=null,this._resizeTo=null,this.resizeTo=e.resizeTo||null},i.destroy=function(){globalThis.removeEventListener("resize",this.queueResize),this.cancelResize(),this.cancelResize=null,this.queueResize=null,this.resizeTo=null,this.resize=null},i.extension=e.Application,i}(),s=function(){function t(e){var i=this;this.stage=new n,e=Object.assign({forceCanvas:!1},e),this.renderer=r(e),t._plugins.forEach((function(r){r.init.call(i,e)}))}return t.registerPlugin=function(r){i.add({type:e.Application,ref:r})},t.prototype.render=function(){this.renderer.render(this.stage)},Object.defineProperty(t.prototype,"view",{get:function(){return this.renderer.view},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"screen",{get:function(){return this.renderer.screen},enumerable:!1,configurable:!0}),t.prototype.destroy=function(e,i){var r=this,n=t._plugins.slice(0);n.reverse(),n.forEach((function(e){e.destroy.call(r)})),this.stage.destroy(i),this.stage=null,this.renderer.destroy(e),this.renderer=null},t._plugins=[],t}();i.handleByList(e.Application,s._plugins),i.add(t);export{s as Application,t as ResizePlugin};
//# sourceMappingURL=app.min.mjs.map

File diff suppressed because one or more lines are too long

286
live2d/node_modules/@pixi/app/dist/esm/app.mjs generated vendored Normal file
View File

@@ -0,0 +1,286 @@
/*!
* @pixi/app - v6.5.10
* Compiled Thu, 06 Jul 2023 15:25:11 UTC
*
* @pixi/app is licensed under the MIT License.
* http://www.opensource.org/licenses/mit-license
*/
import { ExtensionType, extensions, autoDetectRenderer } from '@pixi/core';
import { Container } from '@pixi/display';
import { deprecation } from '@pixi/utils';
/**
* Middleware for for Application's resize functionality
* @private
* @class
*/
var ResizePlugin = /** @class */ (function () {
function ResizePlugin() {
}
/**
* Initialize the plugin with scope of application instance
* @static
* @private
* @param {object} [options] - See application options
*/
ResizePlugin.init = function (options) {
var _this = this;
Object.defineProperty(this, 'resizeTo',
/**
* The HTML element or window to automatically resize the
* renderer's view element to match width and height.
* @member {Window|HTMLElement}
* @name resizeTo
* @memberof PIXI.Application#
*/
{
set: function (dom) {
globalThis.removeEventListener('resize', this.queueResize);
this._resizeTo = dom;
if (dom) {
globalThis.addEventListener('resize', this.queueResize);
this.resize();
}
},
get: function () {
return this._resizeTo;
},
});
/**
* Resize is throttled, so it's safe to call this multiple times per frame and it'll
* only be called once.
* @memberof PIXI.Application#
* @method queueResize
* @private
*/
this.queueResize = function () {
if (!_this._resizeTo) {
return;
}
_this.cancelResize();
// // Throttle resize events per raf
_this._resizeId = requestAnimationFrame(function () { return _this.resize(); });
};
/**
* Cancel the resize queue.
* @memberof PIXI.Application#
* @method cancelResize
* @private
*/
this.cancelResize = function () {
if (_this._resizeId) {
cancelAnimationFrame(_this._resizeId);
_this._resizeId = null;
}
};
/**
* Execute an immediate resize on the renderer, this is not
* throttled and can be expensive to call many times in a row.
* Will resize only if `resizeTo` property is set.
* @memberof PIXI.Application#
* @method resize
*/
this.resize = function () {
if (!_this._resizeTo) {
return;
}
// clear queue resize
_this.cancelResize();
var width;
var height;
// Resize to the window
if (_this._resizeTo === globalThis.window) {
width = globalThis.innerWidth;
height = globalThis.innerHeight;
}
// Resize to other HTML entities
else {
var _a = _this._resizeTo, clientWidth = _a.clientWidth, clientHeight = _a.clientHeight;
width = clientWidth;
height = clientHeight;
}
_this.renderer.resize(width, height);
};
// On resize
this._resizeId = null;
this._resizeTo = null;
this.resizeTo = options.resizeTo || null;
};
/**
* Clean up the ticker, scoped to application
* @static
* @private
*/
ResizePlugin.destroy = function () {
globalThis.removeEventListener('resize', this.queueResize);
this.cancelResize();
this.cancelResize = null;
this.queueResize = null;
this.resizeTo = null;
this.resize = null;
};
/** @ignore */
ResizePlugin.extension = ExtensionType.Application;
return ResizePlugin;
}());
/**
* Convenience class to create a new PIXI application.
*
* This class automatically creates the renderer, ticker and root container.
* @example
* // Create the application
* const app = new PIXI.Application();
*
* // Add the view to the DOM
* document.body.appendChild(app.view);
*
* // ex, add display objects
* app.stage.addChild(PIXI.Sprite.from('something.png'));
* @class
* @memberof PIXI
*/
var Application = /** @class */ (function () {
/**
* @param {PIXI.IApplicationOptions} [options] - The optional application and renderer parameters.
* @param {boolean} [options.antialias=false] -
* **WebGL Only.** Whether to enable anti-aliasing. This may affect performance.
* @param {boolean} [options.autoDensity=false] -
* Whether the CSS dimensions of the renderer's view should be resized automatically.
* @param {boolean} [options.autoStart=true] - Automatically starts the rendering after the construction.
* **Note**: Setting this parameter to false does NOT stop the shared ticker even if you set
* `options.sharedTicker` to `true` in case that it is already started. Stop it by your own.
* @param {number} [options.backgroundAlpha=1] -
* Transparency of the background color, value from `0` (fully transparent) to `1` (fully opaque).
* @param {number} [options.backgroundColor=0x000000] -
* The background color used to clear the canvas. It accepts hex numbers (e.g. `0xff0000`).
* @param {boolean} [options.clearBeforeRender=true] - Whether to clear the canvas before new render passes.
* @param {PIXI.IRenderingContext} [options.context] - **WebGL Only.** User-provided WebGL rendering context object.
* @param {boolean} [options.forceCanvas=false] -
* Force using {@link PIXI.CanvasRenderer}, even if WebGL is available. This option only is available when
* using **pixi.js-legacy** or **@pixi/canvas-renderer** packages, otherwise it is ignored.
* @param {number} [options.height=600] - The height of the renderer's view.
* @param {string} [options.powerPreference] -
* **WebGL Only.** A hint indicating what configuration of GPU is suitable for the WebGL context,
* can be `'default'`, `'high-performance'` or `'low-power'`.
* Setting to `'high-performance'` will prioritize rendering performance over power consumption,
* while setting to `'low-power'` will prioritize power saving over rendering performance.
* @param {boolean} [options.premultipliedAlpha=true] -
* **WebGL Only.** Whether the compositor will assume the drawing buffer contains colors with premultiplied alpha.
* @param {boolean} [options.preserveDrawingBuffer=false] -
* **WebGL Only.** Whether to enable drawing buffer preservation. If enabled, the drawing buffer will preserve
* its value until cleared or overwritten. Enable this if you need to call `toDataUrl` on the WebGL context.
* @param {Window|HTMLElement} [options.resizeTo] - Element to automatically resize stage to.
* @param {number} [options.resolution=PIXI.settings.RESOLUTION] -
* The resolution / device pixel ratio of the renderer.
* @param {boolean} [options.sharedLoader=false] - `true` to use PIXI.Loader.shared, `false` to create new Loader.
* @param {boolean} [options.sharedTicker=false] - `true` to use PIXI.Ticker.shared, `false` to create new ticker.
* If set to `false`, you cannot register a handler to occur before anything that runs on the shared ticker.
* The system ticker will always run before both the shared ticker and the app ticker.
* @param {boolean} [options.transparent] -
* **Deprecated since 6.0.0, Use `backgroundAlpha` instead.** \
* `true` sets `backgroundAlpha` to `0`, `false` sets `backgroundAlpha` to `1`.
* @param {boolean|'notMultiplied'} [options.useContextAlpha=true] -
* Pass-through value for canvas' context attribute `alpha`. This option is for cases where the
* canvas needs to be opaque, possibly for performance reasons on some older devices.
* If you want to set transparency, please use `backgroundAlpha`. \
* **WebGL Only:** When set to `'notMultiplied'`, the canvas' context attribute `alpha` will be
* set to `true` and `premultipliedAlpha` will be to `false`.
* @param {HTMLCanvasElement} [options.view=null] -
* The canvas to use as the view. If omitted, a new canvas will be created.
* @param {number} [options.width=800] - The width of the renderer's view.
*/
function Application(options) {
var _this = this;
/**
* The root display container that's rendered.
* @member {PIXI.Container}
*/
this.stage = new Container();
// The default options
options = Object.assign({
forceCanvas: false,
}, options);
this.renderer = autoDetectRenderer(options);
// install plugins here
Application._plugins.forEach(function (plugin) {
plugin.init.call(_this, options);
});
}
/**
* Use the {@link PIXI.extensions.add} API to register plugins.
* @deprecated since 6.5.0
* @static
* @param {PIXI.IApplicationPlugin} plugin - Plugin being installed
*/
Application.registerPlugin = function (plugin) {
deprecation('6.5.0', 'Application.registerPlugin() is deprecated, use extensions.add()');
extensions.add({
type: ExtensionType.Application,
ref: plugin,
});
};
/** Render the current stage. */
Application.prototype.render = function () {
this.renderer.render(this.stage);
};
Object.defineProperty(Application.prototype, "view", {
/**
* Reference to the renderer's canvas element.
* @member {HTMLCanvasElement}
* @readonly
*/
get: function () {
return this.renderer.view;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Application.prototype, "screen", {
/**
* Reference to the renderer's screen rectangle. Its safe to use as `filterArea` or `hitArea` for the whole screen.
* @member {PIXI.Rectangle}
* @readonly
*/
get: function () {
return this.renderer.screen;
},
enumerable: false,
configurable: true
});
/**
* Destroy and don't use after this.
* @param {boolean} [removeView=false] - Automatically remove canvas from DOM.
* @param {object|boolean} [stageOptions] - Options parameter. A boolean will act as if all options
* have been set to that value
* @param {boolean} [stageOptions.children=false] - if set to true, all the children will have their destroy
* method called as well. 'stageOptions' will be passed on to those calls.
* @param {boolean} [stageOptions.texture=false] - Only used for child Sprites if stageOptions.children is set
* to true. Should it destroy the texture of the child sprite
* @param {boolean} [stageOptions.baseTexture=false] - Only used for child Sprites if stageOptions.children is set
* to true. Should it destroy the base texture of the child sprite
*/
Application.prototype.destroy = function (removeView, stageOptions) {
var _this = this;
// Destroy plugins in the opposite order
// which they were constructed
var plugins = Application._plugins.slice(0);
plugins.reverse();
plugins.forEach(function (plugin) {
plugin.destroy.call(_this);
});
this.stage.destroy(stageOptions);
this.stage = null;
this.renderer.destroy(removeView);
this.renderer = null;
};
/** Collection of installed plugins. */
Application._plugins = [];
return Application;
}());
extensions.handleByList(ExtensionType.Application, Application._plugins);
extensions.add(ResizePlugin);
export { Application, ResizePlugin };
//# sourceMappingURL=app.mjs.map

1
live2d/node_modules/@pixi/app/dist/esm/app.mjs.map generated vendored Normal file

File diff suppressed because one or more lines are too long

183
live2d/node_modules/@pixi/app/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,183 @@
/// <reference path="./global.d.ts" />
import type { AbstractRenderer } from '@pixi/core';
import { Container } from '@pixi/display';
import type { ExtensionMetadata } from '@pixi/core';
import type { IDestroyOptions } from '@pixi/display';
import type { IRendererOptionsAuto } from '@pixi/core';
import type { Rectangle } from '@pixi/math';
import type { Renderer } from '@pixi/core';
export declare interface Application extends GlobalMixins.Application {
}
/**
* Convenience class to create a new PIXI application.
*
* This class automatically creates the renderer, ticker and root container.
* @example
* // Create the application
* const app = new PIXI.Application();
*
* // Add the view to the DOM
* document.body.appendChild(app.view);
*
* // ex, add display objects
* app.stage.addChild(PIXI.Sprite.from('something.png'));
* @class
* @memberof PIXI
*/
export declare class Application {
/** Collection of installed plugins. */
static _plugins: IApplicationPlugin[];
/**
* The root display container that's rendered.
* @member {PIXI.Container}
*/
stage: Container;
/**
* WebGL renderer if available, otherwise CanvasRenderer.
* @member {PIXI.Renderer|PIXI.CanvasRenderer}
*/
renderer: Renderer | AbstractRenderer;
/**
* @param {PIXI.IApplicationOptions} [options] - The optional application and renderer parameters.
* @param {boolean} [options.antialias=false] -
* **WebGL Only.** Whether to enable anti-aliasing. This may affect performance.
* @param {boolean} [options.autoDensity=false] -
* Whether the CSS dimensions of the renderer's view should be resized automatically.
* @param {boolean} [options.autoStart=true] - Automatically starts the rendering after the construction.
* **Note**: Setting this parameter to false does NOT stop the shared ticker even if you set
* `options.sharedTicker` to `true` in case that it is already started. Stop it by your own.
* @param {number} [options.backgroundAlpha=1] -
* Transparency of the background color, value from `0` (fully transparent) to `1` (fully opaque).
* @param {number} [options.backgroundColor=0x000000] -
* The background color used to clear the canvas. It accepts hex numbers (e.g. `0xff0000`).
* @param {boolean} [options.clearBeforeRender=true] - Whether to clear the canvas before new render passes.
* @param {PIXI.IRenderingContext} [options.context] - **WebGL Only.** User-provided WebGL rendering context object.
* @param {boolean} [options.forceCanvas=false] -
* Force using {@link PIXI.CanvasRenderer}, even if WebGL is available. This option only is available when
* using **pixi.js-legacy** or **@pixi/canvas-renderer** packages, otherwise it is ignored.
* @param {number} [options.height=600] - The height of the renderer's view.
* @param {string} [options.powerPreference] -
* **WebGL Only.** A hint indicating what configuration of GPU is suitable for the WebGL context,
* can be `'default'`, `'high-performance'` or `'low-power'`.
* Setting to `'high-performance'` will prioritize rendering performance over power consumption,
* while setting to `'low-power'` will prioritize power saving over rendering performance.
* @param {boolean} [options.premultipliedAlpha=true] -
* **WebGL Only.** Whether the compositor will assume the drawing buffer contains colors with premultiplied alpha.
* @param {boolean} [options.preserveDrawingBuffer=false] -
* **WebGL Only.** Whether to enable drawing buffer preservation. If enabled, the drawing buffer will preserve
* its value until cleared or overwritten. Enable this if you need to call `toDataUrl` on the WebGL context.
* @param {Window|HTMLElement} [options.resizeTo] - Element to automatically resize stage to.
* @param {number} [options.resolution=PIXI.settings.RESOLUTION] -
* The resolution / device pixel ratio of the renderer.
* @param {boolean} [options.sharedLoader=false] - `true` to use PIXI.Loader.shared, `false` to create new Loader.
* @param {boolean} [options.sharedTicker=false] - `true` to use PIXI.Ticker.shared, `false` to create new ticker.
* If set to `false`, you cannot register a handler to occur before anything that runs on the shared ticker.
* The system ticker will always run before both the shared ticker and the app ticker.
* @param {boolean} [options.transparent] -
* **Deprecated since 6.0.0, Use `backgroundAlpha` instead.** \
* `true` sets `backgroundAlpha` to `0`, `false` sets `backgroundAlpha` to `1`.
* @param {boolean|'notMultiplied'} [options.useContextAlpha=true] -
* Pass-through value for canvas' context attribute `alpha`. This option is for cases where the
* canvas needs to be opaque, possibly for performance reasons on some older devices.
* If you want to set transparency, please use `backgroundAlpha`. \
* **WebGL Only:** When set to `'notMultiplied'`, the canvas' context attribute `alpha` will be
* set to `true` and `premultipliedAlpha` will be to `false`.
* @param {HTMLCanvasElement} [options.view=null] -
* The canvas to use as the view. If omitted, a new canvas will be created.
* @param {number} [options.width=800] - The width of the renderer's view.
*/
constructor(options?: IApplicationOptions);
/**
* Use the {@link PIXI.extensions.add} API to register plugins.
* @deprecated since 6.5.0
* @static
* @param {PIXI.IApplicationPlugin} plugin - Plugin being installed
*/
static registerPlugin(plugin: IApplicationPlugin): void;
/** Render the current stage. */
render(): void;
/**
* Reference to the renderer's canvas element.
* @member {HTMLCanvasElement}
* @readonly
*/
get view(): HTMLCanvasElement;
/**
* Reference to the renderer's screen rectangle. Its safe to use as `filterArea` or `hitArea` for the whole screen.
* @member {PIXI.Rectangle}
* @readonly
*/
get screen(): Rectangle;
/**
* Destroy and don't use after this.
* @param {boolean} [removeView=false] - Automatically remove canvas from DOM.
* @param {object|boolean} [stageOptions] - Options parameter. A boolean will act as if all options
* have been set to that value
* @param {boolean} [stageOptions.children=false] - if set to true, all the children will have their destroy
* method called as well. 'stageOptions' will be passed on to those calls.
* @param {boolean} [stageOptions.texture=false] - Only used for child Sprites if stageOptions.children is set
* to true. Should it destroy the texture of the child sprite
* @param {boolean} [stageOptions.baseTexture=false] - Only used for child Sprites if stageOptions.children is set
* to true. Should it destroy the base texture of the child sprite
*/
destroy(removeView?: boolean, stageOptions?: IDestroyOptions | boolean): void;
}
/**
* Application options supplied to constructor.
* @memberof PIXI
*/
export declare interface IApplicationOptions extends IRendererOptionsAuto, GlobalMixins.IApplicationOptions {
}
/**
* Any plugin that's usable for Application should contain these methods.
* @memberof PIXI
*/
export declare interface IApplicationPlugin {
/**
* Called when Application is constructed, scoped to Application instance.
* Passes in `options` as the only argument, which are Application constructor options.
* @param {object} options - Application options.
*/
init(options: IApplicationOptions): void;
/** Called when destroying Application, scoped to Application instance. */
destroy(): void;
}
declare type ResizeableRenderer = Pick<Renderer, 'resize'>;
/**
* Middleware for for Application's resize functionality
* @private
* @class
*/
export declare class ResizePlugin {
/** @ignore */
static extension: ExtensionMetadata;
static resizeTo: Window | HTMLElement;
static resize: () => void;
static renderer: ResizeableRenderer;
static queueResize: () => void;
private static _resizeId;
private static _resizeTo;
private static cancelResize;
/**
* Initialize the plugin with scope of application instance
* @static
* @private
* @param {object} [options] - See application options
*/
static init(options?: IApplicationOptions): void;
/**
* Clean up the ticker, scoped to application
* @static
* @private
*/
static destroy(): void;
}
export { }

View File

@@ -1,88 +0,0 @@
import { Container } from '@pixi/display';
import type { ICanvas, IRenderer, IRendererOptionsAuto, Rectangle } from '@pixi/core';
import type { IDestroyOptions } from '@pixi/display';
/**
* Any plugin that's usable for Application should contain these methods.
* @memberof PIXI
*/
export interface IApplicationPlugin {
/**
* Called when Application is constructed, scoped to Application instance.
* Passes in `options` as the only argument, which are Application constructor options.
* @param {object} options - Application options.
*/
init(options: Partial<IApplicationOptions>): void;
/** Called when destroying Application, scoped to Application instance. */
destroy(): void;
}
/**
* Application options supplied to constructor.
* @memberof PIXI
*/
export interface IApplicationOptions extends IRendererOptionsAuto, GlobalMixins.IApplicationOptions {
}
export interface Application extends GlobalMixins.Application {
}
/**
* Convenience class to create a new PixiJS application.
*
* This class automatically creates the renderer, ticker and root container.
* @example
* import { Application, Sprite } from 'pixi.js';
*
* // Create the application
* const app = new Application();
*
* // Add the view to the DOM
* document.body.appendChild(app.view);
*
* // ex, add display objects
* app.stage.addChild(Sprite.from('something.png'));
* @class
* @memberof PIXI
*/
export declare class Application<VIEW extends ICanvas = ICanvas> {
/** Collection of installed plugins. */
static _plugins: IApplicationPlugin[];
/**
* The root display container that's rendered.
* @member {PIXI.Container}
*/
stage: Container;
/**
* WebGL renderer if available, otherwise CanvasRenderer.
* @member {PIXI.Renderer|PIXI.CanvasRenderer}
*/
renderer: IRenderer<VIEW>;
/**
* @param options - The optional application and renderer parameters.
*/
constructor(options?: Partial<IApplicationOptions>);
/** Render the current stage. */
render(): void;
/**
* Reference to the renderer's canvas element.
* @member {PIXI.ICanvas}
* @readonly
*/
get view(): VIEW;
/**
* Reference to the renderer's screen rectangle. Its safe to use as `filterArea` or `hitArea` for the whole screen.
* @member {PIXI.Rectangle}
* @readonly
*/
get screen(): Rectangle;
/**
* Destroy and don't use after this.
* @param {boolean} [removeView=false] - Automatically remove canvas from DOM.
* @param {object|boolean} [stageOptions] - Options parameter. A boolean will act as if all options
* have been set to that value
* @param {boolean} [stageOptions.children=false] - if set to true, all the children will have their destroy
* method called as well. 'stageOptions' will be passed on to those calls.
* @param {boolean} [stageOptions.texture=false] - Only used for child Sprites if stageOptions.children is set
* to true. Should it destroy the texture of the child sprite
* @param {boolean} [stageOptions.baseTexture=false] - Only used for child Sprites if stageOptions.children is set
* to true. Should it destroy the base texture of the child sprite
*/
destroy(removeView?: boolean, stageOptions?: IDestroyOptions | boolean): void;
}

View File

@@ -1,57 +0,0 @@
"use strict";
var core = require("@pixi/core"), display = require("@pixi/display");
const _Application = class _Application2 {
/**
* @param options - The optional application and renderer parameters.
*/
constructor(options) {
this.stage = new display.Container(), options = Object.assign({
forceCanvas: !1
}, options), this.renderer = core.autoDetectRenderer(options), _Application2._plugins.forEach((plugin) => {
plugin.init.call(this, options);
});
}
/** Render the current stage. */
render() {
this.renderer.render(this.stage);
}
/**
* Reference to the renderer's canvas element.
* @member {PIXI.ICanvas}
* @readonly
*/
get view() {
return this.renderer?.view;
}
/**
* Reference to the renderer's screen rectangle. Its safe to use as `filterArea` or `hitArea` for the whole screen.
* @member {PIXI.Rectangle}
* @readonly
*/
get screen() {
return this.renderer?.screen;
}
/**
* Destroy and don't use after this.
* @param {boolean} [removeView=false] - Automatically remove canvas from DOM.
* @param {object|boolean} [stageOptions] - Options parameter. A boolean will act as if all options
* have been set to that value
* @param {boolean} [stageOptions.children=false] - if set to true, all the children will have their destroy
* method called as well. 'stageOptions' will be passed on to those calls.
* @param {boolean} [stageOptions.texture=false] - Only used for child Sprites if stageOptions.children is set
* to true. Should it destroy the texture of the child sprite
* @param {boolean} [stageOptions.baseTexture=false] - Only used for child Sprites if stageOptions.children is set
* to true. Should it destroy the base texture of the child sprite
*/
destroy(removeView, stageOptions) {
const plugins = _Application2._plugins.slice(0);
plugins.reverse(), plugins.forEach((plugin) => {
plugin.destroy.call(this);
}), this.stage.destroy(stageOptions), this.stage = null, this.renderer.destroy(removeView), this.renderer = null;
}
};
_Application._plugins = [];
let Application = _Application;
core.extensions.handleByList(core.ExtensionType.Application, Application._plugins);
exports.Application = Application;
//# sourceMappingURL=Application.js.map

File diff suppressed because one or more lines are too long

View File

@@ -1,59 +0,0 @@
import { autoDetectRenderer, extensions, ExtensionType } from "@pixi/core";
import { Container } from "@pixi/display";
const _Application = class _Application2 {
/**
* @param options - The optional application and renderer parameters.
*/
constructor(options) {
this.stage = new Container(), options = Object.assign({
forceCanvas: !1
}, options), this.renderer = autoDetectRenderer(options), _Application2._plugins.forEach((plugin) => {
plugin.init.call(this, options);
});
}
/** Render the current stage. */
render() {
this.renderer.render(this.stage);
}
/**
* Reference to the renderer's canvas element.
* @member {PIXI.ICanvas}
* @readonly
*/
get view() {
return this.renderer?.view;
}
/**
* Reference to the renderer's screen rectangle. Its safe to use as `filterArea` or `hitArea` for the whole screen.
* @member {PIXI.Rectangle}
* @readonly
*/
get screen() {
return this.renderer?.screen;
}
/**
* Destroy and don't use after this.
* @param {boolean} [removeView=false] - Automatically remove canvas from DOM.
* @param {object|boolean} [stageOptions] - Options parameter. A boolean will act as if all options
* have been set to that value
* @param {boolean} [stageOptions.children=false] - if set to true, all the children will have their destroy
* method called as well. 'stageOptions' will be passed on to those calls.
* @param {boolean} [stageOptions.texture=false] - Only used for child Sprites if stageOptions.children is set
* to true. Should it destroy the texture of the child sprite
* @param {boolean} [stageOptions.baseTexture=false] - Only used for child Sprites if stageOptions.children is set
* to true. Should it destroy the base texture of the child sprite
*/
destroy(removeView, stageOptions) {
const plugins = _Application2._plugins.slice(0);
plugins.reverse(), plugins.forEach((plugin) => {
plugin.destroy.call(this);
}), this.stage.destroy(stageOptions), this.stage = null, this.renderer.destroy(removeView), this.renderer = null;
}
};
_Application._plugins = [];
let Application = _Application;
extensions.handleByList(ExtensionType.Application, Application._plugins);
export {
Application
};
//# sourceMappingURL=Application.mjs.map

File diff suppressed because one or more lines are too long

View File

@@ -1,40 +0,0 @@
import type { ExtensionMetadata, Renderer } from '@pixi/core';
type ResizeableRenderer = Pick<Renderer, 'resize'>;
export interface ResizePluginOptions {
/**
* Element to automatically resize stage to.
* @memberof PIXI.IApplicationOptions
*/
resizeTo?: Window | HTMLElement;
}
/**
* Middleware for for Application's resize functionality
* @private
* @class
*/
export declare class ResizePlugin {
/** @ignore */
static extension: ExtensionMetadata;
static resizeTo: Window | HTMLElement;
static resize: () => void;
static renderer: ResizeableRenderer;
static queueResize: () => void;
static render: () => void;
private static _resizeId;
private static _resizeTo;
private static cancelResize;
/**
* Initialize the plugin with scope of application instance
* @static
* @private
* @param {object} [options] - See application options
*/
static init(options: ResizePluginOptions): void;
/**
* Clean up the ticker, scoped to application
* @static
* @private
*/
static destroy(): void;
}
export {};

View File

@@ -1,59 +0,0 @@
"use strict";
var core = require("@pixi/core");
class ResizePlugin {
/**
* Initialize the plugin with scope of application instance
* @static
* @private
* @param {object} [options] - See application options
*/
static init(options) {
Object.defineProperty(
this,
"resizeTo",
/**
* The HTML element or window to automatically resize the
* renderer's view element to match width and height.
* @member {Window|HTMLElement}
* @name resizeTo
* @memberof PIXI.Application#
*/
{
set(dom) {
globalThis.removeEventListener("resize", this.queueResize), this._resizeTo = dom, dom && (globalThis.addEventListener("resize", this.queueResize), this.resize());
},
get() {
return this._resizeTo;
}
}
), this.queueResize = () => {
this._resizeTo && (this.cancelResize(), this._resizeId = requestAnimationFrame(() => this.resize()));
}, this.cancelResize = () => {
this._resizeId && (cancelAnimationFrame(this._resizeId), this._resizeId = null);
}, this.resize = () => {
if (!this._resizeTo)
return;
this.cancelResize();
let width, height;
if (this._resizeTo === globalThis.window)
width = globalThis.innerWidth, height = globalThis.innerHeight;
else {
const { clientWidth, clientHeight } = this._resizeTo;
width = clientWidth, height = clientHeight;
}
this.renderer.resize(width, height), this.render();
}, this._resizeId = null, this._resizeTo = null, this.resizeTo = options.resizeTo || null;
}
/**
* Clean up the ticker, scoped to application
* @static
* @private
*/
static destroy() {
globalThis.removeEventListener("resize", this.queueResize), this.cancelResize(), this.cancelResize = null, this.queueResize = null, this.resizeTo = null, this.resize = null;
}
}
ResizePlugin.extension = core.ExtensionType.Application;
core.extensions.add(ResizePlugin);
exports.ResizePlugin = ResizePlugin;
//# sourceMappingURL=ResizePlugin.js.map

File diff suppressed because one or more lines are too long

View File

@@ -1,60 +0,0 @@
import { ExtensionType, extensions } from "@pixi/core";
class ResizePlugin {
/**
* Initialize the plugin with scope of application instance
* @static
* @private
* @param {object} [options] - See application options
*/
static init(options) {
Object.defineProperty(
this,
"resizeTo",
/**
* The HTML element or window to automatically resize the
* renderer's view element to match width and height.
* @member {Window|HTMLElement}
* @name resizeTo
* @memberof PIXI.Application#
*/
{
set(dom) {
globalThis.removeEventListener("resize", this.queueResize), this._resizeTo = dom, dom && (globalThis.addEventListener("resize", this.queueResize), this.resize());
},
get() {
return this._resizeTo;
}
}
), this.queueResize = () => {
this._resizeTo && (this.cancelResize(), this._resizeId = requestAnimationFrame(() => this.resize()));
}, this.cancelResize = () => {
this._resizeId && (cancelAnimationFrame(this._resizeId), this._resizeId = null);
}, this.resize = () => {
if (!this._resizeTo)
return;
this.cancelResize();
let width, height;
if (this._resizeTo === globalThis.window)
width = globalThis.innerWidth, height = globalThis.innerHeight;
else {
const { clientWidth, clientHeight } = this._resizeTo;
width = clientWidth, height = clientHeight;
}
this.renderer.resize(width, height), this.render();
}, this._resizeId = null, this._resizeTo = null, this.resizeTo = options.resizeTo || null;
}
/**
* Clean up the ticker, scoped to application
* @static
* @private
*/
static destroy() {
globalThis.removeEventListener("resize", this.queueResize), this.cancelResize(), this.cancelResize = null, this.queueResize = null, this.resizeTo = null, this.resize = null;
}
}
ResizePlugin.extension = ExtensionType.Application;
extensions.add(ResizePlugin);
export {
ResizePlugin
};
//# sourceMappingURL=ResizePlugin.mjs.map

File diff suppressed because one or more lines are too long

View File

@@ -1,3 +0,0 @@
/// <reference path="../global.d.ts" />
export * from './Application';
export * from './ResizePlugin';

View File

@@ -1,5 +0,0 @@
"use strict";
var Application = require("./Application.js"), ResizePlugin = require("./ResizePlugin.js");
exports.Application = Application.Application;
exports.ResizePlugin = ResizePlugin.ResizePlugin;
//# sourceMappingURL=index.js.map

View File

@@ -1 +0,0 @@
{"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;"}

View File

@@ -1,7 +0,0 @@
import { Application } from "./Application.mjs";
import { ResizePlugin } from "./ResizePlugin.mjs";
export {
Application,
ResizePlugin
};
//# sourceMappingURL=index.mjs.map

View File

@@ -1 +0,0 @@
{"version":3,"file":"index.mjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;"}

View File

@@ -1,18 +1,19 @@
{
"name": "@pixi/app",
"version": "7.4.2",
"main": "lib/index.js",
"module": "lib/index.mjs",
"types": "lib/index.d.ts",
"version": "6.5.10",
"main": "dist/cjs/app.js",
"module": "dist/esm/app.mjs",
"bundle": "dist/browser/app.js",
"types": "index.d.ts",
"exports": {
".": {
"import": {
"types": "./lib/index.d.ts",
"default": "./lib/index.mjs"
"types": "./index.d.ts",
"default": "./dist/esm/app.mjs"
},
"require": {
"types": "./lib/index.d.ts",
"default": "./lib/index.js"
"types": "./index.d.ts",
"default": "./dist/cjs/app.js"
}
}
},
@@ -22,21 +23,25 @@
"Matt Karl <matt@mattkarl.com>"
],
"homepage": "http://pixijs.com/",
"bugs": "https://github.com/pixijs/pixijs/issues",
"bugs": "https://github.com/pixijs/pixi.js/issues",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/pixijs/pixijs.git"
"url": "https://github.com/pixijs/pixi.js.git"
},
"publishConfig": {
"access": "public"
},
"files": [
"lib",
"dist",
"*.d.ts"
],
"peerDependencies": {
"@pixi/core": "7.4.2",
"@pixi/display": "7.4.2"
}
"@pixi/core": "6.5.10",
"@pixi/display": "6.5.10",
"@pixi/math": "6.5.10",
"@pixi/utils": "6.5.10"
},
"gitHead": "8cdbf55064b7adc05f65c51e177f1c22f7329f0f"
}

View File

@@ -1,21 +0,0 @@
The MIT License
Copyright (c) 2013-2023 Mathew Groves, Chad Engler
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.

View File

@@ -1,10 +0,0 @@
# @pixi/assets
This package contains the assets class for PixiJS
managing the resolving and loading of assets.
## Installation
```bash
npm install @pixi/assets
```

View File

@@ -1,8 +0,0 @@
declare namespace GlobalMixins
{
// eslint-disable-next-line @typescript-eslint/no-empty-interface
interface AssetsPreferences
{
}
}

View File

@@ -1,18 +0,0 @@
import { ExtensionType } from '@pixi/core';
import type { CacheParser } from './cache';
import type { FormatDetectionParser } from './detections';
import type { LoaderParser } from './loader';
import type { ResolveURLParser } from './resolver';
/**
* This developer convenience object allows developers to group
* together the various asset parsers into a single object.
* @memberof PIXI
*/
interface AssetExtension<ASSET = any, META_DATA = any> {
extension: ExtensionType.Asset;
loader?: Partial<LoaderParser<ASSET, META_DATA>>;
resolver?: Partial<ResolveURLParser>;
cache?: Partial<CacheParser<ASSET>>;
detection?: Partial<FormatDetectionParser>;
}
export type { AssetExtension };

View File

@@ -1,21 +0,0 @@
"use strict";
var core = require("@pixi/core");
const assetKeyMap = {
loader: core.ExtensionType.LoadParser,
resolver: core.ExtensionType.ResolveParser,
cache: core.ExtensionType.CacheParser,
detection: core.ExtensionType.DetectionParser
};
core.extensions.handle(core.ExtensionType.Asset, (extension) => {
const ref = extension.ref;
Object.entries(assetKeyMap).filter(([key]) => !!ref[key]).forEach(([key, type]) => core.extensions.add(Object.assign(
ref[key],
// Allow the function to optionally define it's own
// ExtensionMetadata, the use cases here is priority for LoaderParsers
{ extension: ref[key].extension ?? type }
)));
}, (extension) => {
const ref = extension.ref;
Object.keys(assetKeyMap).filter((key) => !!ref[key]).forEach((key) => core.extensions.remove(ref[key]));
});
//# sourceMappingURL=AssetExtension.js.map

View File

@@ -1 +0,0 @@
{"version":3,"file":"AssetExtension.js","sources":["../src/AssetExtension.ts"],"sourcesContent":["import { extensions, ExtensionType } from '@pixi/core';\n\nimport type { CacheParser } from './cache';\nimport type { FormatDetectionParser } from './detections';\nimport type { LoaderParser } from './loader';\nimport type { ResolveURLParser } from './resolver';\n\nconst assetKeyMap = {\n loader: ExtensionType.LoadParser,\n resolver: ExtensionType.ResolveParser,\n cache: ExtensionType.CacheParser,\n detection: ExtensionType.DetectionParser,\n};\n\ntype AssetType = keyof typeof assetKeyMap;\n\n/**\n * This developer convenience object allows developers to group\n * together the various asset parsers into a single object.\n * @memberof PIXI\n */\ninterface AssetExtension<ASSET = any, META_DATA = any>\n{\n extension: ExtensionType.Asset,\n loader?: Partial<LoaderParser<ASSET, META_DATA>>,\n resolver?: Partial<ResolveURLParser>,\n cache?: Partial<CacheParser<ASSET>>,\n detection?: Partial<FormatDetectionParser>,\n}\n\n// Split the Asset extension into it's various parts\n// these are handled in the Assets.ts file\nextensions.handle(ExtensionType.Asset, (extension) =>\n{\n const ref = extension.ref as AssetExtension;\n\n Object.entries(assetKeyMap)\n .filter(([key]) => !!ref[key as AssetType])\n .forEach(([key, type]) => extensions.add(Object.assign(\n ref[key as AssetType],\n // Allow the function to optionally define it's own\n // ExtensionMetadata, the use cases here is priority for LoaderParsers\n { extension: ref[key as AssetType].extension ?? type },\n )));\n}, (extension) =>\n{\n const ref = extension.ref as AssetExtension;\n\n Object.keys(assetKeyMap)\n .filter((key) => !!ref[key as AssetType])\n .forEach((key) => extensions.remove(ref[key as AssetType]));\n});\n\nexport type { AssetExtension };\n"],"names":["ExtensionType","extensions"],"mappings":";;AAOA,MAAM,cAAc;AAAA,EAChB,QAAQA,KAAc,cAAA;AAAA,EACtB,UAAUA,KAAc,cAAA;AAAA,EACxB,OAAOA,KAAc,cAAA;AAAA,EACrB,WAAWA,KAAc,cAAA;AAC7B;AAoBAC,KAAA,WAAW,OAAOD,KAAAA,cAAc,OAAO,CAAC,cACxC;AACI,QAAM,MAAM,UAAU;AAEf,SAAA,QAAQ,WAAW,EACrB,OAAO,CAAC,CAAC,GAAG,MAAM,CAAC,CAAC,IAAI,GAAgB,CAAC,EACzC,QAAQ,CAAC,CAAC,KAAK,IAAI,MAAMC,KAAW,WAAA,IAAI,OAAO;AAAA,IAC5C,IAAI,GAAgB;AAAA;AAAA;AAAA,IAGpB,EAAE,WAAW,IAAI,GAAgB,EAAE,aAAa,KAAK;AAAA,EACxD,CAAA,CAAC;AACV,GAAG,CAAC,cACJ;AACI,QAAM,MAAM,UAAU;AAEf,SAAA,KAAK,WAAW,EAClB,OAAO,CAAC,QAAQ,CAAC,CAAC,IAAI,GAAgB,CAAC,EACvC,QAAQ,CAAC,QAAQA,KAAA,WAAW,OAAO,IAAI,GAAgB,CAAC,CAAC;AAClE,CAAC;"}

View File

@@ -1,20 +0,0 @@
import { ExtensionType, extensions } from "@pixi/core";
const assetKeyMap = {
loader: ExtensionType.LoadParser,
resolver: ExtensionType.ResolveParser,
cache: ExtensionType.CacheParser,
detection: ExtensionType.DetectionParser
};
extensions.handle(ExtensionType.Asset, (extension) => {
const ref = extension.ref;
Object.entries(assetKeyMap).filter(([key]) => !!ref[key]).forEach(([key, type]) => extensions.add(Object.assign(
ref[key],
// Allow the function to optionally define it's own
// ExtensionMetadata, the use cases here is priority for LoaderParsers
{ extension: ref[key].extension ?? type }
)));
}, (extension) => {
const ref = extension.ref;
Object.keys(assetKeyMap).filter((key) => !!ref[key]).forEach((key) => extensions.remove(ref[key]));
});
//# sourceMappingURL=AssetExtension.mjs.map

View File

@@ -1 +0,0 @@
{"version":3,"file":"AssetExtension.mjs","sources":["../src/AssetExtension.ts"],"sourcesContent":["import { extensions, ExtensionType } from '@pixi/core';\n\nimport type { CacheParser } from './cache';\nimport type { FormatDetectionParser } from './detections';\nimport type { LoaderParser } from './loader';\nimport type { ResolveURLParser } from './resolver';\n\nconst assetKeyMap = {\n loader: ExtensionType.LoadParser,\n resolver: ExtensionType.ResolveParser,\n cache: ExtensionType.CacheParser,\n detection: ExtensionType.DetectionParser,\n};\n\ntype AssetType = keyof typeof assetKeyMap;\n\n/**\n * This developer convenience object allows developers to group\n * together the various asset parsers into a single object.\n * @memberof PIXI\n */\ninterface AssetExtension<ASSET = any, META_DATA = any>\n{\n extension: ExtensionType.Asset,\n loader?: Partial<LoaderParser<ASSET, META_DATA>>,\n resolver?: Partial<ResolveURLParser>,\n cache?: Partial<CacheParser<ASSET>>,\n detection?: Partial<FormatDetectionParser>,\n}\n\n// Split the Asset extension into it's various parts\n// these are handled in the Assets.ts file\nextensions.handle(ExtensionType.Asset, (extension) =>\n{\n const ref = extension.ref as AssetExtension;\n\n Object.entries(assetKeyMap)\n .filter(([key]) => !!ref[key as AssetType])\n .forEach(([key, type]) => extensions.add(Object.assign(\n ref[key as AssetType],\n // Allow the function to optionally define it's own\n // ExtensionMetadata, the use cases here is priority for LoaderParsers\n { extension: ref[key as AssetType].extension ?? type },\n )));\n}, (extension) =>\n{\n const ref = extension.ref as AssetExtension;\n\n Object.keys(assetKeyMap)\n .filter((key) => !!ref[key as AssetType])\n .forEach((key) => extensions.remove(ref[key as AssetType]));\n});\n\nexport type { AssetExtension };\n"],"names":[],"mappings":";AAOA,MAAM,cAAc;AAAA,EAChB,QAAQ,cAAc;AAAA,EACtB,UAAU,cAAc;AAAA,EACxB,OAAO,cAAc;AAAA,EACrB,WAAW,cAAc;AAC7B;AAoBA,WAAW,OAAO,cAAc,OAAO,CAAC,cACxC;AACI,QAAM,MAAM,UAAU;AAEf,SAAA,QAAQ,WAAW,EACrB,OAAO,CAAC,CAAC,GAAG,MAAM,CAAC,CAAC,IAAI,GAAgB,CAAC,EACzC,QAAQ,CAAC,CAAC,KAAK,IAAI,MAAM,WAAW,IAAI,OAAO;AAAA,IAC5C,IAAI,GAAgB;AAAA;AAAA;AAAA,IAGpB,EAAE,WAAW,IAAI,GAAgB,EAAE,aAAa,KAAK;AAAA,EACxD,CAAA,CAAC;AACV,GAAG,CAAC,cACJ;AACI,QAAM,MAAM,UAAU;AAEf,SAAA,KAAK,WAAW,EAClB,OAAO,CAAC,QAAQ,CAAC,CAAC,IAAI,GAAgB,CAAC,EACvC,QAAQ,CAAC,QAAQ,WAAW,OAAO,IAAI,GAAgB,CAAC,CAAC;AAClE,CAAC;"}

View File

@@ -1,509 +0,0 @@
import { Cache } from './cache/Cache';
import { Loader } from './loader/Loader';
import { Resolver } from './resolver/Resolver';
import type { FormatDetectionParser } from './detections';
import type { LoadTextureConfig } from './loader/parsers';
import type { BundleIdentifierOptions } from './resolver/Resolver';
import type { ArrayOr, AssetsBundle, AssetsManifest, LoadParserName, ResolvedAsset, UnresolvedAsset } from './types';
export type ProgressCallback = (progress: number) => void;
/**
* Extensible preferences that can be used, for instance, when configuring loaders.
* @since 7.2.0
* @memberof PIXI
*/
export interface AssetsPreferences extends LoadTextureConfig, GlobalMixins.AssetsPreferences {
}
/**
* Initialization options object for Asset Class.
* @memberof PIXI
*/
export interface AssetInitOptions {
/** a base path for any assets loaded */
basePath?: string;
/** a default URL parameter string to append to all assets loaded */
defaultSearchParams?: string | Record<string, any>;
/**
* a manifest to tell the asset loader upfront what all your assets are
* this can be the manifest object itself, or a URL to the manifest.
*/
manifest?: string | AssetsManifest;
/**
* optional preferences for which textures preferences you have when resolving assets
* for example you might set the resolution to 0.5 if the user is on a rubbish old phone
* or you might set the resolution to 2 if the user is on a retina display
*/
texturePreference?: {
/** the resolution order you prefer, can be an array (priority order - first is prefered) or a single resolutions */
resolution?: number | number[];
/**
* the formats you prefer, by default this will be:
* ['avif', 'webp', 'png', 'jpg', 'jpeg', 'webm', 'mp4', 'm4v', 'ogv']
*/
format?: ArrayOr<string>;
};
/**
* If true, don't attempt to detect whether browser has preferred formats available.
* May result in increased performance as it skips detection step.
*/
skipDetections?: boolean;
/** advanced - override how bundlesIds are generated */
bundleIdentifier?: BundleIdentifierOptions;
/** Optional loader preferences */
preferences?: Partial<AssetsPreferences>;
}
/**
* A one stop shop for all Pixi resource management!
* Super modern and easy to use, with enough flexibility to customize and do what you need!
* @memberof PIXI
* @namespace Assets
*
* Only one Asset Class exists accessed via the Global Asset object.
*
* It has four main responsibilities:
* 1. Allows users to map URLs to keys and resolve them according to the user's browser capabilities
* 2. Loads the resources and transforms them into assets that developers understand.
* 3. Caches the assets and provides a way to access them.
* 4. Allow developers to unload assets and clear the cache.
*
* It also has a few advanced features:
* 1. Allows developers to provide a manifest upfront of all assets and help manage them via 'bundles'.
* 2. Allows users to background load assets. Shortening (or eliminating) load times and improving UX. With this feature,
* in-game loading bars can be a thing of the past!
*
* ### Assets Loading
*
* Do not be afraid to load things multiple times - under the hood, it will NEVER load anything more than once.
*
* For example:
*
* ```js
* import { Assets } from 'pixi.js';
*
* promise1 = Assets.load('bunny.png')
* promise2 = Assets.load('bunny.png')
*
* // promise1 === promise2
* ```
*
* Here both promises will be the same. Once resolved... Forever resolved! It makes for really easy resource management!
*
* Out of the box it supports the following files:
* - textures (avif, webp, png, jpg, gif, svg)
* - sprite sheets (json)
* - bitmap fonts (xml, fnt, txt)
* - web fonts (ttf, woff, woff2)
* - json files (json)
* - text files (txt)
*
* More types can be added fairly easily by creating additional loader parsers.
*
* ### Textures
* - Textures are loaded as ImageBitmap on a worker thread where possible.
* Leading to much less janky load + parse times.
* - By default, we will prefer to load AVIF and WebP image files if you specify them.
* But if the browser doesn't support AVIF or WebP we will fall back to png and jpg.
* - Textures can also be accessed via Texture.from(...) and now use this asset manager under the hood!
* - Don't worry if you set preferences for textures that don't exist (for example you prefer 2x resolutions images
* but only 1x is available for that texture, the Asset manager will pick that up as a fallback automatically)
*
* #### Sprite sheets
* - It's hard to know what resolution a sprite sheet is without loading it first, to address this
* there is a naming convention we have added that will let Pixi understand the image format and resolution
* of the spritesheet via its file name:
*
* `my-spritesheet{resolution}.{imageFormat}.json`
*
* For example:
*
* `my-spritesheet@2x.webp.json` // 2x resolution, WebP sprite sheet
* `my-spritesheet@0.5x.png.json` // 0.5x resolution, png sprite sheet
*
* This is optional! You can just load a sprite sheet as normal.
* This is only useful if you have a bunch of different res / formatted spritesheets.
*
* ### Fonts
* Web fonts will be loaded with all weights.
* It is possible to load only specific weights by doing the following:
*
* ```js
* import { Assets } from 'pixi.js';
*
* // Load specific weights..
* await Assets.load({
* data: {
* weights: ['normal'], // Only loads the weight
* },
* src: `outfit.woff2`,
* });
*
* // Load everything...
* await Assets.load(`outfit.woff2`);
* ```
*
* ### Background Loading
* Background loading will load stuff for you passively behind the scenes. To minimize jank,
* it will only load one asset at a time. As soon as a developer calls `Assets.load(...)` the
* background loader is paused and requested assets are loaded as a priority.
* Don't worry if something is in there that's already loaded, it will just get skipped!
*
* You still need to call `Assets.load(...)` to get an asset that has been loaded in the background.
* It's just that this promise will resolve instantly if the asset
* has already been loaded.
*
* ### Manifest and Bundles
* - Manifest is a JSON file that contains a list of all assets and their properties.
* - Bundles are a way to group assets together.
*
* ```js
* import { Assets } from 'pixi.js';
*
* // Manifest Example
* const manifest = {
* bundles: [
* {
* name: 'load-screen',
* assets: [
* {
* alias: 'background',
* src: 'sunset.png',
* },
* {
* alias: 'bar',
* src: 'load-bar.{png,webp}',
* },
* ],
* },
* {
* name: 'game-screen',
* assets: [
* {
* alias: 'character',
* src: 'robot.png',
* },
* {
* alias: 'enemy',
* src: 'bad-guy.png',
* },
* ],
* },
* ]
* };
*
* await Assets.init({ manifest });
*
* // Load a bundle...
* loadScreenAssets = await Assets.loadBundle('load-screen');
* // Load another bundle...
* gameScreenAssets = await Assets.loadBundle('game-screen');
* ```
* @example
* import { Assets } from 'pixi.js';
*
* const bunny = await Assets.load('bunny.png');
*/
export declare class AssetsClass {
/** the resolver to map various urls */
resolver: Resolver;
/**
* The loader, loads stuff!
* @type {PIXI.AssetLoader}
*/
loader: Loader;
/**
* The global cache of all assets within PixiJS
* @type {PIXI.Cache}
*/
cache: typeof Cache;
/** takes care of loading assets in the background */
private readonly _backgroundLoader;
private _detections;
private _initialized;
constructor();
/**
* Best practice is to call this function before any loading commences
* Initiating is the best time to add any customization to the way things are loaded.
*
* you do not need to call this for the Asset class to work, only if you want to set any initial properties
* @param options - options to initialize the Asset manager with
*/
init(options?: AssetInitOptions): Promise<void>;
/** @deprecated */
add(a: ArrayOr<string>, s?: string | string[], d?: unknown, f?: string, lp?: LoadParserName): void;
/**
* Allows you to specify how to resolve any assets load requests.
* There are a few ways to add things here as shown below:
* @example
* import { Assets } from 'pixi.js';
*
* // Simple
* Assets.add({alias: 'bunnyBooBoo', src: 'bunny.png'});
* const bunny = await Assets.load('bunnyBooBoo');
*
* // Multiple keys:
* Assets.add({alias: ['burger', 'chicken'], src: 'bunny.png'});
*
* const bunny = await Assets.load('burger');
* const bunny2 = await Assets.load('chicken');
*
* // passing options to to the object
* Assets.add({
* alias: 'bunnyBooBooSmooth',
* src: 'bunny{png,webp}',
* data: { scaleMode: SCALE_MODES.NEAREST }, // Base texture options
* });
*
* // Multiple assets
*
* // The following all do the same thing:
*
* Assets.add({alias: 'bunnyBooBoo', src: 'bunny{png,webp}'});
*
* Assets.add({
* alias: 'bunnyBooBoo',
* src: [
* 'bunny.png',
* 'bunny.webp',
* ],
* });
*
* const bunny = await Assets.load('bunnyBooBoo'); // Will try to load WebP if available
* @param data - the data to add
* @param data.aliases - the key or keys that you will reference when loading this asset
* @param data.srcs - the asset or assets that will be chosen from when loading via the specified key
* @param data.data - asset-specific data that will be passed to the loaders
* - Useful if you want to initiate loaded objects with specific data
* @param data.format - the format of the asset
* @param data.loadParser - the name of the load parser to use
*/
add(data: (ArrayOr<UnresolvedAsset>)): void;
/**
* Loads your assets! You pass in a key or URL and it will return a promise that
* resolves to the loaded asset. If multiple assets a requested, it will return a hash of assets.
*
* Don't worry about loading things multiple times, behind the scenes assets are only ever loaded
* once and the same promise reused behind the scenes so you can safely call this function multiple
* times with the same key and it will always return the same asset.
* @example
* import { Assets } from 'pixi.js';
*
* // Load a URL:
* const myImageTexture = await Assets.load('http://some.url.com/image.png'); // => returns a texture
*
* Assets.add('thumper', 'bunny.png');
* Assets.add('chicko', 'chicken.png');
*
* // Load multiple assets:
* const textures = await Assets.load(['thumper', 'chicko']); // => {thumper: Texture, chicko: Texture}
* @param urls - the urls to load
* @param onProgress - optional function that is called when progress on asset loading is made.
* The function is passed a single parameter, `progress`, which represents the percentage
* (0.0 - 1.0) of the assets loaded.
* @returns - the assets that were loaded, either a single asset or a hash of assets
*/
load<T = any>(urls: string | UnresolvedAsset, onProgress?: ProgressCallback): Promise<T>;
load<T = any>(urls: string[] | UnresolvedAsset[], onProgress?: ProgressCallback): Promise<Record<string, T>>;
/**
* This adds a bundle of assets in one go so that you can load them as a group.
* For example you could add a bundle for each screen in you pixi app
* @example
* import { Assets } from 'pixi.js';
*
* Assets.addBundle('animals', {
* bunny: 'bunny.png',
* chicken: 'chicken.png',
* thumper: 'thumper.png',
* });
*
* const assets = await Assets.loadBundle('animals');
* @param bundleId - the id of the bundle to add
* @param assets - a record of the asset or assets that will be chosen from when loading via the specified key
*/
addBundle(bundleId: string, assets: AssetsBundle['assets']): void;
/**
* Bundles are a way to load multiple assets at once.
* If a manifest has been provided to the init function then you can load a bundle, or bundles.
* you can also add bundles via `addBundle`
* @example
* import { Assets } from 'pixi.js';
*
* // Manifest Example
* const manifest = {
* bundles: [
* {
* name: 'load-screen',
* assets: [
* {
* alias: 'background',
* src: 'sunset.png',
* },
* {
* alias: 'bar',
* src: 'load-bar.{png,webp}',
* },
* ],
* },
* {
* name: 'game-screen',
* assets: [
* {
* alias: 'character',
* src: 'robot.png',
* },
* {
* alias: 'enemy',
* src: 'bad-guy.png',
* },
* ],
* },
* ]
* };
*
* await Assets.init({ manifest });
*
* // Load a bundle...
* loadScreenAssets = await Assets.loadBundle('load-screen');
* // Load another bundle...
* gameScreenAssets = await Assets.loadBundle('game-screen');
* @param bundleIds - the bundle id or ids to load
* @param onProgress - Optional function that is called when progress on asset loading is made.
* The function is passed a single parameter, `progress`, which represents the percentage (0.0 - 1.0)
* of the assets loaded. Do not use this function to detect when assets are complete and available,
* instead use the Promise returned by this function.
* @returns all the bundles assets or a hash of assets for each bundle specified
*/
loadBundle(bundleIds: ArrayOr<string>, onProgress?: ProgressCallback): Promise<any>;
/**
* Initiate a background load of some assets. It will passively begin to load these assets in the background.
* So when you actually come to loading them you will get a promise that resolves to the loaded assets immediately
*
* An example of this might be that you would background load game assets after your inital load.
* then when you got to actually load your game screen assets when a player goes to the game - the loading
* would already have stared or may even be complete, saving you having to show an interim load bar.
* @example
* import { Assets } from 'pixi.js';
*
* Assets.backgroundLoad('bunny.png');
*
* // later on in your app...
* await Assets.loadBundle('bunny.png'); // Will resolve quicker as loading may have completed!
* @param urls - the url / urls you want to background load
*/
backgroundLoad(urls: ArrayOr<string>): Promise<void>;
/**
* Initiate a background of a bundle, works exactly like backgroundLoad but for bundles.
* this can only be used if the loader has been initiated with a manifest
* @example
* import { Assets } from 'pixi.js';
*
* await Assets.init({
* manifest: {
* bundles: [
* {
* name: 'load-screen',
* assets: [...],
* },
* ...
* ],
* },
* });
*
* Assets.backgroundLoadBundle('load-screen');
*
* // Later on in your app...
* await Assets.loadBundle('load-screen'); // Will resolve quicker as loading may have completed!
* @param bundleIds - the bundleId / bundleIds you want to background load
*/
backgroundLoadBundle(bundleIds: ArrayOr<string>): Promise<void>;
/**
* Only intended for development purposes.
* This will wipe the resolver and caches.
* You will need to reinitialize the Asset
*/
reset(): void;
/**
* Instantly gets an asset already loaded from the cache. If the asset has not yet been loaded,
* it will return undefined. So it's on you! When in doubt just use `Assets.load` instead.
* (Remember, the loader will never load things more than once!)
* @param keys - The key or keys for the assets that you want to access
* @returns - The assets or hash of assets requested
*/
get<T = any>(keys: string): T;
get<T = any>(keys: string[]): Record<string, T>;
/**
* helper function to map resolved assets back to loaded assets
* @param resolveResults - the resolve results from the resolver
* @param onProgress - the progress callback
*/
private _mapLoadToResolve;
/**
* Unload an asset or assets. As the Assets class is responsible for creating the assets via the `load` function
* this will make sure to destroy any assets and release them from memory.
* Once unloaded, you will need to load the asset again.
*
* Use this to help manage assets if you find that you have a large app and you want to free up memory.
*
* - it's up to you as the developer to make sure that textures are not actively being used when you unload them,
* Pixi won't break but you will end up with missing assets. Not a good look for the user!
* @example
* import { Assets } from 'pixi.js';
*
* // Load a URL:
* const myImageTexture = await Assets.load('http://some.url.com/image.png'); // => returns a texture
*
* await Assets.unload('http://some.url.com/image.png')
*
* // myImageTexture will be destroyed now.
*
* // Unload multiple assets:
* const textures = await Assets.unload(['thumper', 'chicko']);
* @param urls - the urls to unload
*/
unload(urls: ArrayOr<string> | ResolvedAsset | ResolvedAsset[]): Promise<void>;
/**
* Bundles are a way to manage multiple assets at once.
* this will unload all files in a bundle.
*
* once a bundle has been unloaded, you need to load it again to have access to the assets.
* @example
* import { Assets } from 'pixi.js';
*
* Assets.addBundle({
* 'thumper': 'http://some.url.com/thumper.png',
* })
*
* const assets = await Assets.loadBundle('thumper');
*
* // Now to unload...
*
* await Assets.unloadBundle('thumper');
*
* // All assets in the assets object will now have been destroyed and purged from the cache
* @param bundleIds - the bundle id or ids to unload
*/
unloadBundle(bundleIds: ArrayOr<string>): Promise<void>;
private _unloadFromResolved;
/**
* Detects the supported formats for the browser, and returns an array of supported formats, respecting
* the users preferred formats order.
* @param options - the options to use when detecting formats
* @param options.preferredFormats - the preferred formats to use
* @param options.skipDetections - if we should skip the detections altogether
* @param options.detections - the detections to use
* @returns - the detected formats
*/
private _detectFormats;
/** All the detection parsers currently added to the Assets class. */
get detections(): FormatDetectionParser[];
/**
* @deprecated since 7.2.0
* @see {@link Assets.setPreferences}
*/
get preferWorkers(): boolean;
set preferWorkers(value: boolean);
/**
* General setter for preferences. This is a helper function to set preferences on all parsers.
* @param preferences - the preferences to set
*/
setPreferences(preferences: Partial<AssetsPreferences>): void;
}
export declare const Assets: AssetsClass;

Some files were not shown because too many files have changed in this diff Show More