Actualización

This commit is contained in:
Xes
2025-04-10 12:53:50 +02:00
parent f7a0ba2b2f
commit 2001ceddea
39284 changed files with 991962 additions and 0 deletions

View File

@@ -0,0 +1,59 @@
jest.dontMock("jquery").dontMock("../jquery.timepicker");
import $ from "jquery";
require("../jquery.timepicker");
const TEST_INPUT = "testInput";
beforeEach(() => {
document.body.innerHTML = `<div>
<input type="text" id="${TEST_INPUT}" />
</div>`;
});
test("timepicker initializes", () => {
$(`#${TEST_INPUT}`).timepicker();
});
test("show single string noneOption correctly", () => {
$(`#${TEST_INPUT}`)
.timepicker({
noneOption: "----"
})
.timepicker("show");
$(".ui-timepicker-list li:first-child").trigger("click");
expect($(`#${TEST_INPUT}`).val()).toEqual("");
});
test("timepicker can parse time value", () => {
$(`#${TEST_INPUT}`).val("2:37pm");
$(`#${TEST_INPUT}`).timepicker();
const expectedSecondsFromMidnight = 14 * 3600 + 37 * 60;
expect($(`#${TEST_INPUT}`).timepicker("getSecondsFromMidnight")).toEqual(
expectedSecondsFromMidnight
);
});
test("timepicker can tolerate undefined values", () => {
$(`#${TEST_INPUT}`).val("2:37pm");
$(`#${TEST_INPUT}`).timepicker({ 'disableTimeRanges': null });
});
test("setTime works", () => {
$(`#${TEST_INPUT}`).val("2:37pm");
$(`#${TEST_INPUT}`).timepicker();
$(`#${TEST_INPUT}`).timepicker('setTime', 43200);
expect($(`#${TEST_INPUT}`).val()).toEqual("12:00pm");
$(`#${TEST_INPUT}`).timepicker('setTime', '11pm');
expect($(`#${TEST_INPUT}`).val()).toEqual("11:00pm");
$(`#${TEST_INPUT}`).timepicker('setTime', new Date('December 17, 1995 03:24:00'));
expect($(`#${TEST_INPUT}`).val()).toEqual("3:24am");
});

View File

