- 1 :
/**
- 2 :
* @module filter-source
- 3 :
*/
- 4 :
import {isObject} from './obj';
- 5 :
import {getMimetype} from './mimetypes';
- 6 :
- 7 :
/**
- 8 :
* Filter out single bad source objects or multiple source objects in an
- 9 :
* array. Also flattens nested source object arrays into a 1 dimensional
- 10 :
* array of source objects.
- 11 :
*
- 12 :
* @param {Tech~SourceObject|Tech~SourceObject[]} src
- 13 :
* The src object to filter
- 14 :
*
- 15 :
* @return {Tech~SourceObject[]}
- 16 :
* An array of sourceobjects containing only valid sources
- 17 :
*
- 18 :
* @private
- 19 :
*/
- 20 :
const filterSource = function(src) {
- 21 :
// traverse array
- 22 :
if (Array.isArray(src)) {
- 23 :
let newsrc = [];
- 24 :
- 25 :
src.forEach(function(srcobj) {
- 26 :
srcobj = filterSource(srcobj);
- 27 :
- 28 :
if (Array.isArray(srcobj)) {
- 29 :
newsrc = newsrc.concat(srcobj);
- 30 :
} else if (isObject(srcobj)) {
- 31 :
newsrc.push(srcobj);
- 32 :
}
- 33 :
});
- 34 :
- 35 :
src = newsrc;
- 36 :
} else if (typeof src === 'string' && src.trim()) {
- 37 :
// convert string into object
- 38 :
src = [fixSource({src})];
- 39 :
} else if (isObject(src) && typeof src.src === 'string' && src.src && src.src.trim()) {
- 40 :
// src is already valid
- 41 :
src = [fixSource(src)];
- 42 :
} else {
- 43 :
// invalid source, turn it into an empty array
- 44 :
src = [];
- 45 :
}
- 46 :
- 47 :
return src;
- 48 :
};
- 49 :
- 50 :
/**
- 51 :
* Checks src mimetype, adding it when possible
- 52 :
*
- 53 :
* @param {Tech~SourceObject} src
- 54 :
* The src object to check
- 55 :
* @return {Tech~SourceObject}
- 56 :
* src Object with known type
- 57 :
*/
- 58 :
function fixSource(src) {
- 59 :
if (!src.type) {
- 60 :
const mimetype = getMimetype(src.src);
- 61 :
- 62 :
if (mimetype) {
- 63 :
src.type = mimetype;
- 64 :
}
- 65 :
}
- 66 :
- 67 :
return src;
- 68 :
}
- 69 :
- 70 :
export default filterSource;