docsify/src/core/fetch/ajax.js
Joe Pea 62d756c447 refactor: convert to ES Modules and remove traces of CommonJS except in Rollup config because some dependencies are still CommonJS
BREAKING: The new project layout might break in some tooling setups.

We've added an exports field to `package.json` to specify where
statements like `import ... from 'docsify'` will import from, and left
the `main` and `unpkg` fields as-is for backwards compatibility with the
global <script> import method. Most people who use a non-module
`<script>` tag to import Docsify will not notice a difference. Anyone
else who is importing Docsify into a specilized build setup using
`import` statements has a chance of being broken, so we've marked this
as BREAKING.
2023-06-29 19:02:08 -07:00

72 lines
1.6 KiB
JavaScript

/* eslint-disable no-unused-vars */
import progressbar from '../render/progressbar.js';
import { noop, hasOwn } from '../util/core.js';
const cache = {};
/**
* Ajax GET implmentation
* @param {string} url Resource URL
* @param {boolean} [hasBar=false] Has progress bar
* @param {String[]} headers Array of headers
* @return {Promise} Promise response
*/
export function get(url, hasBar = false, headers = {}) {
const xhr = new XMLHttpRequest();
const on = function () {
xhr.addEventListener.apply(xhr, arguments);
};
const cached = cache[url];
if (cached) {
return { then: cb => cb(cached.content, cached.opt), abort: noop };
}
xhr.open('GET', url);
for (const i in headers) {
if (hasOwn.call(headers, i)) {
xhr.setRequestHeader(i, headers[i]);
}
}
xhr.send();
return {
then: function (success, error = noop) {
if (hasBar) {
const id = setInterval(
_ =>
progressbar({
step: Math.floor(Math.random() * 5 + 1),
}),
500
);
on('progress', progressbar);
on('loadend', evt => {
progressbar(evt);
clearInterval(id);
});
}
on('error', error);
on('load', ({ target }) => {
if (target.status >= 400) {
error(target);
} else {
const result = (cache[url] = {
content: target.response,
opt: {
updatedAt: xhr.getResponseHeader('last-modified'),
},
});
success(result.content, result.opt);
}
});
},
abort: _ => xhr.readyState !== 4 && xhr.abort(),
};
}