redoc/lib/services/options.service.ts

76 lines
2.2 KiB
TypeScript
Raw Normal View History

'use strict';
2016-05-06 12:46:41 +03:00
import { Injectable } from '@angular/core';
import { isFunction, isString } from '../utils/helpers';
2016-08-28 21:46:10 +03:00
import { BrowserDomAdapter as DOM } from '../utils/browser-adapter';
2016-05-06 12:46:41 +03:00
const defaults = {
scrollYOffset: 0,
2016-08-28 21:46:10 +03:00
disableLazySchemas: false
};
2015-12-30 02:29:29 +03:00
const OPTION_NAMES = new Set(['scrollYOffset', 'disableLazySchemas', 'specUrl', 'suppressWarnings', 'hideHostname']);
2016-05-06 12:46:41 +03:00
@Injectable()
export class OptionsService {
private _options: any;
2016-06-13 20:54:24 +03:00
2016-08-28 21:46:10 +03:00
constructor() {
this._options = defaults;
2016-11-24 16:29:29 +03:00
this._normalizeOptions();
}
2015-12-30 02:29:29 +03:00
get options() {
return this._options;
}
set options(opts) {
this._options = Object.assign(this._options, opts);
}
parseOptions(el) {
let parsedOpts;
2016-08-28 21:46:10 +03:00
let attributesMap = DOM.attributeMap(el);
parsedOpts = {};
Array.from(attributesMap.keys())
//camelCasify
.map(k => ({
attrName: k,
name: k.replace(/-(.)/g, (m, $1) => $1.toUpperCase())
})
)
.filter(option => OPTION_NAMES.has(option.name))
.forEach(option => {
parsedOpts[option.name] = attributesMap.get(option.attrName);
});
this.options = parsedOpts;
this._normalizeOptions();
}
_normalizeOptions() {
// modify scrollYOffset to always be a function
if (!isFunction(this._options.scrollYOffset)) {
if (isFinite(this._options.scrollYOffset)) {
// if number specified create function that returns this value
let numberOffset = parseFloat(this._options.scrollYOffset);
this.options.scrollYOffset = () => numberOffset;
} else {
// if selector or node function that returns bottom offset of this node
let el = this._options.scrollYOffset;
if (!(el instanceof Node)) {
2016-08-28 21:46:10 +03:00
el = DOM.query(el);
}
if (!el) {
this._options.scrollYOffset = () => 0;
} else {
this._options.scrollYOffset = () => el.offsetTop + el.offsetHeight;
}
}
}
if (isString(this._options.disableLazySchemas)) this._options.disableLazySchemas = true;
if (isString(this._options.suppressWarnings)) this._options.suppressWarnings = true;
if (isString(this._options.hideHostname)) this._options.hideHostname = true;
}
2015-12-30 02:29:29 +03:00
}