@@ -0,0 +1,157 @@
// Type definitions for jQuery.timepicker 1.12.0
// https://github.com/jonthornton/jquery-timepicker
/**
* Declaring a namespace because there are several jquery timepickers already out there on DefinitelyTyped. Jt stands for Jon Thornton
*/
declare namespace Jt.Timepicker {
/**
* Options object for the jquery.timepicker
*/
export interface Options {
/**
* Default: 'body'
* Override where the dropdown is appended.
* Takes either a string to use as a selector, a function that gets passed the clicked input element as argument or a jquery object to use directly.
*/
appendTo?: string | JQuery | ((clickedElement: JQuery) => JQuery);
/**
* Default: null
* A class name to apply to the HTML element that contains the timepicker dropdown.
*/
className?: string;
/**
* Default: false
* Close the timepicker when the window is scrolled. (Replicates <select> behavior.)
*/
closeOnWindowScroll?: boolean;
/**
* Default: false
* Disable typing in the timepicker input box; force users to select from list.
* More information https://github.com/jonthornton/jquery-timepicker/issues/425#issuecomment-133262458
*/
disableTextInput?: boolean;
/**
* Default: []
* Disable selection of certain time ranges. Input is an array of time pairs, like `[['3:00am', '4:30am'], ['5:00pm', '8:00pm']].
* The start of the interval will be disabled but the end won't.
*/
disableTimeRanges?: Array<string[]>;
/**
* Default: false
* Disables the onscreen keyboard for touch devices. There can be instances where Firefox or Chrome have touch events enabled
* (such as on Surface tablets but not actually be a touch device. In this case disableTouchKeyboard will prevent the timepicker
* input field from being focused.
* More information: https://github.com/jonthornton/jquery-timepicker/issues/413
*/
disableTouchKeyboard?: boolean;
/**
* Default: Same as the minTime
* The time against which showDuration will compute relative times. This should be given as a formatted date string.
*/
durationTime?: string | Date | (() => string | Date);
/**
* Default: false
* Force update the time to step settings as soon as it loses focus`.
*/
forceRoundTime?: boolean;
/**
* Default: 24 hours after minTime
* The time that should appear last in the dropdown list. Can be used to limit the range of time options.
*/
listWidth?: number;
/**
* Default: null
* Set this to override CSS styling and set the list width to match the input element's width. Set to 1 to match input width, 2 to double input width, .5 to halve input width, etc. Set to `null` to let CSS determine the list width.
*/
maxTime?: Date | string;
/**
* Default: 12:00 am
* The time that should appear first in the dropdown list.
*/
minTime?: Date | string;
/**
* Default: false.
* Adds one or more custom options to the top of the dropdown. Can accept several different value types:
* Boolean (true): Adds a "None" option that results in an empty input value
* String: Adds an option with a custom label that results in an empty input value
* Object: Similar to string, but allows customizing the element's class name and the resulting input value. Can contain label, value, and className properties. The value property must be a string type.
* Array: An array of strings or objects to add multiple non-time options
*/
noneOption?: boolean | string | string[] | NoneObject;
/**
* default: 'l'
* By default the timepicker dropdown will be aligned to the bottom right of the input element, or aligned to the top left if there isn't enough room below the input. Force alignment with l (left), r (right), t (top), and b (bottom). Examples: tl, rb.
*/
orientation?: string;
/**
* Default: Rounds to the nearest step
* Function used to compute rounded times. The function will receive time in seconds and a settings object as arguments. The function should handle a null value for seconds
*/
roundingFunction?: (seconds: number, settings: Options) => number;
/**
* Default: null
* If no time value is selected, set the dropdown scroll position to show the time provided, e.g. "09:00". A time string, Date object, or integer (seconds past midnight) is acceptible, as well as the string 'now'
*/
scrollDefault?: string | Date | number | {};
/**
* Default: false
* Update the input with the currently highlighted time value when the timepicker loses focus.
*/
selectOnBlur?: boolean;
/**
* Default: false
* Show "24:00" as an option when using 24-hour time format
*/
show2400?: boolean;
/**
* Default: false
* Shows the relative time for each item in the dropdown. minTime or durationTime must be set.
*/
showDuration?: boolean;
/**
* Default: ["click", "focus"]
* Display a timepicker dropdown when the input fires a particular event. Set to null or an empty array to disable automatic display. Setting should be an array of strings
*/
showOn?: string[];
/**
* @deprecated Display a timepicker dropdown when the input gains focus.
* Default: true
*/
showOnFocus?: boolean;
/**
* Default: 30
* The amount of time, in minutes, between each item in the dropdown. Alternately, you can specify a function to generate steps dynamically. The function will receive a count integer (0, 1, 2...) and is expected to return a step integer.
*/
step?: number;
/**
* Default: false
* When scrolling on the edge of the picker, it prevent parent containers () to scroll
*/
stopScrollPropagation?: boolean;
/**
* Default: 'g:ia'
* How times should be displayed in the list and input element. Uses PHP's date() formatting syntax. Characters can be escaped with a preceeding double slash (e.g. H\\hi). Alternatively, you can specify a function instead of a string, to use completely custom time formatting. In this case, * the format function receives a Date object and is expected to return a formatted time as a string
*/
timeFormat?: string | ((givenDate: Date) => string);
/**
* Default: true
* Highlight the nearest corresponding time option as a value is typed into the form input.
*/
typeaheadHighlight?: boolean;
/**
* Default: false
* Convert the input to an HTML <SELECT> control. This is ideal for small screen devices, or if you want to prevent the user from entering
* arbitrary values. This option is not compatible with the following options: appendTo, closeOnWindowScroll, disableTouchKeyboard,
* scrollDefault, selectOnBlur, typeAheadHighlight.
*/
useSelect?: boolean;
}
export interface NoneObject {
label: string;
value: string;
className: string;
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,72 @@
.ui-timepicker-wrapper {
overflow-y: auto;
max-height: 150px;
width: 6.5em;
background: #fff;
border: 1px solid #ddd;
-webkit-box-shadow:0 5px 10px rgba(0,0,0,0.2);
-moz-box-shadow:0 5px 10px rgba(0,0,0,0.2);
box-shadow:0 5px 10px rgba(0,0,0,0.2);
outline: none;
z-index: 10052;
margin: 0;
}
.ui-timepicker-wrapper.ui-timepicker-with-duration {
width: 13em;
}
.ui-timepicker-wrapper.ui-timepicker-with-duration.ui-timepicker-step-30,
.ui-timepicker-wrapper.ui-timepicker-with-duration.ui-timepicker-step-60 {
width: 11em;
}
.ui-timepicker-list {
margin: 0;
padding: 0;
list-style: none;
}
.ui-timepicker-duration {
margin-left: 5px; color: #888;
}
.ui-timepicker-list:hover .ui-timepicker-duration {
color: #888;
}
.ui-timepicker-list li {
padding: 3px 0 3px 5px;
cursor: pointer;
white-space: nowrap;
color: #000;
list-style: none;
margin: 0;
}
.ui-timepicker-list:hover .ui-timepicker-selected {
background: #fff; color: #000;
}
li.ui-timepicker-selected,
.ui-timepicker-list li:hover,
.ui-timepicker-list .ui-timepicker-selected:hover {
background: #1980EC; color: #fff;
}
li.ui-timepicker-selected .ui-timepicker-duration,
.ui-timepicker-list li:hover .ui-timepicker-duration {
color: #ccc;
}
.ui-timepicker-list li.ui-timepicker-disabled,
.ui-timepicker-list li.ui-timepicker-disabled:hover,
.ui-timepicker-list li.ui-timepicker-selected.ui-timepicker-disabled {
color: #888;
cursor: default;
}
.ui-timepicker-list li.ui-timepicker-disabled:hover,
.ui-timepicker-list li.ui-timepicker-selected.ui-timepicker-disabled {
background: #f2f2f2;
}

View File

@@ -0,0 +1,3 @@
const ONE_DAY = 86400;
export { ONE_DAY };

View File

@@ -0,0 +1,43 @@
import roundingFunction from "./rounding";
const DEFAULT_SETTINGS = {
appendTo: "body",
className: null,
closeOnWindowScroll: false,
disableTextInput: false,
disableTimeRanges: [],
disableTouchKeyboard: false,
durationTime: null,
forceRoundTime: false,
lang: {},
maxTime: null,
minTime: null,
noneOption: false,
orientation: "l",
roundingFunction,
scrollDefault: null,
selectOnBlur: false,
show2400: false,
showDuration: false,
showOn: ["click", "focus"],
showOnFocus: true,
step: 30,
stopScrollPropagation: false,
timeFormat: "g:ia",
typeaheadHighlight: true,
useSelect: false,
wrapHours: true
};
const DEFAULT_LANG = {
am: "am",
pm: "pm",
AM: "AM",
PM: "PM",
decimal: ".",
mins: "mins",
hr: "hr",
hrs: "hrs"
};
export { DEFAULT_SETTINGS, DEFAULT_LANG };

View File

@@ -0,0 +1,197 @@
import { DEFAULT_SETTINGS, DEFAULT_LANG } from "./defaults";
import { ONE_DAY } from "./constants";
class Timepicker {
constructor(targetEl, options = {}) {
const attrOptions = Timepicker.extractAttrOptions(
targetEl,
Object.keys(DEFAULT_SETTINGS)
);
this.settings = this.parseSettings({
...DEFAULT_SETTINGS,
...options,
...attrOptions
});
}
static extractAttrOptions(element, keys) {
const output = {};
for (const key of keys) {
// console.log(key, element)
if (key in element.dataset) {
output[key] = element.dataset[key];
}
}
return output;
}
time2int(timeString) {
if (timeString === "" || timeString === null || timeString === undefined)
return null;
if (timeString instanceof Date) {
return (
timeString.getHours() * 3600 +
timeString.getMinutes() * 60 +
timeString.getSeconds()
);
}
if (typeof timeString != "string") {
return timeString;
}
timeString = timeString.toLowerCase().replace(/[\s\.]/g, "");
// if the last character is an "a" or "p", add the "m"
if (timeString.slice(-1) == "a" || timeString.slice(-1) == "p") {
timeString += "m";
}
var pattern = /^(([^0-9]*))?([0-9]?[0-9])(\W?([0-5][0-9]))?(\W+([0-5][0-9]))?(([^0-9]*))$/;
var time = timeString.match(pattern);
if (!time) {
return null;
}
var hour = parseInt(time[3] * 1, 10);
var ampm = time[2] || time[9];
var hours = hour;
var minutes = time[5] * 1 || 0;
var seconds = time[7] * 1 || 0;
if (hour <= 12 && ampm) {
ampm = ampm.trim();
var isPm = ampm == this.settings.lang.pm || ampm == this.settings.lang.PM;
if (hour == 12) {
hours = isPm ? 12 : 0;
} else {
hours = hour + (isPm ? 12 : 0);
}
} else {
var t = hour * 3600 + minutes * 60 + seconds;
if (t >= ONE_DAY + (this.settings.show2400 ? 1 : 0)) {
if (this.settings.wrapHours === false) {
return null;
}
hours = hour % 24;
}
}
var timeInt = hours * 3600 + minutes * 60 + seconds;
// if no am/pm provided, intelligently guess based on the scrollDefault
if (
hour < 12 &&
!ampm &&
this.settings._twelveHourTime &&
this.settings.scrollDefault
) {
var delta = timeInt - this.settings.scrollDefault();
if (delta < 0 && delta >= ONE_DAY / -2) {
timeInt = (timeInt + ONE_DAY / 2) % ONE_DAY;
}
}
return timeInt;
}
parseSettings(settings) {
settings.lang = { ...DEFAULT_LANG, ...settings.lang };
// lang is used by other functions the rest of this depends on
// todo: unwind circular dependency on lang
this.settings = settings;
if (settings.minTime) {
settings.minTime = this.time2int(settings.minTime);
}
if (settings.maxTime) {
settings.maxTime = this.time2int(settings.maxTime);
}
if (settings.durationTime && typeof settings.durationTime !== "function") {
settings.durationTime = this.time2int(settings.durationTime);
}
if (settings.scrollDefault == "now") {
settings.scrollDefault = () => {
return settings.roundingFunction(this.time2int(new Date()), settings);
};
} else if (
settings.scrollDefault &&
typeof settings.scrollDefault != "function"
) {
var val = settings.scrollDefault;
settings.scrollDefault = () => {
return settings.roundingFunction(this.time2int(val), settings);
};
} else if (settings.minTime) {
settings.scrollDefault = function() {
return settings.roundingFunction(settings.minTime, settings);
};
}
if (
typeof settings.timeFormat === "string" &&
settings.timeFormat.match(/[gh]/)
) {
settings._twelveHourTime = true;
}
if (
settings.showOnFocus === false &&
settings.showOn.indexOf("focus") != -1
) {
settings.showOn.splice(settings.showOn.indexOf("focus"), 1);
}
if (!settings.disableTimeRanges) {
settings.disableTimeRanges = [];
}
if (settings.disableTimeRanges.length > 0) {
// convert string times to integers
for (var i in settings.disableTimeRanges) {
settings.disableTimeRanges[i] = [
this.time2int(settings.disableTimeRanges[i][0]),
this.time2int(settings.disableTimeRanges[i][1])
];
}
// sort by starting time
settings.disableTimeRanges = settings.disableTimeRanges.sort(function(
a,
b
) {
return a[0] - b[0];
});
// merge any overlapping ranges
for (var i = settings.disableTimeRanges.length - 1; i > 0; i--) {
if (
settings.disableTimeRanges[i][0] <=
settings.disableTimeRanges[i - 1][1]
) {
settings.disableTimeRanges[i - 1] = [
Math.min(
settings.disableTimeRanges[i][0],
settings.disableTimeRanges[i - 1][0]
),
Math.max(
settings.disableTimeRanges[i][1],
settings.disableTimeRanges[i - 1][1]
)
];
settings.disableTimeRanges.splice(i, 1);
}
}
}
return settings;
}
}
export default Timepicker;

View File

@@ -0,0 +1,37 @@
import { ONE_DAY } from "./constants";
const roundingFunction = (seconds, settings) => {
if (seconds === null) {
return null;
} else if (typeof settings.step !== "number") {
// TODO: nearest fit irregular steps
return seconds;
} else {
var offset = seconds % (settings.step * 60); // step is in minutes
var start = settings.minTime || 0;
// adjust offset by start mod step so that the offset is aligned not to 00:00 but to the start
offset -= start % (settings.step * 60);
if (offset >= settings.step * 30) {
// if offset is larger than a half step, round up
seconds += settings.step * 60 - offset;
} else {
// round down
seconds -= offset;
}
return _moduloSeconds(seconds, settings);
}
};
function _moduloSeconds(seconds, settings) {
if (seconds == ONE_DAY && settings.show2400) {
return seconds;
}
return seconds % ONE_DAY;
}
export default roundingFunction;