@ideal-postcodes/address-finder
Version:
Address Finder JS library backed by the Ideal Postcodes UK address search API
72 lines (71 loc) • 3 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.watch = void 0;
const core_axios_1 = require("@ideal-postcodes/core-axios");
const controller_1 = require("./controller");
const contexts_1 = require("./contexts");
const jsutil_1 = require("@ideal-postcodes/jsutil");
const setup_1 = require("./setup");
const isTrue = () => true;
const getAnchors = (config, marker) => {
const scope = (0, jsutil_1.getScope)(config.scope || null);
const matches = scope.querySelectorAll(config.anchor ||
config.inputField ||
(config.outputFields || {}).line_1);
return (0, jsutil_1.toArray)(matches).filter((e) => !(0, jsutil_1.loaded)(e, marker));
};
const DEFAULT_INTERVAL = 1000;
const formScope = (anchor) => (0, jsutil_1.getParent)(anchor, "FORM");
/**
* Dynamically apply AddressFinder when relevant fields appear
* - Exits if page test is fails
* - Check if key usable
* - Creates a bind method
* - Retrives parent scope
* - Marks anchor if completed
* - Creates timer tools
*/
const watch = (config, options = {}) => {
const client = new core_axios_1.Client({ ...controller_1.defaults, ...config, api_key: config.apiKey });
const { pageTest = isTrue } = options;
if (!pageTest())
return Promise.resolve(null);
return (0, core_axios_1.checkKeyUsability)({ client })
.then((key) => {
if (!key.available)
return null;
const { getScope = formScope, interval = DEFAULT_INTERVAL, anchor, onBind = controller_1.NOOP, onAnchorFound = controller_1.NOOP, onBindAttempt = controller_1.NOOP, immediate = true, marker = "idpc", } = options;
const bind = () => {
onBindAttempt({ config, options });
getAnchors({ anchor, ...config }, marker).forEach((anchor) => {
const scope = getScope(anchor);
if (!scope)
return;
const contexts = (0, contexts_1.toContextMap)(key.contexts);
const newConfig = { scope, ...config, checkKey: false, contexts };
onAnchorFound({ anchor, scope, config: newConfig });
const c = (0, setup_1.setup)(newConfig);
const details = c.options.contexts[key.context];
if (c.options.detectCountry && details) {
c.applyContext(details, false);
}
else {
c.applyContext(c.currentContext(), false);
}
(0, jsutil_1.markLoaded)(anchor, marker);
onBind(c);
});
};
const { start, stop } = (0, jsutil_1.generateTimer)({ bind, pageTest, interval });
if (immediate)
start();
return { start, stop, bind };
})
.catch((e) => {
// Swallow promise errors and raise via optionall onError callback
if (options.onError)
options.onError(e);
return null;
});
};
exports.watch = watch;