Spaces:
Running
Running
File size: 15,774 Bytes
4bb817b |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import {
isTypedArray, HashMap, clone, createHashMap, isArray, isObject, isArrayLike,
hasOwn, assert, each, map, isNumber, isString, keys
} from 'zrender/src/core/util';
import {
SourceFormat, SeriesLayoutBy, DimensionDefinition,
OptionEncodeValue, OptionSourceData,
SOURCE_FORMAT_ORIGINAL,
SERIES_LAYOUT_BY_COLUMN,
SOURCE_FORMAT_UNKNOWN,
SOURCE_FORMAT_KEYED_COLUMNS,
SOURCE_FORMAT_TYPED_ARRAY,
DimensionName,
OptionSourceHeader,
DimensionDefinitionLoose,
SOURCE_FORMAT_ARRAY_ROWS,
SOURCE_FORMAT_OBJECT_ROWS,
Dictionary,
OptionSourceDataObjectRows,
OptionDataValue,
OptionSourceDataArrayRows,
SERIES_LAYOUT_BY_ROW,
OptionSourceDataOriginal,
OptionSourceDataKeyedColumns
} from '../util/types';
import { DatasetOption } from '../component/dataset/install';
import { getDataItemValue } from '../util/model';
import { BE_ORDINAL, guessOrdinal } from './helper/sourceHelper';
/**
* [sourceFormat]
*
* + "original":
* This format is only used in series.data, where
* itemStyle can be specified in data item.
*
* + "arrayRows":
* [
* ['product', 'score', 'amount'],
* ['Matcha Latte', 89.3, 95.8],
* ['Milk Tea', 92.1, 89.4],
* ['Cheese Cocoa', 94.4, 91.2],
* ['Walnut Brownie', 85.4, 76.9]
* ]
*
* + "objectRows":
* [
* {product: 'Matcha Latte', score: 89.3, amount: 95.8},
* {product: 'Milk Tea', score: 92.1, amount: 89.4},
* {product: 'Cheese Cocoa', score: 94.4, amount: 91.2},
* {product: 'Walnut Brownie', score: 85.4, amount: 76.9}
* ]
*
* + "keyedColumns":
* {
* 'product': ['Matcha Latte', 'Milk Tea', 'Cheese Cocoa', 'Walnut Brownie'],
* 'count': [823, 235, 1042, 988],
* 'score': [95.8, 81.4, 91.2, 76.9]
* }
*
* + "typedArray"
*
* + "unknown"
*/
export interface SourceMetaRawOption {
seriesLayoutBy: SeriesLayoutBy;
sourceHeader: OptionSourceHeader;
dimensions: DimensionDefinitionLoose[];
}
// Prevent from `new Source()` external and circular reference.
export interface Source extends SourceImpl {};
// @inner
class SourceImpl {
/**
* Not null/undefined.
*/
readonly data: OptionSourceData;
/**
* See also "detectSourceFormat".
* Not null/undefined.
*/
readonly sourceFormat: SourceFormat;
/**
* 'row' or 'column'
* Not null/undefined.
*/
readonly seriesLayoutBy: SeriesLayoutBy;
/**
* dimensions definition from:
* (1) standalone defined in option prop `dimensions: [...]`
* (2) detected from option data. See `determineSourceDimensions`.
* If can not be detected (e.g., there is only pure data `[[11, 33], ...]`
* `dimensionsDefine` will be null/undefined.
*/
readonly dimensionsDefine: DimensionDefinition[];
/**
* Only make sense in `SOURCE_FORMAT_ARRAY_ROWS`.
* That is the same as `sourceHeader: number`,
* which means from which line the real data start.
* Not null/undefined, uint.
*/
readonly startIndex: number;
/**
* Dimension count detected from data. Only works when `dimensionDefine`
* does not exists.
* Can be null/undefined (when unknown), uint.
*/
readonly dimensionsDetectedCount: number;
/**
* Raw props from user option.
*/
readonly metaRawOption: SourceMetaRawOption;
constructor(fields: {
data: OptionSourceData,
sourceFormat: SourceFormat, // default: SOURCE_FORMAT_UNKNOWN
// Visit config are optional:
seriesLayoutBy?: SeriesLayoutBy, // default: 'column'
dimensionsDefine?: DimensionDefinition[],
startIndex?: number, // default: 0
dimensionsDetectedCount?: number,
metaRawOption?: SourceMetaRawOption,
// [Caveat]
// This is the raw user defined `encode` in `series`.
// If user not defined, DO NOT make a empty object or hashMap here.
// An empty object or hashMap will prevent from auto generating encode.
encodeDefine?: HashMap<OptionEncodeValue, DimensionName>
}) {
this.data = fields.data || (
fields.sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS ? {} : []
);
this.sourceFormat = fields.sourceFormat || SOURCE_FORMAT_UNKNOWN;
// Visit config
this.seriesLayoutBy = fields.seriesLayoutBy || SERIES_LAYOUT_BY_COLUMN;
this.startIndex = fields.startIndex || 0;
this.dimensionsDetectedCount = fields.dimensionsDetectedCount;
this.metaRawOption = fields.metaRawOption;
const dimensionsDefine = this.dimensionsDefine = fields.dimensionsDefine;
if (dimensionsDefine) {
for (let i = 0; i < dimensionsDefine.length; i++) {
const dim = dimensionsDefine[i];
if (dim.type == null) {
if (guessOrdinal(this, i) === BE_ORDINAL.Must) {
dim.type = 'ordinal';
}
}
}
}
}
}
export function isSourceInstance(val: unknown): val is Source {
return val instanceof SourceImpl;
}
/**
* Create a source from option.
* NOTE: Created source is immutable. Don't change any properties in it.
*/
export function createSource(
sourceData: OptionSourceData,
thisMetaRawOption: SourceMetaRawOption,
// can be null. If not provided, auto detect it from `sourceData`.
sourceFormat: SourceFormat
): Source {
sourceFormat = sourceFormat || detectSourceFormat(sourceData);
const seriesLayoutBy = thisMetaRawOption.seriesLayoutBy;
const determined = determineSourceDimensions(
sourceData,
sourceFormat,
seriesLayoutBy,
thisMetaRawOption.sourceHeader,
thisMetaRawOption.dimensions
);
const source = new SourceImpl({
data: sourceData,
sourceFormat: sourceFormat,
seriesLayoutBy: seriesLayoutBy,
dimensionsDefine: determined.dimensionsDefine,
startIndex: determined.startIndex,
dimensionsDetectedCount: determined.dimensionsDetectedCount,
metaRawOption: clone(thisMetaRawOption)
});
return source;
}
/**
* Wrap original series data for some compatibility cases.
*/
export function createSourceFromSeriesDataOption(data: OptionSourceData): Source {
return new SourceImpl({
data: data,
sourceFormat: isTypedArray(data)
? SOURCE_FORMAT_TYPED_ARRAY
: SOURCE_FORMAT_ORIGINAL
});
}
/**
* Clone source but excludes source data.
*/
export function cloneSourceShallow(source: Source): Source {
return new SourceImpl({
data: source.data,
sourceFormat: source.sourceFormat,
seriesLayoutBy: source.seriesLayoutBy,
dimensionsDefine: clone(source.dimensionsDefine),
startIndex: source.startIndex,
dimensionsDetectedCount: source.dimensionsDetectedCount
});
}
/**
* Note: An empty array will be detected as `SOURCE_FORMAT_ARRAY_ROWS`.
*/
export function detectSourceFormat(data: DatasetOption['source']): SourceFormat {
let sourceFormat: SourceFormat = SOURCE_FORMAT_UNKNOWN;
if (isTypedArray(data)) {
sourceFormat = SOURCE_FORMAT_TYPED_ARRAY;
}
else if (isArray(data)) {
// FIXME Whether tolerate null in top level array?
if (data.length === 0) {
sourceFormat = SOURCE_FORMAT_ARRAY_ROWS;
}
for (let i = 0, len = data.length; i < len; i++) {
const item = data[i];
if (item == null) {
continue;
}
else if (isArray(item) || isTypedArray(item)) {
sourceFormat = SOURCE_FORMAT_ARRAY_ROWS;
break;
}
else if (isObject(item)) {
sourceFormat = SOURCE_FORMAT_OBJECT_ROWS;
break;
}
}
}
else if (isObject(data)) {
for (const key in data) {
if (hasOwn(data, key) && isArrayLike((data as Dictionary<unknown>)[key])) {
sourceFormat = SOURCE_FORMAT_KEYED_COLUMNS;
break;
}
}
}
return sourceFormat;
}
/**
* Determine the source definitions from data standalone dimensions definitions
* are not specified.
*/
function determineSourceDimensions(
data: OptionSourceData,
sourceFormat: SourceFormat,
seriesLayoutBy: SeriesLayoutBy,
sourceHeader: OptionSourceHeader,
// standalone raw dimensions definition, like:
// {
// dimensions: ['aa', 'bb', { name: 'cc', type: 'time' }]
// }
// in `dataset` or `series`
dimensionsDefine: DimensionDefinitionLoose[]
): {
// If the input `dimensionsDefine` is specified, return it.
// Else determine dimensions from the input `data`.
// If not determined, `dimensionsDefine` will be null/undefined.
dimensionsDefine: Source['dimensionsDefine'];
startIndex: Source['startIndex'];
dimensionsDetectedCount: Source['dimensionsDetectedCount'];
} {
let dimensionsDetectedCount;
let startIndex: number;
// PENDING: Could data be null/undefined here?
// currently, if `dataset.source` not specified, error thrown.
// if `series.data` not specified, nothing rendered without error thrown.
// Should test these cases.
if (!data) {
return {
dimensionsDefine: normalizeDimensionsOption(dimensionsDefine),
startIndex,
dimensionsDetectedCount
};
}
if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
const dataArrayRows = data as OptionSourceDataArrayRows;
// Rule: Most of the first line are string: it is header.
// Caution: consider a line with 5 string and 1 number,
// it still can not be sure it is a head, because the
// 5 string may be 5 values of category columns.
if (sourceHeader === 'auto' || sourceHeader == null) {
arrayRowsTravelFirst(function (val) {
// '-' is regarded as null/undefined.
if (val != null && val !== '-') {
if (isString(val)) {
startIndex == null && (startIndex = 1);
}
else {
startIndex = 0;
}
}
// 10 is an experience number, avoid long loop.
}, seriesLayoutBy, dataArrayRows, 10);
}
else {
startIndex = isNumber(sourceHeader) ? sourceHeader : sourceHeader ? 1 : 0;
}
if (!dimensionsDefine && startIndex === 1) {
dimensionsDefine = [];
arrayRowsTravelFirst(function (val, index) {
dimensionsDefine[index] = (val != null ? val + '' : '') as DimensionName;
}, seriesLayoutBy, dataArrayRows, Infinity);
}
dimensionsDetectedCount = dimensionsDefine
? dimensionsDefine.length
: seriesLayoutBy === SERIES_LAYOUT_BY_ROW
? dataArrayRows.length
: dataArrayRows[0]
? dataArrayRows[0].length
: null;
}
else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
if (!dimensionsDefine) {
dimensionsDefine = objectRowsCollectDimensions(data as OptionSourceDataObjectRows);
}
}
else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
if (!dimensionsDefine) {
dimensionsDefine = [];
each(data as OptionSourceDataKeyedColumns, function (colArr, key) {
dimensionsDefine.push(key);
});
}
}
else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
const value0 = getDataItemValue((data as OptionSourceDataOriginal)[0]);
dimensionsDetectedCount = isArray(value0) && value0.length || 1;
}
else if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
if (__DEV__) {
assert(!!dimensionsDefine, 'dimensions must be given if data is TypedArray.');
}
}
return {
startIndex: startIndex,
dimensionsDefine: normalizeDimensionsOption(dimensionsDefine),
dimensionsDetectedCount: dimensionsDetectedCount
};
}
function objectRowsCollectDimensions(data: OptionSourceDataObjectRows): DimensionDefinitionLoose[] {
let firstIndex = 0;
let obj;
while (firstIndex < data.length && !(obj = data[firstIndex++])) {} // jshint ignore: line
if (obj) {
return keys(obj);
}
}
// Consider dimensions defined like ['A', 'price', 'B', 'price', 'C', 'price'],
// which is reasonable. But dimension name is duplicated.
// Returns undefined or an array contains only object without null/undefined or string.
function normalizeDimensionsOption(dimensionsDefine: DimensionDefinitionLoose[]): DimensionDefinition[] {
if (!dimensionsDefine) {
// The meaning of null/undefined is different from empty array.
return;
}
const nameMap = createHashMap<{ count: number }, string>();
return map(dimensionsDefine, function (rawItem, index) {
rawItem = isObject(rawItem) ? rawItem : { name: rawItem };
// Other fields will be discarded.
const item: DimensionDefinition = {
name: rawItem.name,
displayName: rawItem.displayName,
type: rawItem.type
};
// User can set null in dimensions.
// We don't auto specify name, otherwise a given name may
// cause it to be referred unexpectedly.
if (item.name == null) {
return item;
}
// Also consider number form like 2012.
item.name += '';
// User may also specify displayName.
// displayName will always exists except user not
// specified or dim name is not specified or detected.
// (A auto generated dim name will not be used as
// displayName).
if (item.displayName == null) {
item.displayName = item.name;
}
const exist = nameMap.get(item.name);
if (!exist) {
nameMap.set(item.name, {count: 1});
}
else {
item.name += '-' + exist.count++;
}
return item;
});
}
function arrayRowsTravelFirst(
cb: (val: OptionDataValue, idx: number) => void,
seriesLayoutBy: SeriesLayoutBy,
data: OptionSourceDataArrayRows,
maxLoop: number
): void {
if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
for (let i = 0; i < data.length && i < maxLoop; i++) {
cb(data[i] ? data[i][0] : null, i);
}
}
else {
const value0 = data[0] || [];
for (let i = 0; i < value0.length && i < maxLoop; i++) {
cb(value0[i], i);
}
}
}
export function shouldRetrieveDataByName(source: Source): boolean {
const sourceFormat = source.sourceFormat;
return sourceFormat === SOURCE_FORMAT_OBJECT_ROWS || sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS;
}
|