@roots/bud-api
Version:
bud.js core module
53 lines (52 loc) • 1.83 kB
JavaScript
import { BudError } from '@roots/bud-support/errors';
export const hash = function (value = true) {
if (typeof value === `boolean`) {
return setHash(this, value);
}
if (value instanceof this.constructor) {
return setHash(this, true);
}
if (typeof value === `function`) {
value = value(this.context.hash);
if (typeof value !== `boolean` && typeof value !== `string`)
throw new BudError(`bud.hash: invalid input`, {
details: `callbacks supplied to bud.hash should return a boolean or a string value`,
docs: new URL(`https://bud.js.org/reference/bud.hash`),
thrownBy: `@roots/bud-api/methods/hash`,
});
if (typeof value === `string`) {
setHash(this, true);
setFormat(this, value);
return this;
}
return setHash(this, value);
}
if (typeof value === `string`) {
setHash(this, true);
return setFormat(this, value);
}
throw new BudError(`bud.hash: invalid input`, {
details: `bud.hash accepts a boolean, string, or callback function as input.`,
docs: new URL(`https://bud.js.org/reference/bud.hash`),
thrownBy: `@roots/bud-api/methods/hash`,
});
};
const formatHashString = (value) => {
if (!value.startsWith(`[`))
value = `[${value}`;
if (!value.endsWith(`]`))
value = `${value}]`;
return value;
};
const setFormat = (bud, value) => {
value = formatHashString(value);
bud.hooks
.on(`value.hashFormat`, value)
.api.logger.log(`bud.hash: hash format set to`, value);
return bud;
};
const setHash = (bud, value) => {
bud.context.hash = value;
bud.api.logger.log(`bud.hash:`, `hash`, value ? `enabled` : `disabled`);
return bud;
};