mami/src/mami.js/title.js
2024-02-09 00:56:27 +00:00

77 lines
2.3 KiB
JavaScript

#include args.js
const MamiWindowTitle = function(options) {
options = MamiArguments.verify(options, [
MamiArguments.type('getName', 'function', () => ''),
MamiArguments.type('setTitle', 'function', text => document.title = text),
MamiArguments.check('strobeInterval', 500, val => {
const valType = typeof val;
return val === 'number' || val === 'function';
}),
MamiArguments.check('strobeRepeat', 5, val => {
const valType = typeof val;
return val === 'number' || val === 'function';
}),
]);
const getName = options.getName;
const setTitleImpl = options.setTitle;
const setTitle = text => {
if(text === undefined || text === null)
text = '';
else if(typeof text !== 'string')
text = text.toString();
setTitleImpl(text);
};
const defaultStrobeInterval = typeof options.strobeInterval === 'function' ? options.strobeInterval : () => options.strobeInterval;
const defaultStrobeRepeat = typeof options.strobeRepeat === 'function' ? options.strobeRepeat : () => options.strobeRepeat;
let activeStrobe;
const clearTitle = () => {
if(activeStrobe === undefined)
return;
clearInterval(activeStrobe);
activeStrobe = undefined;
setTitle(getName());
};
const strobeTitle = (titles, interval, repeat) => {
if(!Array.isArray(titles))
throw 'titles must be an array of strings';
if(titles.length < 1)
throw 'titles must contain at least one item';
if(typeof interval !== 'number')
interval = defaultStrobeInterval();
if(typeof repeat !== 'number')
repeat = defaultStrobeRepeat();
const target = titles.length * repeat;
let round = 0;
clearTitle();
setTitle(titles[0]);
activeStrobe = setInterval(() => {
if(round >= target) {
clearTitle();
setTitle(getName());
return;
}
++round;
setTitle(titles[round % titles.length]);
}, interval);
};
return {
set: setTitle,
clear: clearTitle,
strobe: strobeTitle,
};
};