repo
stringlengths
5
106
file_url
stringlengths
78
301
file_path
stringlengths
4
211
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 14:56:49
2026-01-05 02:23:25
truncated
bool
2 classes
iamkun/dayjs
https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/test/plugin/localeData.test.js
test/plugin/localeData.test.js
import MockDate from 'mockdate' import moment from 'moment' import dayjs from '../../src' import '../../src/locale/fr' import '../../src/locale/ru' import '../../src/locale/zh-cn' import localeData from '../../src/plugin/localeData' import localizedFormat from '../../src/plugin/localizedFormat' dayjs.extend(localizedFormat) dayjs.extend(localeData) beforeEach(() => { MockDate.set(new Date()) }) afterEach(() => { MockDate.reset() }) describe('Instance localeData', () => { ['zh-cn', 'en', 'fr'].forEach((lo) => { it(`Locale: ${lo}`, () => { dayjs.locale(lo) moment.locale(lo) const d = dayjs() const m = moment() const dayjsLocaleData = dayjs().localeData() const momentLocaleData = moment().localeData() expect(dayjsLocaleData.firstDayOfWeek()).toBe(momentLocaleData.firstDayOfWeek()) expect(dayjsLocaleData.months(d)).toBe(momentLocaleData.months(m)) expect(dayjsLocaleData.months()).toEqual(momentLocaleData.months()) expect(dayjsLocaleData.monthsShort(d)).toBe(momentLocaleData.monthsShort(m)) expect(dayjsLocaleData.monthsShort()).toEqual(momentLocaleData.monthsShort()) expect(dayjsLocaleData.weekdays(d)).toBe(momentLocaleData.weekdays(m)) expect(dayjsLocaleData.weekdays()).toEqual(momentLocaleData.weekdays()) expect(dayjsLocaleData.weekdaysMin(d)).toBe(momentLocaleData.weekdaysMin(m)) expect(dayjsLocaleData.weekdaysMin()).toEqual(momentLocaleData.weekdaysMin()) expect(dayjsLocaleData.weekdaysShort(d)).toBe(momentLocaleData.weekdaysShort(m)) expect(dayjsLocaleData.weekdaysShort()).toEqual(momentLocaleData.weekdaysShort()) const longDateFormats = ['LT', 'LTS', 'L', 'LL', 'LLL', 'LLLL', 'l', 'll', 'lll', 'llll'] longDateFormats.forEach((f) => { expect(dayjsLocaleData.longDateFormat(f)).toEqual(momentLocaleData.longDateFormat(f)) }) }) }) dayjs.locale('en') moment.locale('en') }) it('Global localeData', () => { ['zh-cn', 'en', 'fr'].forEach((lo) => { dayjs.locale(lo) moment.locale(lo) const dayjsLocaleData = dayjs.localeData() const momentLocaleData = moment.localeData() expect(dayjsLocaleData.firstDayOfWeek()).toBe(momentLocaleData.firstDayOfWeek()) expect(dayjsLocaleData.months()).toEqual(momentLocaleData.months()) expect(dayjsLocaleData.monthsShort()).toEqual(momentLocaleData.monthsShort()) expect(dayjsLocaleData.weekdays()).toEqual(momentLocaleData.weekdays()) expect(dayjsLocaleData.weekdaysShort()).toEqual(momentLocaleData.weekdaysShort()) expect(dayjsLocaleData.weekdaysMin()).toEqual(momentLocaleData.weekdaysMin()) const longDateFormats = ['LT', 'LTS', 'L', 'LL', 'LLL', 'LLLL', 'l', 'll', 'lll', 'llll'] longDateFormats.forEach((f) => { expect(dayjsLocaleData.longDateFormat(f)).toEqual(momentLocaleData.longDateFormat(f)) }) }) }) it('Listing the months and weekdays', () => { ['zh-cn', 'en', 'fr'].forEach((lo) => { dayjs.locale(lo) moment.locale(lo) expect(dayjs.months()).toEqual(moment.months()) expect(dayjs.monthsShort()).toEqual(moment.monthsShort()) expect(dayjs.weekdays()).toEqual(moment.weekdays()) expect(dayjs.weekdaysShort()).toEqual(moment.weekdaysShort()) expect(dayjs.weekdaysMin()).toEqual(moment.weekdaysMin()) }) }) it('Month function', () => { const dayjsLocaleData = dayjs().locale('ru').localeData() const momentLocaleData = moment().locale('ru').localeData() expect(dayjsLocaleData.months()).toEqual(momentLocaleData.months()) expect(dayjsLocaleData.monthsShort()).toEqual(momentLocaleData.monthsShort()) dayjs.locale('ru') moment.locale('ru') expect(dayjs.months()).toEqual(moment.months()) expect(dayjs.monthsShort()).toEqual(moment.monthsShort()) }) it('Locale order', () => { dayjs.locale('fr') moment.locale('fr') expect(dayjs.weekdays(true)).toEqual(moment.weekdays(true)) expect(dayjs.weekdaysShort(true)).toEqual(moment.weekdaysShort(true)) expect(dayjs.weekdaysMin(true)).toEqual(moment.weekdaysMin(true)) expect(dayjs.weekdays()).not.toEqual(dayjs.weekdays(true)) dayjs.locale('en') moment.locale('en') expect(dayjs.weekdays(true)).toEqual(moment.weekdays(true)) }) it('meridiem', () => { dayjs.locale('zh-cn') expect(typeof dayjs.localeData().meridiem).toEqual('function') expect(typeof dayjs().localeData().meridiem).toEqual('function') dayjs.locale('en') }) it('ordinal', () => { dayjs.locale('zh-cn') expect(typeof dayjs.localeData().ordinal).toEqual('function') expect(typeof dayjs().localeData().ordinal).toEqual('function') dayjs.locale('en') })
javascript
MIT
54f447048cee679e51a7053f8042d9b6b7028b89
2026-01-04T14:57:31.496629Z
false
iamkun/dayjs
https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/test/plugin/advancedFormat.test.js
test/plugin/advancedFormat.test.js
import MockDate from 'mockdate' import moment from 'moment' import dayjs from '../../src' import advancedFormat from '../../src/plugin/advancedFormat' import isoWeek from '../../src/plugin/isoWeek' import weekOfYear from '../../src/plugin/weekOfYear' import weekYear from '../../src/plugin/weekYear' import timezone from '../../src/plugin/timezone' import utc from '../../src/plugin/utc' import '../../src/locale/zh-cn' import '../../src/locale/nl' dayjs.extend(utc) dayjs.extend(timezone) dayjs.extend(isoWeek) dayjs.extend(weekYear) dayjs.extend(weekOfYear) dayjs.extend(advancedFormat) beforeEach(() => { MockDate.set(new Date()) }) afterEach(() => { MockDate.reset() }) it('Format of invalid date', () => { expect(dayjs(null).format('z').toLowerCase()).toEqual(moment(null).format('z').toLowerCase()) }) it('Format empty string', () => { expect(dayjs().format()).toBe(moment().format()) }) it('Format Quarter Q', () => { expect(dayjs().format('Q')).toBe(moment().format('Q')) }) it('Format Timestamp X x', () => { expect(dayjs().format('X')).toBe(moment().format('X')) expect(dayjs().format('x')).toBe(moment().format('x')) }) it('Format Day of Month Do 1 - 31', () => { expect(dayjs().format('Do')).toBe(moment().format('Do')) let d = '2018-05-02 00:00:00.000' expect(dayjs(d).format('Do')).toBe(moment(d).format('Do')) d = '2018-05-01 00:00:00.000' expect(dayjs(d).format('Do')).toBe(moment(d).format('Do')) d = '2018-05-03 00:00:00.000' expect(dayjs(d).format('Do')).toBe(moment(d).format('Do')) d = '2018-05-04 00:00:00.000' expect(dayjs(d).format('Do')).toBe(moment(d).format('Do')) d = '2018-05-08 00:00:00.000' expect(dayjs(d).locale('nl').format('Do')).toBe(moment(d).locale('nl').format('Do')) d = '2018-05-11' expect(dayjs(d).format('Do')).toBe(moment(d).format('Do')) d = '2018-05-12' expect(dayjs(d).format('Do')).toBe(moment(d).format('Do')) d = '2018-05-13' expect(dayjs(d).format('Do')).toBe(moment(d).format('Do')) d = '2018-05-19 00:00:00.000' expect(dayjs(d).locale('nl').format('Do')).toBe(moment(d).locale('nl').format('Do')) d = '2018-05-22' expect(dayjs(d).format('Do')).toBe(moment(d).format('Do')) }) it('Format Hour k kk 24-hour 1 - 24', () => { expect(dayjs().format('k')).toBe(moment().format('k')) expect(dayjs().format('kk')).toBe(moment().format('kk')) let d = '2018-05-02 00:00:00.000' expect(dayjs(d).format('k')).toBe('24') expect(dayjs(d).format('k')).toBe(moment(d).format('k')) expect(dayjs(d).format('kk')).toBe('24') expect(dayjs(d).format('kk')).toBe(moment(d).format('kk')) d = '2018-05-02 01:00:00.000' expect(dayjs(d).format('k')).toBe('1') expect(dayjs(d).format('k')).toBe(moment(d).format('k')) expect(dayjs(d).format('kk')).toBe('01') expect(dayjs(d).format('kk')).toBe(moment(d).format('kk')) d = '2018-05-02 23:59:59.999' expect(dayjs(d).format('k')).toBe('23') expect(dayjs(d).format('k')).toBe(moment(d).format('k')) expect(dayjs(d).format('kk')).toBe('23') expect(dayjs(d).format('kk')).toBe(moment(d).format('kk')) }) it('Format Week of Year wo', () => { const d = '2018-12-01' expect(dayjs(d).format('wo')).toBe(moment(d).format('wo')) expect(dayjs(d).locale('zh-cn').format('wo')) .toBe(moment(d).locale('zh-cn').format('wo')) }) it('Format Week of Year wo', () => { const d = '2018-12-01' expect(dayjs(d).format('wo')).toBe(moment(d).format('wo')) expect(dayjs(d).locale('zh-cn').format('wo')) .toBe(moment(d).locale('zh-cn').format('wo')) }) it('Format Week Year gggg', () => { const d = '2018-12-31' expect(dayjs(d).format('gggg')).toBe(moment(d).format('gggg')) }) it('Format Iso Week Year GGGG', () => { const d = '2021-01-01' expect(dayjs(d).format('GGGG')).toBe(moment(d).format('GGGG')) }) it('Format Iso Week of Year', () => { const d = '2021-01-01' expect(dayjs(d).format('W')).toBe(moment(d).format('W')) expect(dayjs(d).format('WW')).toBe(moment(d).format('WW')) }) it('Format offsetName z zzz', () => { const dtz = dayjs.tz('2012-03-11 01:59:59', 'America/New_York') expect(dtz.format('z')).toBe('EST') expect(dtz.format('zzz')).toBe('Eastern Standard Time') expect(dayjs().format('z')).toBeDefined() expect(dayjs().format('zzz')).toBeDefined() }) it('Skips format strings inside brackets', () => { expect(dayjs().format('[Q]')).toBe('Q') expect(dayjs().format('[Do]')).toBe('Do') expect(dayjs().format('[gggg]')).toBe('gggg') expect(dayjs().format('[GGGG]')).toBe('GGGG') expect(dayjs().format('[w]')).toBe('w') expect(dayjs().format('[ww]')).toBe('ww') expect(dayjs().format('[W]')).toBe('W') expect(dayjs().format('[WW]')).toBe('WW') expect(dayjs().format('[wo]')).toBe('wo') expect(dayjs().format('[k]')).toBe('k') expect(dayjs().format('[kk]')).toBe('kk') expect(dayjs().format('[X]')).toBe('X') expect(dayjs().format('[x]')).toBe('x') })
javascript
MIT
54f447048cee679e51a7053f8042d9b6b7028b89
2026-01-04T14:57:31.496629Z
false
iamkun/dayjs
https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/test/plugin/toObject.test.js
test/plugin/toObject.test.js
import MockDate from 'mockdate' import moment from 'moment' import dayjs from '../../src' import toObject from '../../src/plugin/toObject' dayjs.extend(toObject) beforeEach(() => { MockDate.set(new Date()) }) afterEach(() => { MockDate.reset() }) it('As Object -> toObject', () => { expect(dayjs().toObject()).toEqual(moment().toObject()) })
javascript
MIT
54f447048cee679e51a7053f8042d9b6b7028b89
2026-01-04T14:57:31.496629Z
false
iamkun/dayjs
https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/test/plugin/calendar.test.js
test/plugin/calendar.test.js
import MockDate from 'mockdate' import moment from 'moment' import dayjs from '../../src' import calendar from '../../src/plugin/calendar' import zhCn from '../../src/locale/zh-cn' dayjs.extend(calendar) beforeEach(() => { MockDate.set(new Date()) }) afterEach(() => { MockDate.reset() }) it('No argument && null && undefined', () => { expect(dayjs().calendar()).toEqual(moment().calendar()) // [email protected] does not support calendar(null) calendar(undefined) }) it('ReferenceTime', () => { const now = '2015-01-15T14:21:22.000Z' const dates = [ { name: 'nextDay', date: '2015-01-14T11:23:55.000Z', result: 'Tomorrow' }, { name: 'sameDay', date: '2015-01-15T11:23:55.000Z', result: 'Today' }, { name: 'nextWeek', date: '2015-01-09T11:23:55.000Z', result: 'Thursday' }, { name: 'lastDay', date: '2015-01-16T11:23:55.000Z', result: 'Yesterday' }, { name: 'lastWeek', date: '2015-01-21T11:23:55.000Z', result: 'Last' }, { name: 'sameElse', date: '2015-01-01T11:23:55.000Z', result: '01/15/2015' }, { name: 'sameElse', date: '2015-02-21T11:23:55.000Z', result: '01/15/2015' } ] dates.forEach((d) => { const dayjsResult = dayjs(now).calendar(d.date) const momentjsResult = moment(now).calendar(d.date) expect(dayjsResult) .toEqual(momentjsResult) expect(dayjsResult.indexOf(d.result) > -1) .toBe(true) }) }) it('Custom format', () => { const format = { sameDay: '[sameDay]', sameElse: '[sameElse]' } expect(dayjs().calendar(null, format)).toEqual(moment().calendar(null, format)) const now = '2015-01-15T14:21:22.000Z' const nextDayWithoutFormat = '2015-01-14T11:23:55.000Z' expect(dayjs(now).calendar(nextDayWithoutFormat, format)) .toEqual(moment(now).calendar(nextDayWithoutFormat, format)) }) it('Custom callback', () => { const callbacks = { sameDay: jest.fn(), sameElse: jest.fn() } const now = '2015-01-15T14:21:22.000Z' const nextDayWithoutFormat = '2015-01-14T11:23:55.000Z' expect(dayjs(now).calendar(nextDayWithoutFormat, callbacks)) .toEqual(moment(now).calendar(nextDayWithoutFormat, callbacks)) }) it('Calls callback', () => { const callbacks = { sameDay: jest.fn(), sameElse: jest.fn() } dayjs().calendar(null, callbacks) expect(callbacks.sameElse).not.toBeCalled() expect(callbacks.sameDay).toBeCalled() }) it('callback is a function with the scope of the current moment', () => { const callbacks = { sameDay: jest.fn() } expect(dayjs().calendar(null, callbacks)).toEqual(callbacks.sameDay()) const callbacks2 = { sameDay: function cb() { return this } } const result = dayjs().calendar(null, callbacks2) expect(result.format).not.toBeUndefined() expect(dayjs.isDayjs(result)).toBeTruthy() }) it('callback is a function and first argument a moment that depicts now', () => { const callbacks = { sameDay: jest.fn() } const now = dayjs() dayjs(now).calendar(now, callbacks) expect(callbacks.sameDay).toBeCalledWith(now) }) it('set global calendar in locale file', () => { const now = '2019-04-03T14:21:22.000Z' zhCn.calendar = { sameDay: '[今天]HH:mm', nextDay: '[明天]HH:mm', nextWeek: '[下]ddddHH:mm', lastDay: '[昨天]HH:mm', lastWeek: '[上]ddddHH:mm', sameElse: 'YYYY/MM/DD' } dayjs.locale(zhCn) expect(dayjs(now).calendar()) .toEqual(moment(now).locale('zh-cn').calendar()) })
javascript
MIT
54f447048cee679e51a7053f8042d9b6b7028b89
2026-01-04T14:57:31.496629Z
false
iamkun/dayjs
https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/test/plugin/dayOfYear.test.js
test/plugin/dayOfYear.test.js
import MockDate from 'mockdate' import moment from 'moment' import dayjs from '../../src' import dayOfYear from '../../src/plugin/dayOfYear' dayjs.extend(dayOfYear) beforeEach(() => { MockDate.set(new Date()) }) afterEach(() => { MockDate.reset() }) it('DayOfYear get', () => { expect(dayjs().dayOfYear()).toBe(moment().dayOfYear()) expect(dayjs('2015-01-01T00:00:00.000').dayOfYear()).toBe(1) expect(dayjs('2015-01-31T00:00:00.000').dayOfYear()).toBe(31) expect(dayjs('2015-02-01T00:00:00.000').dayOfYear()).toBe(32) expect(dayjs('2015-02-28T00:00:00.000').dayOfYear()).toBe(59) expect(dayjs('2015-12-31T00:00:00.000').dayOfYear()).toBe(365) }) it('DayOfYear set', () => { expect(dayjs().dayOfYear(4).dayOfYear()).toBe(moment().dayOfYear(4).dayOfYear()) expect(dayjs('2015-01-01T00:00:00.000Z') .dayOfYear(4) .dayOfYear()).toBe(4) expect(dayjs('2015-01-01T00:00:00.000Z') .dayOfYear(4) .toISOString()).toBe('2015-01-04T00:00:00.000Z') expect(dayjs('2015-01-01T00:00:00.000Z') .dayOfYear(32) .dayOfYear()).toBe(32) expect(dayjs('2015-01-01T00:00:00.000Z') .dayOfYear(32) .toISOString()).toBe('2015-02-01T00:00:00.000Z') expect(dayjs('2015-01-01T00:00:00.000Z') .dayOfYear(365) .dayOfYear()).toBe(365) expect(dayjs('2015-01-01T00:00:00.000Z') .dayOfYear(365) .toISOString()).toBe('2015-12-31T00:00:00.000Z') })
javascript
MIT
54f447048cee679e51a7053f8042d9b6b7028b89
2026-01-04T14:57:31.496629Z
false
iamkun/dayjs
https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/test/plugin/weekday.test.js
test/plugin/weekday.test.js
import MockDate from 'mockdate' import moment from 'moment' import dayjs from '../../src' import weekday from '../../src/plugin/weekday' import '../../src/locale/zh-cn' import '../../src/locale/ar' dayjs.extend(weekday) beforeEach(() => { MockDate.set(new Date()) }) afterEach(() => { MockDate.reset() moment.locale('en') dayjs.locale('en') }) it('Sunday is the first day of the week', () => { expect(dayjs().weekday()).toBe(moment().weekday()) expect(dayjs().weekday(0).date()).toBe(moment().weekday(0).date()) expect(dayjs().weekday(-7).format()).toBe(moment().weekday(-7).format()) expect(dayjs().weekday(7).format()).toBe(moment().weekday(7).format()) }) it('Monday is the first day of the week', () => { moment.locale('zh-cn') dayjs.locale('zh-cn') expect(dayjs().weekday()).toBe(moment().weekday()) expect(dayjs().weekday(0).date()).toBe(moment().weekday(0).date()) expect(dayjs().weekday(-7).format()).toBe(moment().weekday(-7).format()) expect(dayjs().weekday(7).format()).toBe(moment().weekday(7).format()) const d1 = '2020-01-05' expect(dayjs(d1).weekday()).toBe(moment(d1).weekday()) const d2 = '2020-01-07' expect(dayjs(d2).weekday()).toBe(moment(d2).weekday()) }) it('Saturday is the first day of the week', () => { moment.locale('ar') dayjs.locale('ar') expect(dayjs().weekday()).toBe(moment().weekday()) expect(dayjs().weekday(0).date()).toBe(moment().weekday(0).date()) expect(dayjs().weekday(-7).valueOf()).toBe(moment().weekday(-7).valueOf()) expect(dayjs().weekday(7).valueOf()).toBe(moment().weekday(7).valueOf()) })
javascript
MIT
54f447048cee679e51a7053f8042d9b6b7028b89
2026-01-04T14:57:31.496629Z
false
iamkun/dayjs
https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/test/locale/be.test.js
test/locale/be.test.js
import MockDate from 'mockdate' import moment from 'moment' import dayjs from '../../src' import '../../src/locale/be' import relativeTime from '../../src/plugin/relativeTime' dayjs.extend(relativeTime) beforeEach(() => { MockDate.set(new Date()) }) afterEach(() => { MockDate.reset() }) it('Belarusian locale relative time in past and future with suffix', () => { const cases = [ [1, 's', 'праз некалькі секунд'], [-1, 's', 'некалькі секунд таму'], [1, 'm', 'праз хвіліну'], [-1, 'm', 'хвіліну таму'], [1, 'h', 'праз гадзіну'], [-1, 'h', 'гадзіну таму'], [1, 'd', 'праз дзень'], [-1, 'd', 'дзень таму'], [1, 'M', 'праз месяц'], [-1, 'M', 'месяц таму'], [2, 'd', 'праз 2 дні'], [-2, 'd', '2 дні таму'], [10, 'd', 'праз 10 дзён'], [-10, 'd', '10 дзён таму'], [6, 'm', 'праз 6 хвілін'], [-6, 'm', '6 хвілін таму'], [5, 'h', 'праз 5 гадзін'], [-5, 'h', '5 гадзін таму'], [3, 'M', 'праз 3 месяцы'], [-3, 'M', '3 месяцы таму'], [4, 'y', 'праз 4 гады'], [-4, 'y', '4 гады таму'] ] const locales = ['be'] locales.forEach((locale) => { cases.forEach((c) => { expect(dayjs() .add(c[0], c[1]) .locale(locale) .fromNow()).toBe(c[2]) expect(dayjs() .add(c[0], c[1]) .locale(locale) .fromNow()).toBe(moment() .add(c[0], c[1]) .locale(locale) .fromNow()) }) }) }) it('Belarusian locale relative time in past and future without suffix', () => { const cases = [ [1, 's', 'некалькі секунд'], [-1, 's', 'некалькі секунд'], [1, 'm', 'хвіліна'], [-1, 'm', 'хвіліна'], [1, 'h', 'гадзіна'], [-1, 'h', 'гадзіна'], // Test all plural forms for days [1, 'd', 'дзень'], [21, 'd', '21 дзень'], [31, 'd', 'месяц'], // 2-4 form [2, 'd', '2 дні'], [3, 'd', '3 дні'], [4, 'd', '4 дні'], // 5-20 and other cases [5, 'd', '5 дзён'], [6, 'd', '6 дзён'], // 11-14 special case [11, 'd', '11 дзён'], [12, 'd', '12 дзён'], [13, 'd', '13 дзён'], [14, 'd', '14 дзён'], // 22-24 [22, 'd', '22 дні'], [23, 'd', '23 дні'], [24, 'd', '24 дні'], // Test all plural forms for months [1, 'M', 'месяц'], [2, 'M', '2 месяцы'], [5, 'M', '5 месяцаў'], // Test all plural forms for years [1, 'y', 'год'], [2, 'y', '2 гады'], [5, 'y', '5 гадоў'], [11, 'y', '11 гадоў'], [21, 'y', '21 год'] ] const locales = ['be'] locales.forEach((locale) => { cases.forEach((c) => { expect(dayjs() .add(c[0], c[1]) .locale(locale) .fromNow(true)).toBe(c[2]) expect(dayjs() .add(c[0], c[1]) .locale(locale) .fromNow(true)).toBe(moment() .add(c[0], c[1]) .locale(locale) .fromNow(true)) }) }) }) it('Belarusian locale formats dates with correct month forms', () => { const tests = [ // Full month names { date: '2022-01-19', format: 'dd, D MMMM YYYY г.', expected: 'ср, 19 студзеня 2022 г.' }, { date: '2022-01-01', format: 'MMMM', expected: 'студзень' }, // Short month names in format form (with day) { date: '2022-01-15', format: 'D MMM', expected: '15 студ' }, { date: '2022-02-15', format: 'D MMM', expected: '15 лют' }, // Short month names in standalone form { date: '2022-01-01', format: 'MMM', expected: 'студ' }, { date: '2022-02-01', format: 'MMM', expected: 'лют' } ] tests.forEach(({ date, format, expected }) => { const dayjsWithLocale = dayjs(date).locale('be') expect(dayjsWithLocale.format(format)).toEqual(expected) }) })
javascript
MIT
54f447048cee679e51a7053f8042d9b6b7028b89
2026-01-04T14:57:31.496629Z
false
iamkun/dayjs
https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/test/locale/keys.test.js
test/locale/keys.test.js
import fs from 'fs' import path from 'path' import dayjs from '../../src' const localeDir = '../../src/locale' const Locale = [] const localeNameRegex = /\/\/ (.*) \[/ // load all locales from locale dir fs.readdirSync(path.join(__dirname, localeDir)) .forEach((file) => { const fPath = path.join(__dirname, localeDir, file) Locale.push({ name: file, // eslint-disable-next-line import/no-dynamic-require, global-require content: require(fPath).default, file: fs.readFileSync(fPath, 'utf-8') }) }) Locale.forEach((locale) => { it(`Locale keys for ${locale.content.name}`, () => { const { name, ordinal, weekdays, months, formats, relativeTime, weekdaysShort, monthsShort, weekdaysMin, weekStart, yearStart, meridiem } = locale.content // comments required const commentsMatchResult = locale.file.match(localeNameRegex) expect(commentsMatchResult[1]).not.toBeUndefined() expect(name).toEqual(locale.name.replace('.js', '')) expect(name).toBe(name.toLowerCase()) expect(weekdays).toEqual(expect.any(Array)) if (weekdaysShort) expect(weekdaysShort).toEqual(expect.any(Array)) if (weekdaysMin) expect(weekdaysMin).toEqual(expect.any(Array)) if (weekStart) expect(weekStart).toEqual(expect.any(Number)) if (yearStart) expect(yearStart).toEqual(expect.any(Number)) // months could be a function or array if (Array.isArray(months)) { expect(months).toEqual(expect.any(Array)) } else { expect(months(dayjs(), 'str')).toEqual(expect.any(String)) expect(months.f).toEqual(expect.any(Array)) expect(months.s).toEqual(expect.any(Array)) } // monthsShort could be a function or array if (monthsShort) { if (Array.isArray(monthsShort)) { expect(monthsShort).toEqual(expect.any(Array)) } else { expect(monthsShort(dayjs(), 'str')).toEqual(expect.any(String)) expect(monthsShort.f).toEqual(expect.any(Array)) expect(monthsShort.s).toEqual(expect.any(Array)) } } // function pass date return string or number or null if (name !== 'en') { // en ordinal set in advancedFormat for (let i = 1; i <= 31; i += 1) { expect(ordinal(i)).toEqual(expect.anything()) } } expect(dayjs().locale(name).$locale().name).toBe(name) if (formats) { const { LT, LTS, L, LL, LLL, LLLL, l, ll, lll, llll, ...remainingFormats } = formats expect(formats).toEqual(expect.objectContaining({ L: expect.any(String), LL: expect.any(String), LLL: expect.any(String), LLLL: expect.any(String), LT: expect.any(String), LTS: expect.any(String) })) expect(Object.keys(remainingFormats).length).toEqual(0) if (l) expect(l).toEqual(expect.any(String)) if (ll) expect(ll).toEqual(expect.any(String)) if (lll) expect(lll).toEqual(expect.any(String)) if (llll) expect(llll).toEqual(expect.any(String)) } if (relativeTime) { expect(Object.keys(relativeTime).sort()).toEqual(['d', 'dd', 'future', 'h', 'hh', 'm', 'mm', 'M', 'MM', 'past', 's', 'y', 'yy'] .sort()) } if (meridiem) { for (let i = 1; i <= 23; i += 1) { expect(meridiem(i)).toEqual(expect.anything()) } } }) })
javascript
MIT
54f447048cee679e51a7053f8042d9b6b7028b89
2026-01-04T14:57:31.496629Z
false
iamkun/dayjs
https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/test/locale/ar-kw.test.js
test/locale/ar-kw.test.js
import MockDate from 'mockdate' import dayjs from '../../src' import relativeTime from '../../src/plugin/relativeTime' import '../../src/locale/ru' import locale from '../../src/locale/ar-kw' dayjs.extend(relativeTime) beforeEach(() => { MockDate.set(new Date()) }) afterEach(() => { MockDate.reset() }) it('Meridiem', () => { dayjs.locale(locale) expect(dayjs('2020-01-01 03:00:00').locale('ar-kw').format('A')).toEqual('ص') expect(dayjs('2020-01-01 11:00:00').locale('ar-kw').format('A')).toEqual('ص') expect(dayjs('2020-01-01 16:00:00').locale('ar-kw').format('A')).toEqual('م') expect(dayjs('2020-01-01 20:00:00').locale('ar-kw').format('A')).toEqual('م') })
javascript
MIT
54f447048cee679e51a7053f8042d9b6b7028b89
2026-01-04T14:57:31.496629Z
false
iamkun/dayjs
https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/test/locale/ja.test.js
test/locale/ja.test.js
import MockDate from 'mockdate' import moment from 'moment' import dayjs from '../../src' import relativeTime from '../../src/plugin/relativeTime' import '../../src/locale/ja' dayjs.extend(relativeTime) beforeEach(() => { MockDate.set(new Date()) }) afterEach(() => { MockDate.reset() }) it('Finnish locale relative time in past and future', () => { const cases = [ [1, 'd', '1日後'], [-1, 'd', '1日前'], [2, 'd', '2日後'], [-2, 'd', '2日前'], [10, 'd', '10日後'], [-10, 'd', '10日前'], [6, 'm', '6分後'], [-6, 'm', '6分前'], [5, 'h', '5時間後'], [-5, 'h', '5時間前'], [3, 'M', '3ヶ月後'], [-3, 'M', '3ヶ月前'], [4, 'y', '4年後'], [-4, 'y', '4年前'] ] cases.forEach((c) => { expect(dayjs().add(c[0], c[1]).locale('ja').fromNow()) .toBe(c[2]) expect(dayjs().add(c[0], c[1]).locale('ja').fromNow()) .toBe(moment().add(c[0], c[1]).locale('ja').fromNow()) }) expect(dayjs().add(-10, 'd').locale('ja').fromNow(true)) .toBe('10日') expect(dayjs().add(-10, 'd').locale('ja').fromNow(true)) .toBe(moment().add(-10, 'd').locale('ja').fromNow(true)) })
javascript
MIT
54f447048cee679e51a7053f8042d9b6b7028b89
2026-01-04T14:57:31.496629Z
false
iamkun/dayjs
https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/test/locale/ar-sa.test.js
test/locale/ar-sa.test.js
import MockDate from 'mockdate' import dayjs from '../../src' import relativeTime from '../../src/plugin/relativeTime' import '../../src/locale/ru' import locale from '../../src/locale/ar-sa' dayjs.extend(relativeTime) beforeEach(() => { MockDate.set(new Date()) }) afterEach(() => { MockDate.reset() }) it('Meridiem', () => { dayjs.locale(locale) expect(dayjs('2020-01-01 03:00:00').locale('ar-sa').format('A')).toEqual('ص') expect(dayjs('2020-01-01 11:00:00').locale('ar-sa').format('A')).toEqual('ص') expect(dayjs('2020-01-01 16:00:00').locale('ar-sa').format('A')).toEqual('م') expect(dayjs('2020-01-01 20:00:00').locale('ar-sa').format('A')).toEqual('م') })
javascript
MIT
54f447048cee679e51a7053f8042d9b6b7028b89
2026-01-04T14:57:31.496629Z
false
iamkun/dayjs
https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/test/locale/ku.test.js
test/locale/ku.test.js
import moment from 'moment' import MockDate from 'mockdate' import dayjs from '../../src' import locale, { englishToArabicNumbersMap } from '../../src/locale/ku' import preParsePostFormat from '../../src/plugin/preParsePostFormat' dayjs.extend(preParsePostFormat) beforeEach(() => { MockDate.set(new Date()) }) afterEach(() => { MockDate.reset() }) it('Format meridiem correctly', () => { for (let i = 0; i <= 23; i += 1) { const dayjsKu = dayjs() .startOf('day') .add(i, 'hour') const hour = (i % 12 || 12) .toString() .replace(/\d/g, match => englishToArabicNumbersMap[match]) const m = i < 12 ? 'پ.ن' : 'د.ن' expect(dayjsKu.locale('ku').format('h A')).toBe(`${hour} ${m}`) } }) it('Preparse with locale function', () => { for (let i = 0; i <= 7; i += 1) { dayjs.locale(locale) const momentKu = moment() .locale('ku') .add(i, 'day') expect(dayjs(momentKu.format()).format()).toEqual(momentKu.format()) } })
javascript
MIT
54f447048cee679e51a7053f8042d9b6b7028b89
2026-01-04T14:57:31.496629Z
false
iamkun/dayjs
https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/test/locale/de.test.js
test/locale/de.test.js
import MockDate from 'mockdate' import moment from 'moment' import dayjs from '../../src' import relativeTime from '../../src/plugin/relativeTime' import '../../src/locale/de' import '../../src/locale/de-at' import '../../src/locale/de-ch' dayjs.extend(relativeTime) beforeEach(() => { MockDate.set(new Date()) }) afterEach(() => { MockDate.reset() }) it('German locale relative time in past and future with suffix', () => { const cases = [ [1, 's', 'in ein paar Sekunden'], [-1, 's', 'vor ein paar Sekunden'], [1, 'm', 'in einer Minute'], [-1, 'm', 'vor einer Minute'], [1, 'h', 'in einer Stunde'], [-1, 'h', 'vor einer Stunde'], [1, 'd', 'in einem Tag'], [-1, 'd', 'vor einem Tag'], [1, 'M', 'in einem Monat'], [-1, 'M', 'vor einem Monat'], [2, 'd', 'in 2 Tagen'], [-2, 'd', 'vor 2 Tagen'], [10, 'd', 'in 10 Tagen'], [-10, 'd', 'vor 10 Tagen'], [6, 'm', 'in 6 Minuten'], [-6, 'm', 'vor 6 Minuten'], [5, 'h', 'in 5 Stunden'], [-5, 'h', 'vor 5 Stunden'], [3, 'M', 'in 3 Monaten'], [-3, 'M', 'vor 3 Monaten'], [4, 'y', 'in 4 Jahren'], [-4, 'y', 'vor 4 Jahren'] ] const locales = ['de', 'de-at', 'de-ch'] locales.forEach((locale) => { cases.forEach((c) => { expect(dayjs().add(c[0], c[1]).locale(locale).fromNow()) .toBe(c[2]) expect(dayjs().add(c[0], c[1]).locale(locale).fromNow()) .toBe(moment().add(c[0], c[1]).locale(locale).fromNow()) }) }) }) it('German locale relative time in past and future without suffix', () => { const cases = [ [1, 's', 'ein paar Sekunden'], [-1, 's', 'ein paar Sekunden'], [1, 'm', 'eine Minute'], [-1, 'm', 'eine Minute'], [1, 'h', 'eine Stunde'], [-1, 'h', 'eine Stunde'], [1, 'd', 'ein Tag'], [-1, 'd', 'ein Tag'], [2, 'd', '2 Tage'], [-2, 'd', '2 Tage'], [10, 'd', '10 Tage'], [-10, 'd', '10 Tage'], [6, 'm', '6 Minuten'], [-6, 'm', '6 Minuten'], [5, 'h', '5 Stunden'], [-5, 'h', '5 Stunden'], [3, 'M', '3 Monate'], [-3, 'M', '3 Monate'], [4, 'y', '4 Jahre'], [-4, 'y', '4 Jahre'] ] const locales = ['de', 'de-at', 'de-ch'] locales.forEach((locale) => { cases.forEach((c) => { expect(dayjs().add(c[0], c[1]).locale(locale).fromNow(true)) .toBe(c[2]) expect(dayjs().add(c[0], c[1]).locale(locale).fromNow(true)) .toBe(moment().add(c[0], c[1]).locale(locale).fromNow(true)) }) }) }) it('German locales use region specific names', () => { const locales = [ { locale: 'de', expectedFormattedDate: 'Mi., 19. Januar 2022' }, { locale: 'de-at', expectedFormattedDate: 'Mi., 19. Jänner 2022' }, { locale: 'de-ch', expectedFormattedDate: 'Mi, 19. Januar 2022' } ] locales.forEach((locale) => { const dayjsWithLocale = dayjs('2022-01-19').locale(locale.locale) expect(dayjsWithLocale.format('ddd, D. MMMM YYYY')).toEqual(locale.expectedFormattedDate) }) })
javascript
MIT
54f447048cee679e51a7053f8042d9b6b7028b89
2026-01-04T14:57:31.496629Z
false
iamkun/dayjs
https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/test/locale/sk.test.js
test/locale/sk.test.js
import moment from 'moment' import MockDate from 'mockdate' import dayjs from '../../src' import relativeTime from '../../src/plugin/relativeTime' import '../../src/locale/sk' dayjs.extend(relativeTime) beforeEach(() => { MockDate.set(new Date()) }) afterEach(() => { MockDate.reset() }) it('RelativeTime: Time from X', () => { const T = [ [44.4, 'second'], // a few seconds [89.5, 'second'], // a minute [2, 'minute'], // 2 minutes [43, 'minute'], // 43 minutes [45, 'minute'], // an hour [3, 'hour'], // 3 hours [21, 'hour'], // 21 hours [1, 'day'], // a day [3, 'day'], // 3 day [25, 'day'], // 25 days [1, 'month'], // a month [2, 'month'], // 2 month [10, 'month'], // 10 month [1, 'year'], // a year [2, 'year'], // 2 year [5, 'year'], // 5 year [18, 'month'] // 2 years ] T.forEach((t) => { dayjs.locale('sk') moment.locale('sk') const dayjsDay = dayjs() const momentDay = moment() const dayjsCompare = dayjs().add(t[0], t[1]) const momentCompare = moment().add(t[0], t[1]) expect(dayjsDay.from(dayjsCompare)) .toBe(momentDay.from(momentCompare)) expect(dayjsDay.to(dayjsCompare)) .toBe(momentDay.to(momentCompare)) expect(dayjsDay.from(dayjsCompare, true)) .toBe(momentDay.from(momentCompare, true)) }) })
javascript
MIT
54f447048cee679e51a7053f8042d9b6b7028b89
2026-01-04T14:57:31.496629Z
false
iamkun/dayjs
https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/test/locale/sv-fi.test.js
test/locale/sv-fi.test.js
import dayjs from '../../src' import localizedFormat from '../../src/plugin/localizedFormat' import '../../src/locale/sv-fi' dayjs.extend(localizedFormat) it('Finland Swedish locale', () => { // time expect(dayjs('2019-02-01 12:34:56').locale('sv-fi').format('LT')) .toBe('12.34') expect(dayjs('2019-02-01 23:45:56').locale('sv-fi').format('LTS')) .toBe('23.45.56') // date expect(dayjs('2019-02-01').locale('sv-fi').format('L')) .toBe('01.02.2019') expect(dayjs('2019-12-15').locale('sv-fi').format('LL')) .toBe('15. december 2019') // short expect(dayjs('2019-02-01').locale('sv-fi').format('l')) .toBe('1.2.2019') expect(dayjs('2019-12-15').locale('sv-fi').format('ll')) .toBe('15. dec 2019') // date and time expect(dayjs('2019-03-01 12:30').locale('sv-fi').format('LLL')) .toBe('1. mars 2019, kl. 12.30') expect(dayjs('2021-06-12 17:30').locale('sv-fi').format('LLLL')) .toBe('lördag, 12. juni 2021, kl. 17.30') // short expect(dayjs('2019-03-01 12:30').locale('sv-fi').format('lll')) .toBe('1. mar 2019, kl. 12.30') expect(dayjs('2021-06-01 17:30').locale('sv-fi').format('llll')) .toBe('tis, 1. jun 2021, kl. 17.30') })
javascript
MIT
54f447048cee679e51a7053f8042d9b6b7028b89
2026-01-04T14:57:31.496629Z
false
iamkun/dayjs
https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/test/locale/ar-dz.test.js
test/locale/ar-dz.test.js
import MockDate from 'mockdate' import dayjs from '../../src' import relativeTime from '../../src/plugin/relativeTime' import '../../src/locale/ru' import locale from '../../src/locale/ar-dz' dayjs.extend(relativeTime) beforeEach(() => { MockDate.set(new Date()) }) afterEach(() => { MockDate.reset() }) it('Meridiem', () => { dayjs.locale(locale) expect(dayjs('2020-01-01 03:00:00').locale('ar-dz').format('A')).toEqual('ص') expect(dayjs('2020-01-01 11:00:00').locale('ar-dz').format('A')).toEqual('ص') expect(dayjs('2020-01-01 16:00:00').locale('ar-dz').format('A')).toEqual('م') expect(dayjs('2020-01-01 20:00:00').locale('ar-dz').format('A')).toEqual('م') })
javascript
MIT
54f447048cee679e51a7053f8042d9b6b7028b89
2026-01-04T14:57:31.496629Z
false
iamkun/dayjs
https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/test/locale/it-ch.test.js
test/locale/it-ch.test.js
import moment from 'moment' import MockDate from 'mockdate' import dayjs from '../../src' import '../../src/locale/it-ch' import relativeTime from '../../src/plugin/relativeTime' import localizedFormat from '../../src/plugin/localizedFormat' dayjs.extend(relativeTime) dayjs.extend(localizedFormat) describe('Italian formats in Switzerland', () => { beforeEach(() => { dayjs.locale('it-ch') moment.locale('it-ch') MockDate.set(new Date()) }) afterEach(() => { MockDate.reset() }) it('Format month with locale function', () => { for (let i = 0; i <= 7; i += 1) { const dayjsWithLocale = dayjs().add(i, 'day') const momentWithLocale = moment().add(i, 'day') const testFormat1 = 'DD MMMM YYYY MMM' const testFormat2 = 'dddd, MMMM D YYYY' const testFormat3 = 'MMMM' const testFormat4 = 'MMM' const testFormat5 = 'L' expect(dayjsWithLocale.format(testFormat1)).toEqual(momentWithLocale.format(testFormat1)) expect(dayjsWithLocale.format(testFormat2)).toEqual(momentWithLocale.format(testFormat2)) expect(dayjsWithLocale.format(testFormat3)).toEqual(momentWithLocale.format(testFormat3)) expect(dayjsWithLocale.format(testFormat4)).toEqual(momentWithLocale.format(testFormat4)) expect(dayjsWithLocale.format(testFormat5)).toEqual(momentWithLocale.format(testFormat5)) } }) it('RelativeTime: Time from X', () => { const T = [ [44.4, 'second'], // a few seconds [89.5, 'second'], // a minute [2, 'minute'], // 2 minutes [5, 'minute'], // 5 minutes [43, 'minute'], // 44 minutes [45, 'minute'], // an hour [3, 'hour'], // 3 hours [21, 'hour'], // 21 hours [1, 'day'], // a day [3, 'day'], // 3 day [25, 'day'], // 25 days [1, 'month'], // a month [2, 'month'], // 2 month [10, 'month'], // 10 month [1, 'year'], // a year [2, 'year'], // 2 year [5, 'year'], // 5 year [18, 'month'] // 2 years ] T.forEach((t) => { expect(dayjs().from(dayjs().add(t[0], t[1]))) .toBe(moment().from(moment().add(t[0], t[1]))) expect(dayjs().from(dayjs().add(t[0], t[1]), true)) .toBe(moment().from(moment().add(t[0], t[1]), true)) }) }) })
javascript
MIT
54f447048cee679e51a7053f8042d9b6b7028b89
2026-01-04T14:57:31.496629Z
false
iamkun/dayjs
https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/test/locale/zh-tw.test.js
test/locale/zh-tw.test.js
import dayjs from '../../src' import advancedFormat from '../../src/plugin/advancedFormat' import weekOfYear from '../../src/plugin/weekOfYear' import '../../src/locale/zh' import '../../src/locale/zh-tw' dayjs.extend(advancedFormat).extend(weekOfYear) const zh = dayjs().locale('zh') const zhTW = dayjs().locale('zh-tw') test('ordinal', () => { expect(zh.format('wo')).toEqual(`${zh.format('w')}周`) expect(zhTW.format('wo')).toEqual(`${zhTW.format('w')}週`) }) test('Meridiem', () => { for (let i = 0; i <= 24; i += 1) { expect(zh.add(i, 'hour').format('A')).toBe(zhTW.add(i, 'hour').format('A')) } })
javascript
MIT
54f447048cee679e51a7053f8042d9b6b7028b89
2026-01-04T14:57:31.496629Z
false
iamkun/dayjs
https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/test/locale/sv.test.js
test/locale/sv.test.js
import MockDate from 'mockdate' import dayjs from '../../src' import advancedFormat from '../../src/plugin/advancedFormat' import '../../src/locale/sv' dayjs.extend(advancedFormat) beforeEach(() => { MockDate.set(new Date()) }) afterEach(() => { MockDate.reset() }) it('Swedish locale Do 1a not format to 1am', () => { expect(dayjs('2019-01-01').locale('sv').format('dddd Do MMMM')) .toBe('tisdag 1a januari') expect(dayjs('2019-01-02').locale('sv').format('dddd Do MMMM')) .toBe('onsdag 2a januari') })
javascript
MIT
54f447048cee679e51a7053f8042d9b6b7028b89
2026-01-04T14:57:31.496629Z
false
iamkun/dayjs
https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/test/locale/br.test.js
test/locale/br.test.js
import moment from 'moment' import MockDate from 'mockdate' import dayjs from '../../src' import relativeTime from '../../src/plugin/relativeTime' import '../../src/locale/br' dayjs.extend(relativeTime) beforeEach(() => { MockDate.set(new Date()) }) afterEach(() => { MockDate.reset() }) it('Format Month with locale function', () => { for (let i = 0; i <= 7; i += 1) { const dayjsBR = dayjs().locale('br').add(i, 'day') const momentBR = moment().locale('br').add(i, 'day') const testFormat1 = 'DD MMMM YYYY MMM' const testFormat2 = 'MMMM' const testFormat3 = 'MMM' expect(dayjsBR.format(testFormat1)).toEqual(momentBR.format(testFormat1)) expect(dayjsBR.format(testFormat2)).toEqual(momentBR.format(testFormat2)) expect(dayjsBR.format(testFormat3)).toEqual(momentBR.format(testFormat3)) } }) it('RelativeTime: Time from X', () => { const T = [ [44.4, 'second'], // a few seconds [89.5, 'second'], // a minute [130, 'second'], // two minutes [43, 'minute'], // 44 minutes [1, 'hour'], // 1 hour [21, 'hour'], // 21 hours [2, 'day'], // 2 days [25, 'day'], // 25 days [2, 'month'], // 2 months [10, 'month'], // 10 months [18, 'month'], // 2 years [15, 'year'] // 15 years ] T.forEach((t) => { dayjs.locale('br') moment.locale('br') expect(dayjs().from(dayjs().add(t[0], t[1]))) .toBe(moment().from(moment().add(t[0], t[1]))) expect(dayjs().from(dayjs().add(t[0], t[1]), true)) .toBe(moment().from(moment().add(t[0], t[1]), true)) }) })
javascript
MIT
54f447048cee679e51a7053f8042d9b6b7028b89
2026-01-04T14:57:31.496629Z
false
iamkun/dayjs
https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/test/locale/en.test.js
test/locale/en.test.js
import dayjs from '../../src' import '../../src/locale/en' import '../../src/locale/en-gb' import '../../src/locale/en-in' import '../../src/locale/en-tt' import localizedFormat from '../../src/plugin/localizedFormat' dayjs.extend(localizedFormat) const locales = [ { locale: 'en', expectedDate: '12/25/2019' }, { locale: 'en-gb', expectedDate: '25/12/2019' }, { locale: 'en-in', expectedDate: '25/12/2019' }, { locale: 'en-tt', expectedDate: '25/12/2019' } ] describe('English date formats', () => { locales.forEach((locale) => { it(`should correctly format date with locale - ${locale.locale}`, () => { const dayjsWithLocale = dayjs('2019-12-25').locale(locale.locale) expect(dayjsWithLocale.format('L')).toEqual(locale.expectedDate) }) }) })
javascript
MIT
54f447048cee679e51a7053f8042d9b6b7028b89
2026-01-04T14:57:31.496629Z
false
iamkun/dayjs
https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/test/locale/ar.test.js
test/locale/ar.test.js
import moment from 'moment' import MockDate from 'mockdate' import dayjs from '../../src' import relativeTime from '../../src/plugin/relativeTime' import preParsePostFormat from '../../src/plugin/preParsePostFormat' import localeData from '../../src/plugin/localeData' import '../../src/locale/ar' dayjs.extend(localeData) dayjs.extend(relativeTime) dayjs.extend(preParsePostFormat) beforeEach(() => { MockDate.set(new Date()) }) afterEach(() => { MockDate.reset() }) it('Format Month with locale function', () => { for (let i = 0; i <= 7; i += 1) { const dayjsAR = dayjs().locale('ar').add(i, 'day') const momentAR = moment().locale('ar').add(i, 'day') const testFormat1 = 'DD MMMM YYYY MMM' const testFormat2 = 'MMMM' const testFormat3 = 'MMM' expect(dayjsAR.format(testFormat1)).toEqual(momentAR.format(testFormat1)) expect(dayjsAR.format(testFormat2)).toEqual(momentAR.format(testFormat2)) expect(dayjsAR.format(testFormat3)).toEqual(momentAR.format(testFormat3)) } }) it('Preparse with locale function', () => { for (let i = 0; i <= 7; i += 1) { dayjs.locale('ar') const momentAR = moment().locale('ar').add(i, 'day') expect(dayjs(momentAR.format()).format()).toEqual(momentAR.format()) } }) it('RelativeTime: Time from X gets formatted', () => { const T = [ [44.4, 'second', 'منذ ثانية واحدة'] ] T.forEach((t) => { dayjs.locale('ar') expect(dayjs().from(dayjs().add(t[0], t[1]))) .toBe(t[2]) }) }) it('Format meridiem with locale function', () => { for (let i = 0; i <= 23; i += 1) { const hour = dayjs() .startOf('day') .add(i, 'hour') const meridiem = i > 12 ? 'م' : 'ص' expect(hour.locale('ar').format('A')).toBe(`${meridiem}`) } })
javascript
MIT
54f447048cee679e51a7053f8042d9b6b7028b89
2026-01-04T14:57:31.496629Z
false
iamkun/dayjs
https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/test/locale/ar-ma.test.js
test/locale/ar-ma.test.js
import MockDate from 'mockdate' import dayjs from '../../src' import relativeTime from '../../src/plugin/relativeTime' import '../../src/locale/ru' import locale from '../../src/locale/ar-ma' dayjs.extend(relativeTime) beforeEach(() => { MockDate.set(new Date()) }) afterEach(() => { MockDate.reset() }) it('Meridiem', () => { dayjs.locale(locale) expect(dayjs('2020-01-01 03:00:00').locale('ar-ma').format('A')).toEqual('ص') expect(dayjs('2020-01-01 11:00:00').locale('ar-ma').format('A')).toEqual('ص') expect(dayjs('2020-01-01 16:00:00').locale('ar-ma').format('A')).toEqual('م') expect(dayjs('2020-01-01 20:00:00').locale('ar-ma').format('A')).toEqual('م') })
javascript
MIT
54f447048cee679e51a7053f8042d9b6b7028b89
2026-01-04T14:57:31.496629Z
false
iamkun/dayjs
https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/test/locale/zh-cn.test.js
test/locale/zh-cn.test.js
// import moment from 'moment' import MockDate from 'mockdate' import dayjs from '../../src' import '../../src/locale/zh-cn' beforeEach(() => { MockDate.set(new Date()) }) afterEach(() => { MockDate.reset() }) it('Meridiem', () => { // the '中午' is different to moment.js 11-13 expect(dayjs('2020-01-01 10:59:59').locale('zh-cn').format('A')).toEqual('上午') expect(dayjs('2020-01-01 11:00:00').locale('zh-cn').format('A')).toEqual('中午') expect(dayjs('2020-01-01 12:59:59').locale('zh-cn').format('A')).toEqual('中午') expect(dayjs('2020-01-01 13:00:00').locale('zh-cn').format('A')).toEqual('下午') })
javascript
MIT
54f447048cee679e51a7053f8042d9b6b7028b89
2026-01-04T14:57:31.496629Z
false
iamkun/dayjs
https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/test/locale/ar-iq.test.js
test/locale/ar-iq.test.js
import MockDate from 'mockdate' import dayjs from '../../src' import relativeTime from '../../src/plugin/relativeTime' import '../../src/locale/ru' import locale from '../../src/locale/ar-iq' dayjs.extend(relativeTime) beforeEach(() => { MockDate.set(new Date()) }) afterEach(() => { MockDate.reset() }) it('Meridiem', () => { dayjs.locale(locale) expect(dayjs('2020-01-01 03:00:00').locale('ar-iq').format('A')).toEqual('ص') expect(dayjs('2020-01-01 11:00:00').locale('ar-iq').format('A')).toEqual('ص') expect(dayjs('2020-01-01 16:00:00').locale('ar-iq').format('A')).toEqual('م') expect(dayjs('2020-01-01 20:00:00').locale('ar-iq').format('A')).toEqual('م') })
javascript
MIT
54f447048cee679e51a7053f8042d9b6b7028b89
2026-01-04T14:57:31.496629Z
false
iamkun/dayjs
https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/test/locale/sr-cyrl.test.js
test/locale/sr-cyrl.test.js
import MockDate from 'mockdate' import dayjs from '../../src' import relativeTime from '../../src/plugin/relativeTime' import '../../src/locale/sr-cyrl' dayjs.extend(relativeTime) beforeEach(() => { MockDate.set(new Date()) }) afterEach(() => { MockDate.reset() }) it('Serbian cyrillic locale relative time in past and future', () => { const cases = [ [1, 's', 'за неколико секунди', 'неколико секунди'], [-1, 's', 'пре неколико секунди', 'неколико секунди'], [4, 's', 'за неколико секунди', 'неколико секунди'], [1, 'm', 'за један минут', 'један минут'], [-1, 'm', 'пре једног минута', 'један минут'], [4, 'm', 'за 4 минута', '4 минута'], [5, 'm', 'за 5 минута', '5 минута'], [21, 'm', 'за 21 минут', '21 минут'], [1, 'h', 'за један сат', 'један сат'], [-1, 'h', 'пре једног сата', 'један сат'], [4, 'h', 'за 4 сата', '4 сата'], [5, 'h', 'за 5 сати', '5 сати'], [21, 'h', 'за 21 сат', '21 сат'], [1, 'd', 'за један дан', 'један дан'], [-1, 'd', 'пре једног дана', 'један дан'], [4, 'd', 'за 4 дана', '4 дана'], [5, 'd', 'за 5 дана', '5 дана'], [21, 'd', 'за 21 дан', '21 дан'], [1, 'M', 'за један месец', 'један месец'], [-1, 'M', 'пре једног месеца', 'један месец'], [4, 'M', 'за 4 месеца', '4 месеца'], [5, 'M', 'за 5 месеци', '5 месеци'], [10, 'M', 'за 10 месеци', '10 месеци'], [1, 'y', 'за једну годину', 'једна година'], [-1, 'y', 'пре једне године', 'једна година'], [4, 'y', 'за 4 године', '4 године'], [5, 'y', 'за 5 година', '5 година'], [21, 'y', 'за 21 годину', '21 година'] ] cases.forEach((c) => { expect(dayjs().add(c[0], c[1]).locale('sr-cyrl').fromNow()).toBe(c[2]) expect(dayjs().add(c[0], c[1]).locale('sr-cyrl').fromNow(true)).toBe(c[3]) // TODO: compare to momentjs once logic and grammar are fixed there }) })
javascript
MIT
54f447048cee679e51a7053f8042d9b6b7028b89
2026-01-04T14:57:31.496629Z
false
iamkun/dayjs
https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/test/locale/it.test.js
test/locale/it.test.js
import moment from 'moment' import MockDate from 'mockdate' import dayjs from '../../src' import '../../src/locale/it' import relativeTime from '../../src/plugin/relativeTime' import localizedFormat from '../../src/plugin/localizedFormat' dayjs.extend(relativeTime) dayjs.extend(localizedFormat) describe('Italian formats', () => { beforeEach(() => { dayjs.locale('it') moment.locale('it') MockDate.set(new Date()) }) afterEach(() => { MockDate.reset() }) it('Format month with locale function', () => { for (let i = 0; i <= 7; i += 1) { const dayjsWithLocale = dayjs().add(i, 'day') const momentWithLocale = moment().add(i, 'day') const testFormat1 = 'DD MMMM YYYY MMM' const testFormat2 = 'dddd, MMMM D YYYY' const testFormat3 = 'MMMM' const testFormat4 = 'MMM' const testFormat5 = 'L' expect(dayjsWithLocale.format(testFormat1)).toEqual(momentWithLocale.format(testFormat1)) expect(dayjsWithLocale.format(testFormat2)).toEqual(momentWithLocale.format(testFormat2)) expect(dayjsWithLocale.format(testFormat3)).toEqual(momentWithLocale.format(testFormat3)) expect(dayjsWithLocale.format(testFormat4)).toEqual(momentWithLocale.format(testFormat4)) expect(dayjsWithLocale.format(testFormat5)).toEqual(momentWithLocale.format(testFormat5)) } }) it('RelativeTime: Time from X', () => { const T = [ [89.5, 'second'], // a minute [2, 'minute'], // 2 minutes [5, 'minute'], // 5 minutes [43, 'minute'], // 44 minutes [45, 'minute'], // an hour [3, 'hour'], // 3 hours [21, 'hour'], // 21 hours [1, 'day'], // a day [3, 'day'], // 3 day [25, 'day'], // 25 days [1, 'month'], // a month [2, 'month'], // 2 month [10, 'month'], // 10 month [1, 'year'], // a year [2, 'year'], // 2 year [5, 'year'], // 5 year [18, 'month'] // 2 years ] T.forEach((t) => { expect(dayjs().from(dayjs().add(t[0], t[1]))) .toBe(moment().from(moment().add(t[0], t[1]))) expect(dayjs().from(dayjs().add(t[0], t[1]), true)) .toBe(moment().from(moment().add(t[0], t[1]), true)) }) }) // moment.js uses `alcuni secondi` while dayjs uses `qualche secondo`. it('RelativeTime: A few seconds', () => { const T = [ [44.4, 'second'] // a few seconds ] T.forEach((t) => { expect(dayjs().from(dayjs().add(t[0], t[1]))) .toBe('qualche secondo fa') expect(dayjs().from(dayjs().add(t[0], t[1]), true)) .toBe('qualche secondo') }) }) })
javascript
MIT
54f447048cee679e51a7053f8042d9b6b7028b89
2026-01-04T14:57:31.496629Z
false
iamkun/dayjs
https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/test/locale/sr.test.js
test/locale/sr.test.js
import MockDate from 'mockdate' import dayjs from '../../src' import relativeTime from '../../src/plugin/relativeTime' import '../../src/locale/sr' dayjs.extend(relativeTime) beforeEach(() => { MockDate.set(new Date()) }) afterEach(() => { MockDate.reset() }) it('Serbian locale relative time in past and future', () => { const cases = [ [1, 's', 'za nekoliko sekundi', 'nekoliko sekundi'], [-1, 's', 'pre nekoliko sekundi', 'nekoliko sekundi'], [4, 's', 'za nekoliko sekundi', 'nekoliko sekundi'], [1, 'm', 'za jedan minut', 'jedan minut'], [-1, 'm', 'pre jednog minuta', 'jedan minut'], [4, 'm', 'za 4 minuta', '4 minuta'], [5, 'm', 'za 5 minuta', '5 minuta'], [21, 'm', 'za 21 minut', '21 minut'], [1, 'h', 'za jedan sat', 'jedan sat'], [-1, 'h', 'pre jednog sata', 'jedan sat'], [4, 'h', 'za 4 sata', '4 sata'], [5, 'h', 'za 5 sati', '5 sati'], [21, 'h', 'za 21 sat', '21 sat'], [1, 'd', 'za jedan dan', 'jedan dan'], [-1, 'd', 'pre jednog dana', 'jedan dan'], [4, 'd', 'za 4 dana', '4 dana'], [5, 'd', 'za 5 dana', '5 dana'], [21, 'd', 'za 21 dan', '21 dan'], [1, 'M', 'za jedan mesec', 'jedan mesec'], [-1, 'M', 'pre jednog meseca', 'jedan mesec'], [4, 'M', 'za 4 meseca', '4 meseca'], [5, 'M', 'za 5 meseci', '5 meseci'], [10, 'M', 'za 10 meseci', '10 meseci'], [1, 'y', 'za jednu godinu', 'jedna godina'], [-1, 'y', 'pre jedne godine', 'jedna godina'], [4, 'y', 'za 4 godine', '4 godine'], [5, 'y', 'za 5 godina', '5 godina'], [21, 'y', 'za 21 godinu', '21 godina'] ] cases.forEach((c) => { // With suffix expect(dayjs().add(c[0], c[1]).locale('sr').fromNow()).toBe(c[2]) // Without suffix expect(dayjs().add(c[0], c[1]).locale('sr').fromNow(true)).toBe(c[3]) // TODO: compare to momentjs once logic and grammar are fixed there }) })
javascript
MIT
54f447048cee679e51a7053f8042d9b6b7028b89
2026-01-04T14:57:31.496629Z
false
iamkun/dayjs
https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/test/locale/ru.test.js
test/locale/ru.test.js
import moment from 'moment' import MockDate from 'mockdate' import dayjs from '../../src' import relativeTime from '../../src/plugin/relativeTime' import '../../src/locale/ru' dayjs.extend(relativeTime) beforeEach(() => { MockDate.set(new Date()) }) afterEach(() => { MockDate.reset() }) it('Format Month with locale function', () => { for (let i = 0; i <= 7; i += 1) { const dayjsRU = dayjs().locale('ru').add(i, 'day') const momentRU = moment().locale('ru').add(i, 'day') const testFormat1 = 'DD MMMM YYYY MMM' const testFormat2 = 'MMMM' const testFormat3 = 'MMM' expect(dayjsRU.format(testFormat1)).toEqual(momentRU.format(testFormat1)) expect(dayjsRU.format(testFormat2)).toEqual(momentRU.format(testFormat2)) expect(dayjsRU.format(testFormat3)).toEqual(momentRU.format(testFormat3)) } }) it('RelativeTime: Time from X', () => { const T = [ [44.4, 'second'], // a few seconds [89.5, 'second'], // a minute [43, 'minute'], // 44 minutes [21, 'hour'], // 21 hours [25, 'day'], // 25 days [10, 'month'], // 2 month [18, 'month'] // 2 years ] T.forEach((t) => { dayjs.locale('ru') moment.locale('ru') expect(dayjs().from(dayjs().add(t[0], t[1]))) .toBe(moment().from(moment().add(t[0], t[1]))) expect(dayjs().from(dayjs().add(t[0], t[1]), true)) .toBe(moment().from(moment().add(t[0], t[1]), true)) }) }) it('Meridiem', () => { expect(dayjs('2020-01-01 03:00:00').locale('ru').format('A')).toEqual('ночи') expect(dayjs('2020-01-01 11:00:00').locale('ru').format('A')).toEqual('утра') expect(dayjs('2020-01-01 16:00:00').locale('ru').format('A')).toEqual('дня') expect(dayjs('2020-01-01 20:00:00').locale('ru').format('A')).toEqual('вечера') })
javascript
MIT
54f447048cee679e51a7053f8042d9b6b7028b89
2026-01-04T14:57:31.496629Z
false
iamkun/dayjs
https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/test/locale/bg.test.js
test/locale/bg.test.js
import moment from 'moment' import MockDate from 'mockdate' import dayjs from '../../src' import relativeTime from '../../src/plugin/relativeTime' import advancedFormat from '../../src/plugin/advancedFormat' import '../../src/locale/bg' dayjs.extend(relativeTime) dayjs.extend(advancedFormat) beforeEach(() => { MockDate.set(new Date()) }) afterEach(() => { MockDate.reset() }) it('Format Month with locale function', () => { for (let i = 0; i <= 7; i += 1) { const dayjsBG = dayjs().locale('bg').add(i, 'day') const momentBG = moment().locale('bg').add(i, 'day') const testFormat1 = 'DD MMMM YYYY MMM' const testFormat2 = 'MMMM' const testFormat3 = 'MMM' expect(dayjsBG.format(testFormat1)).toEqual(momentBG.format(testFormat1)) expect(dayjsBG.format(testFormat2)).toEqual(momentBG.format(testFormat2)) expect(dayjsBG.format(testFormat3)).toEqual(momentBG.format(testFormat3)) } }) it('RelativeTime: Time from X', () => { const T = [ [44.4, 'second'], // a few seconds [89.5, 'second'], // a minute [130, 'second'], // two minutes [43, 'minute'], // 44 minutes [1, 'hour'], // 1 hour [21, 'hour'], // 21 hours [2, 'day'], // 2 days [25, 'day'], // 25 days [2, 'month'], // 2 months [10, 'month'], // 10 months [18, 'month'], // 2 years [15, 'year'] // 15 years ] T.forEach((t) => { dayjs.locale('bg') moment.locale('bg') expect(dayjs().from(dayjs().add(t[0], t[1]))) .toBe(moment().from(moment().add(t[0], t[1]))) expect(dayjs().from(dayjs().add(t[0], t[1]), true)) .toBe(moment().from(moment().add(t[0], t[1]), true)) }) }) it('Ordinal', () => { dayjs.locale('bg') moment.locale('bg') for (let d = 1; d <= 31; d += 1) { const day = d < 10 ? `0${d}` : d const date = `2021-01-${day}` expect(dayjs(date).format('Do')).toBe(moment(date).format('Do')) } })
javascript
MIT
54f447048cee679e51a7053f8042d9b6b7028b89
2026-01-04T14:57:31.496629Z
false
iamkun/dayjs
https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/test/locale/lt.test.js
test/locale/lt.test.js
import moment from 'moment' import dayjs from '../../src' import '../../src/locale/lt' it('Format month with locale function', () => { for (let i = 0; i <= 7; i += 1) { const dayjsUK = dayjs().locale('lt').add(i, 'day') const momentUK = moment().locale('lt').add(i, 'day') const testFormat1 = 'DD MMMM YYYY MMM' const testFormat2 = 'dddd, MMMM D YYYY' const testFormat3 = 'MMMM' const testFormat4 = 'MMM' expect(dayjsUK.format(testFormat1)).toEqual(momentUK.format(testFormat1)) expect(dayjsUK.format(testFormat2)).toEqual(momentUK.format(testFormat2)) expect(dayjsUK.format(testFormat3)).toEqual(momentUK.format(testFormat3)) expect(dayjsUK.format(testFormat4)).toEqual(momentUK.format(testFormat4)) } })
javascript
MIT
54f447048cee679e51a7053f8042d9b6b7028b89
2026-01-04T14:57:31.496629Z
false
iamkun/dayjs
https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/test/locale/fi.test.js
test/locale/fi.test.js
import MockDate from 'mockdate' import moment from 'moment' import dayjs from '../../src' import relativeTime from '../../src/plugin/relativeTime' import '../../src/locale/fi' dayjs.extend(relativeTime) beforeEach(() => { MockDate.set(new Date()) }) afterEach(() => { MockDate.reset() }) it('Finnish locale relative time in past and future', () => { const cases = [ [1, 'd', 'päivän päästä'], [-1, 'd', 'päivä sitten'], [2, 'd', 'kahden päivän päästä'], [-2, 'd', 'kaksi päivää sitten'], [10, 'd', '10 päivän päästä'], [-10, 'd', '10 päivää sitten'], [6, 'm', 'kuuden minuutin päästä'], [-6, 'm', 'kuusi minuuttia sitten'], [5, 'h', 'viiden tunnin päästä'], [-5, 'h', 'viisi tuntia sitten'], [3, 'M', 'kolmen kuukauden päästä'], [-3, 'M', 'kolme kuukautta sitten'], [4, 'y', 'neljän vuoden päästä'], [-4, 'y', 'neljä vuotta sitten'] ] cases.forEach((c) => { expect(dayjs().add(c[0], c[1]).locale('fi').fromNow()) .toBe(c[2]) expect(dayjs().add(c[0], c[1]).locale('fi').fromNow()) .toBe(moment().add(c[0], c[1]).locale('fi').fromNow()) }) expect(dayjs().add(-10, 'd').locale('fi').fromNow(true)) .toBe('10 päivää') expect(dayjs().add(-10, 'd').locale('fi').fromNow(true)) .toBe(moment().add(-10, 'd').locale('fi').fromNow(true)) })
javascript
MIT
54f447048cee679e51a7053f8042d9b6b7028b89
2026-01-04T14:57:31.496629Z
false
iamkun/dayjs
https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/test/locale/bn-bd.test.js
test/locale/bn-bd.test.js
import moment from 'moment' import MockDate from 'mockdate' import dayjs from '../../src' import relativeTime from '../../src/plugin/relativeTime' import localeData from '../../src/plugin/localeData' import preParsePostFormat from '../../src/plugin/preParsePostFormat' import '../../src/locale/bn-bd' dayjs.extend(localeData) dayjs.extend(relativeTime) dayjs.extend(preParsePostFormat) beforeEach(() => { MockDate.set(new Date()) }) afterEach(() => { MockDate.reset() }) it('Format Month with locale function', () => { for (let i = 0; i <= 7; i += 1) { const dayjsBN = dayjs() .locale('bn-bd') .add(i, 'day') const momentBN = moment() .locale('bn-bd') .add(i, 'day') const testFormat1 = 'DD MMMM YYYY MMM' const testFormat2 = 'MMMM' const testFormat3 = 'MMM' expect(dayjsBN.format(testFormat1)).toEqual(momentBN.format(testFormat1)) expect(dayjsBN.format(testFormat2)).toEqual(momentBN.format(testFormat2)) expect(dayjsBN.format(testFormat3)).toEqual(momentBN.format(testFormat3)) } }) it('Month short', () => { const date = '2021-02-01T05:54:32.005Z' const dayjsBN = dayjs(date) .locale('bn-bd') const momentBN = moment(date) .locale('bn-bd') const testFormat1 = 'DD MMMM YYYY MMM' expect(dayjsBN.format(testFormat1)).toEqual(momentBN.format(testFormat1)) }) it('Preparse with locale function', () => { for (let i = 0; i <= 7; i += 1) { dayjs.locale('bn-bd') const momentBN = moment() .locale('bn-bd') .add(i, 'day') expect(dayjs(momentBN.format()).format()).toEqual(momentBN.format()) } }) it('RelativeTime: Time from X', () => { const T = [ [44.4, 'second'], // a few seconds [89.5, 'second'], // a minute [130, 'second'], // two minutes [43, 'minute'], // 44 minutes [1, 'hour'], // 1 hour [21, 'hour'], // 21 hours [2, 'day'], // 2 days [25, 'day'], // 25 days [2, 'month'], // 2 months [10, 'month'], // 10 months [18, 'month'], // 2 years [15, 'year'] // 15 years ] T.forEach((t) => { dayjs.locale('bn-bd') moment.locale('bn-bd') expect(dayjs().from(dayjs().add(t[0], t[1]))).toBe(moment().from(moment().add(t[0], t[1]))) expect(dayjs().from(dayjs().add(t[0], t[1]), true)) .toBe(moment().from(moment().add(t[0], t[1]), true)) }) })
javascript
MIT
54f447048cee679e51a7053f8042d9b6b7028b89
2026-01-04T14:57:31.496629Z
false
iamkun/dayjs
https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/test/locale/sl.test.js
test/locale/sl.test.js
import MockDate from 'mockdate' import dayjs from '../../src' import relativeTime from '../../src/plugin/relativeTime' import '../../src/locale/sl' dayjs.extend(relativeTime) beforeEach(() => { MockDate.set(new Date()) }) afterEach(() => { MockDate.reset() }) it('Slovenian locale relative time in past and future', () => { const cases = [ [1, 's', 'čez nekaj sekund', 'nekaj sekund'], [-1, 's', 'pred nekaj sekundami', 'nekaj sekund'], [1, 'm', 'čez eno minuto', 'ena minuta'], [-1, 'm', 'pred eno minuto', 'ena minuta'], [2, 'm', 'čez 2 minuti', '2 minuti'], [-2, 'm', 'pred 2 minutama', '2 minuti'], [3, 'm', 'čez 3 minute', '3 minute'], [-3, 'm', 'pred 3 minutami', '3 minute'], [5, 'm', 'čez 5 minut', '5 minut'], [-5, 'm', 'pred 5 minutami', '5 minut'], [1, 'h', 'čez eno uro', 'ena ura'], [-1, 'h', 'pred eno uro', 'ena ura'], [2, 'h', 'čez 2 uri', '2 uri'], [-2, 'h', 'pred 2 urama', '2 uri'], [3, 'h', 'čez 3 ure', '3 ure'], [-3, 'h', 'pred 3 urami', '3 ure'], [5, 'h', 'čez 5 ur', '5 ur'], [-5, 'h', 'pred 5 urami', '5 ur'], [1, 'd', 'čez en dan', 'en dan'], [-1, 'd', 'pred enim dnem', 'en dan'], [2, 'd', 'čez 2 dneva', '2 dneva'], [-2, 'd', 'pred 2 dnevoma', '2 dneva'], [3, 'd', 'čez 3 dni', '3 dni'], [-3, 'd', 'pred 3 dnevi', '3 dni'], [5, 'd', 'čez 5 dni', '5 dni'], [-5, 'd', 'pred 5 dnevi', '5 dni'], [1, 'M', 'čez en mesec', 'en mesec'], [-1, 'M', 'pred enim mesecem', 'en mesec'], [2, 'M', 'čez 2 meseca', '2 meseca'], [-2, 'M', 'pred 2 mesecema', '2 meseca'], [3, 'M', 'čez 3 mesece', '3 mesece'], [-3, 'M', 'pred 3 meseci', '3 mesece'], [5, 'M', 'čez 5 mesecev', '5 mesecev'], [-5, 'M', 'pred 5 meseci', '5 mesecev'], [1, 'y', 'čez eno leto', 'eno leto'], [-1, 'y', 'pred enim letom', 'eno leto'], [2, 'y', 'čez 2 leti', '2 leti'], [-2, 'y', 'pred 2 letoma', '2 leti'], [3, 'y', 'čez 3 leta', '3 leta'], [-3, 'y', 'pred 3 leti', '3 leta'], [5, 'y', 'čez 5 let', '5 let'], [-5, 'y', 'pred 5 leti', '5 let'] // these are rounded // if user decides to change rounding then it would be good to test them also // [102, 's', 'čez 102 sekundi', '102 sekundi'], // [-102, 's', 'pred 102 sekundama', '102 sekundi'], // [103, 's', 'čez 103 sekunde', '103 sekunde'], // [-103, 's', 'pred 103 sekundami', '103 sekunde'], // [114, 's', 'čez 114 sekund', '114 sekund'], // [-114, 's', 'pred 114 sekundami', '114 sekund'], // [-102, 'm', 'čez 102 minuti', '102 minuti'], // [-102, 'm', 'pred 102 minutama', '102 minuti'], // [103, 'm', 'čez 103 minute', '103 minute'], // [-103, 'm', 'pred 103 minutami', '103 minute'], // [114, 'm', 'čez 114 minut', '114 minut'], // [-114, 'm', 'pred 114 minutami', '114 minut'] ] cases.forEach((c) => { // With suffix expect(dayjs().add(c[0], c[1]).locale('sl').fromNow()).toBe(c[2]) // Without suffix expect(dayjs().add(c[0], c[1]).locale('sl').fromNow(true)).toBe(c[3]) }) })
javascript
MIT
54f447048cee679e51a7053f8042d9b6b7028b89
2026-01-04T14:57:31.496629Z
false
iamkun/dayjs
https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/test/locale/ar-ly.test.js
test/locale/ar-ly.test.js
import MockDate from 'mockdate' import dayjs from '../../src' import relativeTime from '../../src/plugin/relativeTime' import '../../src/locale/ru' import locale from '../../src/locale/ar-ly' dayjs.extend(relativeTime) beforeEach(() => { MockDate.set(new Date()) }) afterEach(() => { MockDate.reset() }) it('Meridiem', () => { dayjs.locale(locale) expect(dayjs('2020-01-01 03:00:00').locale('ar-ly').format('A')).toEqual('ص') expect(dayjs('2020-01-01 11:00:00').locale('ar-ly').format('A')).toEqual('ص') expect(dayjs('2020-01-01 16:00:00').locale('ar-ly').format('A')).toEqual('م') expect(dayjs('2020-01-01 20:00:00').locale('ar-ly').format('A')).toEqual('م') })
javascript
MIT
54f447048cee679e51a7053f8042d9b6b7028b89
2026-01-04T14:57:31.496629Z
false
iamkun/dayjs
https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/test/locale/is.test.js
test/locale/is.test.js
import MockDate from 'mockdate' import moment from 'moment' import dayjs from '../../src' import '../../src/locale/is' import relativeTime from '../../src/plugin/relativeTime' dayjs.extend(relativeTime) beforeEach(() => { MockDate.set(new Date()) }) afterEach(() => { MockDate.reset() }) const expectations = [ [1, 's', 'nokkrar sekúndur', 'fyrir nokkrum sekúndum síðan', 'eftir nokkrar sekúndur'], [1, 'm', 'mínúta', 'fyrir mínútu síðan', 'eftir mínútu'], [1, 'h', 'klukkustund', 'fyrir klukkustund síðan', 'eftir klukkustund'], [1, 'd', 'dagur', 'fyrir degi síðan', 'eftir dag'], [1, 'M', 'mánuður', 'fyrir mánuði síðan', 'eftir mánuð'], [1, 'y', 'ár', 'fyrir ári síðan', 'eftir ár'], [2, 'm', '2 mínútur', 'fyrir 2 mínútum síðan', 'eftir 2 mínútur'], [2, 'h', '2 klukkustundir', 'fyrir 2 klukkustundum síðan', 'eftir 2 klukkustundir'], [2, 'd', '2 dagar', 'fyrir 2 dögum síðan', 'eftir 2 daga'], [2, 'M', '2 mánuðir', 'fyrir 2 mánuðum síðan', 'eftir 2 mánuði'], [2, 'y', '2 ár', 'fyrir 2 árum síðan', 'eftir 2 ár'], [21, 'm', '21 mínúta', 'fyrir 21 mínútu síðan', 'eftir 21 mínútu'], [21, 'h', '21 klukkustund', 'fyrir 21 klukkustund síðan', 'eftir 21 klukkustund'], [21, 'd', '21 dagur', 'fyrir 21 degi síðan', 'eftir 21 dag'], [21, 'y', '21 ár', 'fyrir 21 ári síðan', 'eftir 21 ár'] ] describe('moment compatibility', () => { it('without suffix', () => { expectations.forEach((expectation) => { const [offset, unit, expectationWithoutSuffix] = expectation const momentResult = moment() .add(offset, unit) .locale('is') .fromNow(true) expect(expectationWithoutSuffix).toBe(momentResult) }) }) it('past', () => { expectations.forEach((expectation) => { const [offset, unit, , pastExpectation] = expectation const momentResult = moment() .add(-offset, unit) .locale('is') .fromNow() expect(pastExpectation).toBe(momentResult) }) }) it('future', () => { expectations.forEach((expectation) => { const [offset, unit, , , futureExpectation] = expectation const momentResult = moment() .add(offset, unit) .locale('is') .fromNow() expect(futureExpectation).toBe(momentResult) }) }) }) describe('Icelandic output matches moment output', () => { it('without suffix', () => { expectations.forEach((expectation) => { const [offset, unit, expectationWithoutSuffix] = expectation const result = dayjs() .add(offset, unit) .locale('is') .fromNow(true) expect(result).toBe(expectationWithoutSuffix) }) }) it('past', () => { expectations.forEach((expectation) => { const [offset, unit, , pastExpectation] = expectation const result = dayjs() .add(-offset, unit) .locale('is') .fromNow() expect(result).toBe(pastExpectation) }) }) it('future', () => { expectations.forEach((expectation) => { const [offset, unit, , , futureExpectation] = expectation const result = dayjs() .add(offset, unit) .locale('is') .fromNow() expect(result).toBe(futureExpectation) }) }) })
javascript
MIT
54f447048cee679e51a7053f8042d9b6b7028b89
2026-01-04T14:57:31.496629Z
false
iamkun/dayjs
https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/test/locale/ar-tn.test.js
test/locale/ar-tn.test.js
import MockDate from 'mockdate' import dayjs from '../../src' import relativeTime from '../../src/plugin/relativeTime' import '../../src/locale/ru' import locale from '../../src/locale/ar-tn' dayjs.extend(relativeTime) beforeEach(() => { MockDate.set(new Date()) }) afterEach(() => { MockDate.reset() }) it('Meridiem', () => { dayjs.locale(locale) expect(dayjs('2020-01-01 03:00:00').locale('ar-tn').format('A')).toEqual('ص') expect(dayjs('2020-01-01 11:00:00').locale('ar-tn').format('A')).toEqual('ص') expect(dayjs('2020-01-01 16:00:00').locale('ar-tn').format('A')).toEqual('م') expect(dayjs('2020-01-01 20:00:00').locale('ar-tn').format('A')).toEqual('م') })
javascript
MIT
54f447048cee679e51a7053f8042d9b6b7028b89
2026-01-04T14:57:31.496629Z
false
iamkun/dayjs
https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/test/locale/uk.test.js
test/locale/uk.test.js
import moment from 'moment' import MockDate from 'mockdate' import dayjs from '../../src' import relativeTime from '../../src/plugin/relativeTime' import '../../src/locale/uk' dayjs.extend(relativeTime) beforeEach(() => { MockDate.set(new Date()) }) afterEach(() => { MockDate.reset() }) it('Format Month with locale function', () => { for (let i = 0; i <= 7; i += 1) { const dayjsUK = dayjs().locale('uk').add(i, 'day') const momentUK = moment().locale('uk').add(i, 'day') const testFormat1 = 'DD MMMM YYYY MMM' const testFormat2 = 'MMMM' const testFormat3 = 'MMM' expect(dayjsUK.format(testFormat1)).toEqual(momentUK.format(testFormat1)) expect(dayjsUK.format(testFormat2)).toEqual(momentUK.format(testFormat2)) expect(dayjsUK.format(testFormat3)).toEqual(momentUK.format(testFormat3)) } }) it('RelativeTime: Time from X', () => { const T = [ [44.4, 'second'], // a few seconds [89.5, 'second'], // a minute [43, 'minute'], // 44 minutes [21, 'hour'], // 21 hours [25, 'day'], // 25 days [10, 'month'], // 2 month [18, 'month'] // 2 years ] T.forEach((t) => { dayjs.locale('uk') moment.locale('uk') expect(dayjs().from(dayjs().add(t[0], t[1]))) .toBe(moment().from(moment().add(t[0], t[1]))) expect(dayjs().from(dayjs().add(t[0], t[1]), true)) .toBe(moment().from(moment().add(t[0], t[1]), true)) }) }) it('hour', () => { const str0 = '2020-03-18 19:15:00' const str = '2020-03-18 20:15:00' const result = dayjs(str0).locale('uk').to(str) expect(result).toEqual(moment(str0).locale('uk').to(str)) const result2 = dayjs(str).locale('uk').to(str0, true) expect(result2).toEqual('година') // different from moment.js })
javascript
MIT
54f447048cee679e51a7053f8042d9b6b7028b89
2026-01-04T14:57:31.496629Z
false
iamkun/dayjs
https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/test/locale/zh-hk.test.js
test/locale/zh-hk.test.js
import dayjs from '../../src' import advancedFormat from '../../src/plugin/advancedFormat' import weekOfYear from '../../src/plugin/weekOfYear' import '../../src/locale/zh' import '../../src/locale/zh-cn' import '../../src/locale/zh-hk' import '../../src/locale/zh-tw' dayjs.extend(advancedFormat).extend(weekOfYear) const zh = dayjs().locale('zh') const zhCN = dayjs().locale('zh-cn') const zhHK = dayjs().locale('zh-hk') const zhTW = dayjs().locale('zh-tw') test('ordinal', () => { expect(zh.format('wo')).toEqual(`${zh.format('w')}周`) expect(zhCN.format('wo')).toEqual(`${zhCN.format('w')}周`) expect(zhHK.format('wo')).toEqual(`${zhHK.format('w')}週`) expect(zhTW.format('wo')).toEqual(`${zhTW.format('w')}週`) }) test('Meridiem', () => { for (let i = 0; i <= 24; i += 1) { expect(zh.add(i, 'hour').format('A')).toBe(zhCN.add(i, 'hour').format('A')) } }) test('Meridiem', () => { expect(dayjs('2020-01-01 05:59:59').locale('zh-hk').format('A')).toEqual('凌晨') expect(dayjs('2020-01-01 08:59:59').locale('zh-hk').format('A')).toEqual('早上') expect(dayjs('2020-01-01 10:59:59').locale('zh-hk').format('A')).toEqual('上午') expect(dayjs('2020-01-01 11:00:00').locale('zh-hk').format('A')).toEqual('中午') expect(dayjs('2020-01-01 12:59:59').locale('zh-hk').format('A')).toEqual('中午') expect(dayjs('2020-01-01 13:00:00').locale('zh-hk').format('A')).toEqual('下午') })
javascript
MIT
54f447048cee679e51a7053f8042d9b6b7028b89
2026-01-04T14:57:31.496629Z
false
iamkun/dayjs
https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/test/locale/hr.test.js
test/locale/hr.test.js
import moment from 'moment' import dayjs from '../../src' import '../../src/locale/hr' it('Format month with locale function', () => { for (let i = 0; i <= 7; i += 1) { const dayjsUK = dayjs().locale('hr').add(i, 'day') const momentUK = moment().locale('hr').add(i, 'day') const testFormat1 = 'DD MMMM YYYY MMM' const testFormat2 = 'dddd, MMMM D YYYY' const testFormat3 = 'MMMM' const testFormat4 = 'MMM' expect(dayjsUK.format(testFormat1)).toEqual(momentUK.format(testFormat1)) expect(dayjsUK.format(testFormat2)).toEqual(momentUK.format(testFormat2)) expect(dayjsUK.format(testFormat3)).toEqual(momentUK.format(testFormat3)) expect(dayjsUK.format(testFormat4)).toEqual(momentUK.format(testFormat4)) } })
javascript
MIT
54f447048cee679e51a7053f8042d9b6b7028b89
2026-01-04T14:57:31.496629Z
false
iamkun/dayjs
https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/test/locale/pl.test.js
test/locale/pl.test.js
import moment from 'moment' import MockDate from 'mockdate' import dayjs from '../../src' import relativeTime from '../../src/plugin/relativeTime' import '../../src/locale/pl' dayjs.extend(relativeTime) beforeEach(() => { MockDate.set(new Date()) }) afterEach(() => { MockDate.reset() }) it('Format month with locale function', () => { for (let i = 0; i <= 7; i += 1) { const dayjsUK = dayjs().locale('pl').add(i, 'day') const momentUK = moment().locale('pl').add(i, 'day') const testFormat1 = 'DD MMMM YYYY MMM' const testFormat2 = 'dddd, MMMM D YYYY' const testFormat3 = 'MMMM' const testFormat4 = 'MMM' expect(dayjsUK.format(testFormat1)).toEqual(momentUK.format(testFormat1)) expect(dayjsUK.format(testFormat2)).toEqual(momentUK.format(testFormat2)) expect(dayjsUK.format(testFormat3)).toEqual(momentUK.format(testFormat3)) expect(dayjsUK.format(testFormat4)).toEqual(momentUK.format(testFormat4)) } }) it('RelativeTime: Time from X', () => { const T = [ [44.4, 'second'], // a few seconds [89.5, 'second'], // a minute [2, 'minute'], // 2 minutes [5, 'minute'], // 5 minutes [43, 'minute'], // 44 minutes [45, 'minute'], // an hour [3, 'hour'], // 3 hours [21, 'hour'], // 21 hours [1, 'day'], // a day [3, 'day'], // 3 day [25, 'day'], // 25 days [1, 'month'], // a month [2, 'month'], // 2 month [10, 'month'], // 10 month [1, 'year'], // a year [2, 'year'], // 2 year [5, 'year'], // 5 year [18, 'month'] // 2 years ] T.forEach((t) => { dayjs.locale('pl') moment.locale('pl') expect(dayjs().from(dayjs().add(t[0], t[1]))) .toBe(moment().from(moment().add(t[0], t[1]))) expect(dayjs().from(dayjs().add(t[0], t[1]), true)) .toBe(moment().from(moment().add(t[0], t[1]), true)) }) })
javascript
MIT
54f447048cee679e51a7053f8042d9b6b7028b89
2026-01-04T14:57:31.496629Z
false
iamkun/dayjs
https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/test/locale/he.test.js
test/locale/he.test.js
import moment from 'moment' import dayjs from '../../src' import relativeTime from '../../src/plugin/relativeTime' import '../../src/locale/he' dayjs.extend(relativeTime) it('RelativeTime: Time from X', () => { const T = [ [44.4, 'second'], // a few seconds [89.5, 'second'], // a minute [2, 'minute'], // 2 minutes [43, 'minute'], // 43 minutes [45, 'minute'], // an hour [3, 'hour'], // 3 hours [21, 'hour'], // 21 hours [1, 'day'], // a day [3, 'day'], // 3 day [25, 'day'], // 25 days [1, 'month'], // a month [2, 'month'], // 2 month [10, 'month'], // 10 month [1, 'year'], // a year [2, 'year'], // 2 year [5, 'year'], // 5 year [18, 'month'] // 2 years ] T.forEach((t) => { dayjs.locale('he') moment.locale('he') const dayjsDay = dayjs() const momentDay = moment() const dayjsCompare = dayjs().add(t[0], t[1]) const momentCompare = moment().add(t[0], t[1]) expect(dayjsDay.from(dayjsCompare)).toBe(momentDay.from(momentCompare)) expect(dayjsDay.to(dayjsCompare)).toBe(momentDay.to(momentCompare)) expect(dayjsDay.from(dayjsCompare, true)).toBe(momentDay.from(momentCompare, true)) }) })
javascript
MIT
54f447048cee679e51a7053f8042d9b6b7028b89
2026-01-04T14:57:31.496629Z
false
iamkun/dayjs
https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/test/locale/zh.test.js
test/locale/zh.test.js
import dayjs from '../../src' import advancedFormat from '../../src/plugin/advancedFormat' import weekOfYear from '../../src/plugin/weekOfYear' import '../../src/locale/zh' import '../../src/locale/zh-cn' dayjs.extend(advancedFormat).extend(weekOfYear) const zh = dayjs().locale('zh') const zhCN = dayjs().locale('zh-cn') test('ordinal', () => { expect(zh.format('wo')).toEqual(`${zh.format('w')}周`) }) test('Meridiem', () => { for (let i = 0; i <= 24; i += 1) { expect(zh.add(i, 'hour').format('A')).toBe(zhCN.add(i, 'hour').format('A')) } })
javascript
MIT
54f447048cee679e51a7053f8042d9b6b7028b89
2026-01-04T14:57:31.496629Z
false
iamkun/dayjs
https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/test/locale/bn.test.js
test/locale/bn.test.js
import moment from 'moment' import MockDate from 'mockdate' import dayjs from '../../src' import relativeTime from '../../src/plugin/relativeTime' import localeData from '../../src/plugin/localeData' import preParsePostFormat from '../../src/plugin/preParsePostFormat' import '../../src/locale/bn' dayjs.extend(localeData) dayjs.extend(relativeTime) dayjs.extend(preParsePostFormat) beforeEach(() => { MockDate.set(new Date()) }) afterEach(() => { MockDate.reset() }) it('Format Month with locale function', () => { for (let i = 0; i <= 7; i += 1) { const dayjsBN = dayjs() .locale('bn') .add(i, 'day') const momentBN = moment() .locale('bn') .add(i, 'day') const testFormat1 = 'DD MMMM YYYY MMM' const testFormat2 = 'MMMM' const testFormat3 = 'MMM' expect(dayjsBN.format(testFormat1)).toEqual(momentBN.format(testFormat1)) expect(dayjsBN.format(testFormat2)).toEqual(momentBN.format(testFormat2)) expect(dayjsBN.format(testFormat3)).toEqual(momentBN.format(testFormat3)) } }) it('Month short', () => { const date = '2021-02-01T05:54:32.005Z' const dayjsBN = dayjs(date) .locale('bn') const momentBN = moment(date) .locale('bn') const testFormat1 = 'DD MMMM YYYY MMM' expect(dayjsBN.format(testFormat1)).toEqual(momentBN.format(testFormat1)) }) it('Preparse with locale function', () => { for (let i = 0; i <= 7; i += 1) { dayjs.locale('bn') const momentBN = moment() .locale('bn') .add(i, 'day') expect(dayjs(momentBN.format()).format()).toEqual(momentBN.format()) } }) it('RelativeTime: Time from X', () => { const T = [ [44.4, 'second'], // a few seconds [89.5, 'second'], // a minute [130, 'second'], // two minutes [43, 'minute'], // 44 minutes [1, 'hour'], // 1 hour [21, 'hour'], // 21 hours [2, 'day'], // 2 days [25, 'day'], // 25 days [2, 'month'], // 2 months [10, 'month'], // 10 months [18, 'month'], // 2 years [15, 'year'] // 15 years ] T.forEach((t) => { dayjs.locale('bn') moment.locale('bn') expect(dayjs().from(dayjs().add(t[0], t[1]))).toBe(moment().from(moment().add(t[0], t[1]))) expect(dayjs().from(dayjs().add(t[0], t[1]), true)) .toBe(moment().from(moment().add(t[0], t[1]), true)) }) })
javascript
MIT
54f447048cee679e51a7053f8042d9b6b7028b89
2026-01-04T14:57:31.496629Z
false
iamkun/dayjs
https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/test/locale/hu.test.js
test/locale/hu.test.js
import moment from 'moment' import dayjs from '../../src' import relativeTime from '../../src/plugin/relativeTime' import '../../src/locale/hu' dayjs.extend(relativeTime) it('RelativeTime: Time from X', () => { const T = [ [44.4, 'second'], // a few seconds [89.5, 'second'], // a minute [2, 'minute'], // 2 minutes [43, 'minute'], // 43 minutes [45, 'minute'], // an hour [3, 'hour'], // 3 hours [21, 'hour'], // 21 hours [1, 'day'], // a day [3, 'day'], // 3 day [25, 'day'], // 25 days [1, 'month'], // a month [2, 'month'], // 2 month [10, 'month'], // 10 month [1, 'year'], // a year [2, 'year'], // 2 year [5, 'year'], // 5 year [18, 'month'] // 2 years ] T.forEach((t) => { dayjs.locale('hu') moment.locale('hu') const dayjsDay = dayjs() const momentDay = moment() const dayjsCompare = dayjs().add(t[0], t[1]) const momentCompare = moment().add(t[0], t[1]) expect(dayjsDay.from(dayjsCompare)).toBe(momentDay.from(momentCompare)) expect(dayjsDay.to(dayjsCompare)).toBe(momentDay.to(momentCompare)) expect(dayjsDay.from(dayjsCompare, true)).toBe(momentDay.from(momentCompare, true)) }) })
javascript
MIT
54f447048cee679e51a7053f8042d9b6b7028b89
2026-01-04T14:57:31.496629Z
false
iamkun/dayjs
https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/test/locale/et.test.js
test/locale/et.test.js
import moment from 'moment' import MockDate from 'mockdate' import dayjs from '../../src' import relativeTime from '../../src/plugin/relativeTime' import '../../src/locale/et' dayjs.extend(relativeTime) beforeEach(() => { MockDate.set(new Date()) }) afterEach(() => { MockDate.reset() }) it('RelativeTime: Time from X', () => { const T = [ [44.4, 'second'], // a few seconds [89.5, 'second'], // a minute [43, 'minute'], // 44 minutes [21, 'hour'], // 21 hours [25, 'day'], // 25 days [10, 'month'], // 2 month [18, 'month'] // 2 years ] T.forEach((t) => { dayjs.locale('et') moment.locale('et') expect(dayjs().from(dayjs().add(t[0], t[1]))) .toBe(moment().from(moment().add(t[0], t[1]))) expect(dayjs().from(dayjs().subtract(t[0], t[1]))) .toBe(moment().from(moment().subtract(t[0], t[1]))) expect(dayjs().from(dayjs().add(t[0], t[1]), true)) .toBe(moment().from(moment().add(t[0], t[1]), true)) }) })
javascript
MIT
54f447048cee679e51a7053f8042d9b6b7028b89
2026-01-04T14:57:31.496629Z
false
iamkun/dayjs
https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/test/locale/cs.test.js
test/locale/cs.test.js
import moment from 'moment' import MockDate from 'mockdate' import dayjs from '../../src' import relativeTime from '../../src/plugin/relativeTime' import '../../src/locale/cs' dayjs.extend(relativeTime) beforeEach(() => { MockDate.set(new Date()) }) afterEach(() => { MockDate.reset() }) it('RelativeTime: Time from X', () => { const T = [ [44.4, 'second'], // a few seconds [89.5, 'second'], // a minute [2, 'minute'], // 2 minutes [43, 'minute'], // 43 minutes [45, 'minute'], // an hour [3, 'hour'], // 3 hours [21, 'hour'], // 21 hours [1, 'day'], // a day [3, 'day'], // 3 day [25, 'day'], // 25 days [1, 'month'], // a month [2, 'month'], // 2 month [10, 'month'], // 10 month [1, 'year'], // a year [2, 'year'], // 2 year [5, 'year'], // 5 year [18, 'month'] // 2 years ] T.forEach((t) => { dayjs.locale('cs') moment.locale('cs') const dayjsDay = dayjs() const momentDay = moment() const dayjsCompare = dayjs().add(t[0], t[1]) const momentCompare = moment().add(t[0], t[1]) expect(dayjsDay.from(dayjsCompare)) .toBe(momentDay.from(momentCompare)) expect(dayjsDay.to(dayjsCompare)) .toBe(momentDay.to(momentCompare)) expect(dayjsDay.from(dayjsCompare, true)) .toBe(momentDay.from(momentCompare, true)) }) })
javascript
MIT
54f447048cee679e51a7053f8042d9b6b7028b89
2026-01-04T14:57:31.496629Z
false
iamkun/dayjs
https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/test/__mocks__/dayjs.js
test/__mocks__/dayjs.js
const dayjs = require('../../src') module.exports = dayjs
javascript
MIT
54f447048cee679e51a7053f8042d9b6b7028b89
2026-01-04T14:57:31.496629Z
false
iamkun/dayjs
https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/build/index.js
build/index.js
const rollup = require('rollup') const configFactory = require('./rollup.config') const fs = require('fs') const util = require('util') const path = require('path') const { ncp } = require('ncp') const { promisify } = util const promisifyReadDir = promisify(fs.readdir) const promisifyReadFile = promisify(fs.readFile) const promisifyWriteFile = promisify(fs.writeFile) const localeNameRegex = /\/\/ (.*) \[/ const formatName = n => n.replace(/\.js/, '').replace('-', '_') const localePath = path.join(__dirname, '../src/locale') async function build(option) { const bundle = await rollup.rollup(option.input) await bundle.write(option.output) } async function listLocaleJson(localeArr) { const localeListArr = [] await Promise.all(localeArr.map(async (l) => { const localeData = await promisifyReadFile(path.join(localePath, l), 'utf-8') localeListArr.push({ key: l.slice(0, -3), name: localeData.match(localeNameRegex)[1] }) })) promisifyWriteFile(path.join(__dirname, '../locale.json'), JSON.stringify(localeListArr), 'utf8') } (async () => { try { /* eslint-disable no-restricted-syntax, no-await-in-loop */ // We use await-in-loop to make rollup run sequentially to save on RAM const locales = await promisifyReadDir(localePath) for (const l of locales) { // run builds sequentially to limit RAM usage await build(configFactory({ input: `./src/locale/${l}`, fileName: `./locale/${l}`, name: `dayjs_locale_${formatName(l)}` })) } const plugins = await promisifyReadDir(path.join(__dirname, '../src/plugin')) for (const plugin of plugins) { // run builds sequentially to limit RAM usage await build(configFactory({ input: `./src/plugin/${plugin}/index`, fileName: `./plugin/${plugin}.js`, name: `dayjs_plugin_${formatName(plugin)}` })) } build(configFactory({ input: './src/index.js', fileName: './dayjs.min.js' })) await promisify(ncp)('./types/', './') // list locales await listLocaleJson(locales) } catch (e) { console.error(e) // eslint-disable-line no-console } })()
javascript
MIT
54f447048cee679e51a7053f8042d9b6b7028b89
2026-01-04T14:57:31.496629Z
false
iamkun/dayjs
https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/build/esm.js
build/esm.js
const fs = require('fs') const path = require('path') const util = require('util') const { ncp } = require('ncp') const { promisify } = util const typeFileExt = '.d.ts' const localeDir = path.join(process.env.PWD, 'esm/locale') const pluginDir = path.join(process.env.PWD, 'esm/plugin') const localeTypePath = path.join(process.env.PWD, 'esm/locale', `index${typeFileExt}`); (async () => { try { const readLocaleDir = await promisify(fs.readdir)(localeDir) readLocaleDir.forEach(async (l) => { const filePath = path.join(localeDir, l) const readFile = await promisify(fs.readFile)(filePath, 'utf8') const result = readFile.replace("'dayjs'", "'../index'") await promisify(fs.writeFile)(filePath, result, 'utf8') }) await promisify(ncp)('./types/', './esm') const readLocaleFile = await promisify(fs.readFile)(localeTypePath, 'utf8') const localResult = readLocaleFile.replace("'dayjs", "'dayjs/esm") await promisify(fs.writeFile)(localeTypePath, localResult, 'utf8') const readPluginDir = await promisify(fs.readdir)(pluginDir) readPluginDir.forEach(async (p) => { if (p.includes(typeFileExt)) { const pluginName = p.replace(typeFileExt, '') const filePath = path.join(pluginDir, p) const targetPath = path.join(pluginDir, pluginName, `index${typeFileExt}`) const readFile = await promisify(fs.readFile)(filePath, 'utf8') const result = readFile.replace(/'dayjs'/g, "'dayjs/esm'") await promisify(fs.writeFile)(targetPath, result, 'utf8') await promisify(fs.unlink)(filePath) } }) } catch (e) { console.error(e) // eslint-disable-line no-console } })()
javascript
MIT
54f447048cee679e51a7053f8042d9b6b7028b89
2026-01-04T14:57:31.496629Z
false
iamkun/dayjs
https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/build/rollup.config.js
build/rollup.config.js
const babel = require('rollup-plugin-babel') const { terser } = require('rollup-plugin-terser') module.exports = (config) => { const { input, fileName, name } = config return { input: { input, external: [ 'dayjs' ], plugins: [ babel({ exclude: 'node_modules/**' }), terser() ] }, output: { file: fileName, format: 'umd', name: name || 'dayjs', globals: { dayjs: 'dayjs' }, compact: true } } }
javascript
MIT
54f447048cee679e51a7053f8042d9b6b7028b89
2026-01-04T14:57:31.496629Z
false
iamkun/dayjs
https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/docs/demo/index.js
docs/demo/index.js
import dayjs from 'dayjs' // basic usage dayjs().format() // parse dayjs('2018-08-08').format() // format dayjs().format('YYYY-MM-DD') // locale dayjs().locale('zh-cn').format() // add dayjs().add(1, 'year').format() // subtract dayjs().subtract(1, 'year').format() // diff dayjs().diff(dayjs().add(1, 'year'), 'year') // isBefore dayjs().isBefore(dayjs().add(1, 'year')) // isAfter dayjs().isAfter(dayjs().subtract(1, 'year')) // isSame dayjs().isSame(dayjs()) // isLeapYear dayjs().isLeapYear() // isBetween dayjs().isBetween(dayjs().subtract(1, 'year'), dayjs().add(1, 'year')) // isSameOrAfter dayjs().isSameOrAfter(dayjs().subtract(1, 'year')) // isSameOrBefore dayjs().isSameOrBefore(dayjs().add(1, 'year')) // startOf dayjs().startOf('year').format() // endOf dayjs().endOf('year').format() // week dayjs().week() // weekday dayjs().weekday()
javascript
MIT
54f447048cee679e51a7053f8042d9b6b7028b89
2026-01-04T14:57:31.496629Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/rollup.config.js
rollup.config.js
import terser from '@rollup/plugin-terser'; import fs from 'fs'; const pkg = JSON.parse(fs.readFileSync('./package.json', 'utf-8')); const banner = (format, content = '') => chunk => { const date = new Date(); const moduleName = chunk.fileName.split('/')[0] || ''; return `/** * Anime.js${ moduleName.includes('.') ? '' : ' - ' + moduleName } - ${ format } * @version v${ pkg.version } * @license MIT * @copyright ${ date.getFullYear() } - Julian Garnier */${content} ` } const replace = (rgx, string = '') => { return { name: 'replace', generateBundle(_, bundle) { Object.keys(bundle).forEach((fileName) => { const file = bundle[fileName]; let code = file.code; code = code.replace(rgx, string); file.code = code; }); } } } const updatePackageVersion = replace(/__packageVersion__/g, pkg.version); // Extracts module input paths from the package.json 'exports' field const inputs = Object.keys(pkg.exports).filter(k => k !== './package.json').map(k => `src${k.replace('.', '')}/index.js`); console.log(inputs); const tasks = [{ input: inputs, output: [ { dir: 'dist/modules/', format: 'esm', preserveModules: true, preserveModulesRoot: 'src', banner: banner('ESM'), }, { dir: 'dist/modules/', format: 'cjs', entryFileNames: '[name].cjs', preserveModules: true, preserveModulesRoot: 'src', banner: banner('CJS'), } ], plugins: [updatePackageVersion], }]; if (process.env.build) { // Gets global JSDoc type definitions from src/types to be inserted in the banner of the bundles after tree shaking const JSDocTypes = fs.readFileSync('./src/types/index.js', 'utf-8').split('// Exported types')[1]; // Removes comments containing JSDoc @import tags to avoid duplicated type definitions in bundles const cleanupJSDocImports = replace(/\/\*\*(?:(?!\*\/|\/\*\*)[\s\S])*?@import(?:(?!\*\/|\/\*\*)[\s\S])*?\*\//g); const minify = terser({ compress: { passes: 10, module: false }, mangle: true, }); tasks.push({ input: 'src/index.js', output: [ { file: 'dist/bundles/anime.esm.js', format: 'esm', name: 'anime', banner: banner('ESM bundle', JSDocTypes) }, { file: 'dist/bundles/anime.umd.js', format: 'umd', name: 'anime', banner: banner('UMD bundle', JSDocTypes) } ], plugins: [updatePackageVersion, cleanupJSDocImports] }); tasks.push({ input: 'src/index.js', output: [ { file: 'dist/bundles/anime.esm.min.js', format: 'esm', name: 'anime', banner: banner('ESM minified bundle') }, { file: 'dist/bundles/anime.umd.min.js', format: 'umd', name: 'anime', banner: banner('UMD minified bundle') } ], plugins: [updatePackageVersion, minify] }); } export default tasks;
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/src/index.js
src/index.js
export * from './timer/index.js'; export * from './animation/index.js'; export * from './timeline/index.js'; export * from './animatable/index.js'; export * from './draggable/index.js'; export * from './scope/index.js'; export * from './events/index.js'; export * from './engine/index.js'; export * from './easings/index.js'; export * as easings from './easings/index.js'; export * from './utils/index.js'; export * as utils from './utils/index.js'; export * from './svg/index.js'; export * as svg from './svg/index.js'; export * from './text/index.js'; export * as text from './text/index.js'; export * from './waapi/index.js'; export * from './types/index.js';
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/src/scope/index.js
src/scope/index.js
export * from './scope.js';
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/src/scope/scope.js
src/scope/scope.js
import { doc, win, } from '../core/consts.js'; import { scope, globals, } from '../core/globals.js'; import { isFnc, mergeObjects, } from '../core/helpers.js'; import { parseTargets, } from '../core/targets.js'; import { keepTime, } from '../utils/time.js'; /** * @import { * Tickable, * ScopeParams, * DOMTarget, * ReactRef, * AngularRef, * DOMTargetSelector, * DefaultsParams, * ScopeConstructorCallback, * ScopeCleanupCallback, * Revertible, * ScopeMethod, * ScopedCallback, * } from '../types/index.js' */ export class Scope { /** @param {ScopeParams} [parameters] */ constructor(parameters = {}) { if (scope.current) scope.current.register(this); const rootParam = parameters.root; /** @type {Document|DOMTarget} */ let root = doc; if (rootParam) { root = /** @type {ReactRef} */(rootParam).current || /** @type {AngularRef} */(rootParam).nativeElement || parseTargets(/** @type {DOMTargetSelector} */(rootParam))[0] || doc; } const scopeDefaults = parameters.defaults; const globalDefault = globals.defaults; const mediaQueries = parameters.mediaQueries; /** @type {DefaultsParams} */ this.defaults = scopeDefaults ? mergeObjects(scopeDefaults, globalDefault) : globalDefault; /** @type {Document|DOMTarget} */ this.root = root; /** @type {Array<ScopeConstructorCallback>} */ this.constructors = []; /** @type {Array<ScopeCleanupCallback>} */ this.revertConstructors = []; /** @type {Array<Revertible>} */ this.revertibles = []; /** @type {Array<ScopeConstructorCallback | ((scope: this) => Tickable)>} */ this.constructorsOnce = []; /** @type {Array<ScopeCleanupCallback>} */ this.revertConstructorsOnce = []; /** @type {Array<Revertible>} */ this.revertiblesOnce = []; /** @type {Boolean} */ this.once = false; /** @type {Number} */ this.onceIndex = 0; /** @type {Record<String, ScopeMethod>} */ this.methods = {}; /** @type {Record<String, Boolean>} */ this.matches = {}; /** @type {Record<String, MediaQueryList>} */ this.mediaQueryLists = {}; /** @type {Record<String, any>} */ this.data = {}; if (mediaQueries) { for (let mq in mediaQueries) { const _mq = win.matchMedia(mediaQueries[mq]); this.mediaQueryLists[mq] = _mq; _mq.addEventListener('change', this); } } } /** * @param {Revertible} revertible */ register(revertible) { const store = this.once ? this.revertiblesOnce : this.revertibles; store.push(revertible); } /** * @template T * @param {ScopedCallback<T>} cb * @return {T} */ execute(cb) { let activeScope = scope.current; let activeRoot = scope.root; let activeDefaults = globals.defaults; scope.current = this; scope.root = this.root; globals.defaults = this.defaults; const mqs = this.mediaQueryLists; for (let mq in mqs) this.matches[mq] = mqs[mq].matches; const returned = cb(this); scope.current = activeScope; scope.root = activeRoot; globals.defaults = activeDefaults; return returned; } /** * @return {this} */ refresh() { this.onceIndex = 0; this.execute(() => { let i = this.revertibles.length; let y = this.revertConstructors.length; while (i--) this.revertibles[i].revert(); while (y--) this.revertConstructors[y](this); this.revertibles.length = 0; this.revertConstructors.length = 0; this.constructors.forEach((/** @type {ScopeConstructorCallback} */constructor) => { const revertConstructor = constructor(this); if (isFnc(revertConstructor)) { this.revertConstructors.push(revertConstructor); } }); }); return this; } /** * @overload * @param {String} a1 * @param {ScopeMethod} a2 * @return {this} * * @overload * @param {ScopeConstructorCallback} a1 * @return {this} * * @param {String|ScopeConstructorCallback} a1 * @param {ScopeMethod} [a2] */ add(a1, a2) { this.once = false; if (isFnc(a1)) { const constructor = /** @type {ScopeConstructorCallback} */(a1); this.constructors.push(constructor); this.execute(() => { const revertConstructor = constructor(this); if (isFnc(revertConstructor)) { this.revertConstructors.push(revertConstructor); } }); } else { this.methods[/** @type {String} */(a1)] = (/** @type {any} */...args) => this.execute(() => a2(...args)); } return this; } /** * @param {ScopeConstructorCallback} scopeConstructorCallback * @return {this} */ addOnce(scopeConstructorCallback) { this.once = true; if (isFnc(scopeConstructorCallback)) { const currentIndex = this.onceIndex++; const tracked = this.constructorsOnce[currentIndex]; if (tracked) return this; const constructor = /** @type {ScopeConstructorCallback} */(scopeConstructorCallback); this.constructorsOnce[currentIndex] = constructor; this.execute(() => { const revertConstructor = constructor(this); if (isFnc(revertConstructor)) { this.revertConstructorsOnce.push(revertConstructor); } }); } return this; } /** * @param {(scope: this) => Tickable} cb * @return {Tickable} */ keepTime(cb) { this.once = true; const currentIndex = this.onceIndex++; const tracked = /** @type {(scope: this) => Tickable} */(this.constructorsOnce[currentIndex]); if (isFnc(tracked)) return tracked(this); const constructor = /** @type {(scope: this) => Tickable} */(keepTime(cb)); this.constructorsOnce[currentIndex] = constructor; let trackedTickable; this.execute(() => { trackedTickable = constructor(this); }); return trackedTickable; } /** * @param {Event} e */ handleEvent(e) { switch (e.type) { case 'change': this.refresh(); break; } } revert() { const revertibles = this.revertibles; const revertConstructors = this.revertConstructors; const revertiblesOnce = this.revertiblesOnce; const revertConstructorsOnce = this.revertConstructorsOnce; const mqs = this.mediaQueryLists; let i = revertibles.length; let j = revertConstructors.length; let k = revertiblesOnce.length; let l = revertConstructorsOnce.length; while (i--) revertibles[i].revert(); while (j--) revertConstructors[j](this); while (k--) revertiblesOnce[k].revert(); while (l--) revertConstructorsOnce[l](this); for (let mq in mqs) mqs[mq].removeEventListener('change', this); revertibles.length = 0; revertConstructors.length = 0; this.constructors.length = 0; revertiblesOnce.length = 0; revertConstructorsOnce.length = 0; this.constructorsOnce.length = 0; this.onceIndex = 0; this.matches = {}; this.methods = {}; this.mediaQueryLists = {}; this.data = {}; } } /** * @param {ScopeParams} [params] * @return {Scope} */ export const createScope = params => new Scope(params);
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/src/draggable/index.js
src/draggable/index.js
export * from './draggable.js';
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/src/draggable/draggable.js
src/draggable/draggable.js
import { scope, globals, } from '../core/globals.js'; import { win, doc, maxValue, noop, compositionTypes, } from '../core/consts.js'; import { parseTargets, } from '../core/targets.js'; import { snap, clamp, round, isObj, isUnd, isArr, isFnc, sqrt, max, atan2, cos, sin, abs, now, isNum, } from '../core/helpers.js'; import { setValue, } from '../core/values.js'; import { mapRange, } from '../utils/number.js'; import { Timer, } from '../timer/timer.js'; import { JSAnimation, } from '../animation/animation.js'; import { removeTargetsFromRenderable, } from '../animation/composition.js'; import { Animatable, } from '../animatable/animatable.js'; import { eases, parseEase, } from '../easings/eases/parser.js'; import { spring, } from '../easings/spring/index.js'; import { get, set, } from '../utils/target.js'; /** * @import { * DOMTarget, * DOMTargetSelector, * DraggableCursorParams, * DraggableDragThresholdParams, * TargetsParam, * DraggableParams, * EasingFunction, * Callback, * AnimatableParams, * DraggableAxisParam, * AnimatableObject, * EasingParam, * } from '../types/index.js' */ /** * @import { * Spring, * } from '../easings/spring/index.js' */ /** * @param {Event} e */ const preventDefault = e => { if (e.cancelable) e.preventDefault(); } class DOMProxy { /** @param {Object} el */ constructor(el) { this.el = el; this.zIndex = 0; this.parentElement = null; this.classList = { add: noop, remove: noop, } } get x() { return this.el.x || 0 }; set x(v) { this.el.x = v }; get y() { return this.el.y || 0 }; set y(v) { this.el.y = v }; get width() { return this.el.width || 0 }; set width(v) { this.el.width = v }; get height() { return this.el.height || 0 }; set height(v) { this.el.height = v }; getBoundingClientRect() { return { top: this.y, right: this.x, bottom: this.y + this.height, left: this.x + this.width, } } } class Transforms { /** * @param {DOMTarget|DOMProxy} $el */ constructor($el) { this.$el = $el; this.inlineTransforms = []; this.point = new DOMPoint(); this.inversedMatrix = this.getMatrix().inverse(); } /** * @param {Number} x * @param {Number} y * @return {DOMPoint} */ normalizePoint(x, y) { this.point.x = x; this.point.y = y; return this.point.matrixTransform(this.inversedMatrix); } /** * @callback TraverseParentsCallback * @param {DOMTarget} $el * @param {Number} i */ /** * @param {TraverseParentsCallback} cb */ traverseUp(cb) { let $el = /** @type {DOMTarget|Document} */(this.$el.parentElement), i = 0; while ($el && $el !== doc) { cb(/** @type {DOMTarget} */($el), i); $el = /** @type {DOMTarget} */($el.parentElement); i++; } } getMatrix() { const matrix = new DOMMatrix(); this.traverseUp($el => { const transformValue = getComputedStyle($el).transform; if (transformValue) { const elMatrix = new DOMMatrix(transformValue); matrix.preMultiplySelf(elMatrix); } }); return matrix; } remove() { this.traverseUp(($el, i) => { this.inlineTransforms[i] = $el.style.transform; $el.style.transform = 'none'; }); } revert() { this.traverseUp(($el, i) => { const ct = this.inlineTransforms[i]; if (ct === '') { $el.style.removeProperty('transform'); } else { $el.style.transform = ct; } }); } } /** * @template {Array<Number>|DOMTargetSelector|String|Number|Boolean|Function|DraggableCursorParams|DraggableDragThresholdParams} T * @param {T | ((draggable: Draggable) => T)} value * @param {Draggable} draggable * @return {T} */ const parseDraggableFunctionParameter = (value, draggable) => value && isFnc(value) ? /** @type {Function} */(value)(draggable) : /** @type {T} */(value); let zIndex = 0; export class Draggable { /** * @param {TargetsParam} target * @param {DraggableParams} [parameters] */ constructor(target, parameters = {}) { if (!target) return; if (scope.current) scope.current.register(this); const paramX = parameters.x; const paramY = parameters.y; const trigger = parameters.trigger; const modifier = parameters.modifier; const ease = parameters.releaseEase; const customEase = ease && parseEase(ease); const hasSpring = !isUnd(ease) && !isUnd(/** @type {Spring} */(ease).ease); const xProp = /** @type {String} */(isObj(paramX) && !isUnd(/** @type {Object} */(paramX).mapTo) ? /** @type {Object} */(paramX).mapTo : 'translateX'); const yProp = /** @type {String} */(isObj(paramY) && !isUnd(/** @type {Object} */(paramY).mapTo) ? /** @type {Object} */(paramY).mapTo : 'translateY'); const container = parseDraggableFunctionParameter(parameters.container, this); this.containerArray = isArr(container) ? container : null; this.$container = /** @type {HTMLElement} */(container && !this.containerArray ? parseTargets(/** @type {DOMTarget} */(container))[0] : doc.body); this.useWin = this.$container === doc.body; /** @type {Window | HTMLElement} */ this.$scrollContainer = this.useWin ? win : this.$container; this.$target = /** @type {HTMLElement} */(isObj(target) ? new DOMProxy(target) : parseTargets(target)[0]); this.$trigger = /** @type {HTMLElement} */(parseTargets(trigger ? trigger : target)[0]); this.fixed = get(this.$target, 'position') === 'fixed'; // Refreshable parameters this.isFinePointer = true; /** @type {[Number, Number, Number, Number]} */ this.containerPadding = [0, 0, 0, 0]; /** @type {Number} */ this.containerFriction = 0; /** @type {Number} */ this.releaseContainerFriction = 0; /** @type {Number|Array<Number>} */ this.snapX = 0; /** @type {Number|Array<Number>} */ this.snapY = 0; /** @type {Number} */ this.scrollSpeed = 0; /** @type {Number} */ this.scrollThreshold = 0; /** @type {Number} */ this.dragSpeed = 0; /** @type {Number} */ this.dragThreshold = 3; /** @type {Number} */ this.maxVelocity = 0; /** @type {Number} */ this.minVelocity = 0; /** @type {Number} */ this.velocityMultiplier = 0; /** @type {Boolean|DraggableCursorParams} */ this.cursor = false; /** @type {Spring} */ this.releaseXSpring = hasSpring ? /** @type {Spring} */(ease) : spring({ mass: setValue(parameters.releaseMass, 1), stiffness: setValue(parameters.releaseStiffness, 80), damping: setValue(parameters.releaseDamping, 20), }); /** @type {Spring} */ this.releaseYSpring = hasSpring ? /** @type {Spring} */(ease) : spring({ mass: setValue(parameters.releaseMass, 1), stiffness: setValue(parameters.releaseStiffness, 80), damping: setValue(parameters.releaseDamping, 20), }); /** @type {EasingFunction} */ this.releaseEase = customEase || eases.outQuint; /** @type {Boolean} */ this.hasReleaseSpring = hasSpring; /** @type {Callback<this>} */ this.onGrab = parameters.onGrab || noop; /** @type {Callback<this>} */ this.onDrag = parameters.onDrag || noop; /** @type {Callback<this>} */ this.onRelease = parameters.onRelease || noop; /** @type {Callback<this>} */ this.onUpdate = parameters.onUpdate || noop; /** @type {Callback<this>} */ this.onSettle = parameters.onSettle || noop; /** @type {Callback<this>} */ this.onSnap = parameters.onSnap || noop; /** @type {Callback<this>} */ this.onResize = parameters.onResize || noop; /** @type {Callback<this>} */ this.onAfterResize = parameters.onAfterResize || noop; /** @type {[Number, Number]} */ this.disabled = [0, 0]; /** @type {AnimatableParams} */ const animatableParams = {}; if (modifier) animatableParams.modifier = modifier; if (isUnd(paramX) || paramX === true) { animatableParams[xProp] = 0; } else if (isObj(paramX)) { const paramXObject = /** @type {DraggableAxisParam} */(paramX); const animatableXParams = {}; if (paramXObject.modifier) animatableXParams.modifier = paramXObject.modifier; if (paramXObject.composition) animatableXParams.composition = paramXObject.composition; animatableParams[xProp] = animatableXParams; } else if (paramX === false) { animatableParams[xProp] = 0; this.disabled[0] = 1; } if (isUnd(paramY) || paramY === true) { animatableParams[yProp] = 0; } else if (isObj(paramY)) { const paramYObject = /** @type {DraggableAxisParam} */(paramY); const animatableYParams = {}; if (paramYObject.modifier) animatableYParams.modifier = paramYObject.modifier; if (paramYObject.composition) animatableYParams.composition = paramYObject.composition; animatableParams[yProp] = animatableYParams; } else if (paramY === false) { animatableParams[yProp] = 0; this.disabled[1] = 1; } /** @type {AnimatableObject} */ this.animate = /** @type {AnimatableObject} */(new Animatable(this.$target, animatableParams)); // Internal props this.xProp = xProp; this.yProp = yProp; this.destX = 0; this.destY = 0; this.deltaX = 0; this.deltaY = 0; this.scroll = {x: 0, y: 0}; /** @type {[Number, Number, Number, Number]} */ this.coords = [this.x, this.y, 0, 0]; // x, y, temp x, temp y /** @type {[Number, Number]} */ this.snapped = [0, 0]; // x, y /** @type {[Number, Number, Number, Number, Number, Number, Number, Number]} */ this.pointer = [0, 0, 0, 0, 0, 0, 0, 0]; // x1, y1, x2, y2, temp x1, temp y1, temp x2, temp y2 /** @type {[Number, Number]} */ this.scrollView = [0, 0]; // w, h /** @type {[Number, Number, Number, Number]} */ this.dragArea = [0, 0, 0, 0]; // x, y, w, h /** @type {[Number, Number, Number, Number]} */ this.containerBounds = [-maxValue, maxValue, maxValue, -maxValue]; // t, r, b, l /** @type {[Number, Number, Number, Number]} */ this.scrollBounds = [0, 0, 0, 0]; // t, r, b, l /** @type {[Number, Number, Number, Number]} */ this.targetBounds = [0, 0, 0, 0]; // t, r, b, l /** @type {[Number, Number]} */ this.window = [0, 0]; // w, h /** @type {[Number, Number, Number]} */ this.velocityStack = [0, 0, 0]; /** @type {Number} */ this.velocityStackIndex = 0; /** @type {Number} */ this.velocityTime = now(); /** @type {Number} */ this.velocity = 0; /** @type {Number} */ this.angle = 0; /** @type {JSAnimation} */ this.cursorStyles = null; /** @type {JSAnimation} */ this.triggerStyles = null; /** @type {JSAnimation} */ this.bodyStyles = null; /** @type {JSAnimation} */ this.targetStyles = null; /** @type {JSAnimation} */ this.touchActionStyles = null; this.transforms = new Transforms(this.$target); this.overshootCoords = { x: 0, y: 0 }; this.overshootTicker = new Timer({ autoplay: false, onUpdate: () => { this.updated = true; this.manual = true; // Use a duration of 1 to prevent the animatable from completing immediately to prevent issues with onSettle() // https://github.com/juliangarnier/anime/issues/1045 if (!this.disabled[0]) this.animate[this.xProp](this.overshootCoords.x, 1); if (!this.disabled[1]) this.animate[this.yProp](this.overshootCoords.y, 1); }, onComplete: () => { this.manual = false; if (!this.disabled[0]) this.animate[this.xProp](this.overshootCoords.x, 0); if (!this.disabled[1]) this.animate[this.yProp](this.overshootCoords.y, 0); }, }, null, 0).init(); this.updateTicker = new Timer({ autoplay: false, onUpdate: () => this.update() }, null,0,).init(); this.contained = !isUnd(container); this.manual = false; this.grabbed = false; this.dragged = false; this.updated = false; this.released = false; this.canScroll = false; this.enabled = false; this.initialized = false; this.activeProp = this.disabled[1] ? xProp : yProp; this.animate.callbacks.onRender = () => { const hasUpdated = this.updated; const hasMoved = this.grabbed && hasUpdated; const hasReleased = !hasMoved && this.released; const x = this.x; const y = this.y; const dx = x - this.coords[2]; const dy = y - this.coords[3]; this.deltaX = dx; this.deltaY = dy; this.coords[2] = x; this.coords[3] = y; // Check if dx or dy are not 0 to check if the draggable has actually moved // https://github.com/juliangarnier/anime/issues/1032 if (hasUpdated && (dx || dy)) { this.onUpdate(this); } if (!hasReleased) { this.updated = false; } else { this.computeVelocity(dx, dy); this.angle = atan2(dy, dx); } } this.animate.callbacks.onComplete = () => { if ((!this.grabbed && this.released)) { // Set released to false before calling onSettle to avoid recursion this.released = false; } if (!this.manual) { this.deltaX = 0; this.deltaY = 0; this.velocity = 0; this.velocityStack[0] = 0; this.velocityStack[1] = 0; this.velocityStack[2] = 0; this.velocityStackIndex = 0; this.onSettle(this); } }; this.resizeTicker = new Timer({ autoplay: false, duration: 150 * globals.timeScale, onComplete: () => { this.onResize(this); this.refresh(); this.onAfterResize(this); }, }).init(); this.parameters = parameters; this.resizeObserver = new ResizeObserver(() => { if (this.initialized) { this.resizeTicker.restart(); } else { this.initialized = true; } }); this.enable(); this.refresh(); this.resizeObserver.observe(this.$container); if (!isObj(target)) this.resizeObserver.observe(this.$target); } /** * @param {Number} dx * @param {Number} dy * @return {Number} */ computeVelocity(dx, dy) { const prevTime = this.velocityTime; const curTime = now(); const elapsed = curTime - prevTime; if (elapsed < 17) return this.velocity; this.velocityTime = curTime; const velocityStack = this.velocityStack; const vMul = this.velocityMultiplier; const minV = this.minVelocity; const maxV = this.maxVelocity; const vi = this.velocityStackIndex; velocityStack[vi] = round(clamp((sqrt(dx * dx + dy * dy) / elapsed) * vMul, minV, maxV), 5); const velocity = max(velocityStack[0], velocityStack[1], velocityStack[2]); this.velocity = velocity; this.velocityStackIndex = (vi + 1) % 3; return velocity; } /** * @param {Number} x * @param {Boolean} [muteUpdateCallback] * @return {this} */ setX(x, muteUpdateCallback = false) { if (this.disabled[0]) return; const v = round(x, 5); this.overshootTicker.pause(); this.manual = true; this.updated = !muteUpdateCallback; this.destX = v; this.snapped[0] = snap(v, this.snapX); this.animate[this.xProp](v, 0); this.manual = false; return this; } /** * @param {Number} y * @param {Boolean} [muteUpdateCallback] * @return {this} */ setY(y, muteUpdateCallback = false) { if (this.disabled[1]) return; const v = round(y, 5); this.overshootTicker.pause(); this.manual = true; this.updated = !muteUpdateCallback; this.destY = v; this.snapped[1] = snap(v, this.snapY); this.animate[this.yProp](v, 0); this.manual = false; return this; } get x() { return round(/** @type {Number} */(this.animate[this.xProp]()), globals.precision); } set x(x) { this.setX(x, false); } get y() { return round(/** @type {Number} */(this.animate[this.yProp]()), globals.precision); } set y(y) { this.setY(y, false); } get progressX() { return mapRange(this.x, this.containerBounds[3], this.containerBounds[1], 0, 1); } set progressX(x) { this.setX(mapRange(x, 0, 1, this.containerBounds[3], this.containerBounds[1]), false); } get progressY() { return mapRange(this.y, this.containerBounds[0], this.containerBounds[2], 0, 1); } set progressY(y) { this.setY(mapRange(y, 0, 1, this.containerBounds[0], this.containerBounds[2]), false); } updateScrollCoords() { const sx = round(this.useWin ? win.scrollX : this.$container.scrollLeft, 0); const sy = round(this.useWin ? win.scrollY : this.$container.scrollTop, 0); const [ cpt, cpr, cpb, cpl ] = this.containerPadding; const threshold = this.scrollThreshold; this.scroll.x = sx; this.scroll.y = sy; this.scrollBounds[0] = sy - this.targetBounds[0] + cpt - threshold; this.scrollBounds[1] = sx - this.targetBounds[1] - cpr + threshold; this.scrollBounds[2] = sy - this.targetBounds[2] - cpb + threshold; this.scrollBounds[3] = sx - this.targetBounds[3] + cpl - threshold; } updateBoundingValues() { const $container = this.$container; // Return early if no $container defined to prevents error when reading scrollWidth / scrollHeight // https://github.com/juliangarnier/anime/issues/1064 if (!$container) return; const cx = this.x; const cy = this.y; const cx2 = this.coords[2]; const cy2 = this.coords[3]; // Prevents interfering with the scroll area in cases the target is outside of the container // Make sure the temp coords are also adjuset to prevents wrong delta calculation on updates this.coords[2] = 0; this.coords[3] = 0; this.setX(0, true); this.setY(0, true); this.transforms.remove(); const iw = this.window[0] = win.innerWidth; const ih = this.window[1] = win.innerHeight; const uw = this.useWin; const sw = $container.scrollWidth; const sh = $container.scrollHeight; const fx = this.fixed; const transformContainerRect = $container.getBoundingClientRect(); const [ cpt, cpr, cpb, cpl ] = this.containerPadding; this.dragArea[0] = uw ? 0 : transformContainerRect.left; this.dragArea[1] = uw ? 0 : transformContainerRect.top; this.scrollView[0] = uw ? clamp(sw, iw, sw) : sw; this.scrollView[1] = uw ? clamp(sh, ih, sh) : sh; this.updateScrollCoords(); const { width, height, left, top, right, bottom } = $container.getBoundingClientRect(); this.dragArea[2] = round(uw ? clamp(width, iw, iw) : width, 0); this.dragArea[3] = round(uw ? clamp(height, ih, ih) : height, 0); const containerOverflow = get($container, 'overflow'); const visibleOverflow = containerOverflow === 'visible'; const hiddenOverflow = containerOverflow === 'hidden'; this.canScroll = fx ? false : this.contained && (($container === doc.body && visibleOverflow) || (!hiddenOverflow && !visibleOverflow)) && (sw > this.dragArea[2] + cpl - cpr || sh > this.dragArea[3] + cpt - cpb) && (!this.containerArray || (this.containerArray && !isArr(this.containerArray))); if (this.contained) { const sx = this.scroll.x; const sy = this.scroll.y; const canScroll = this.canScroll; const targetRect = this.$target.getBoundingClientRect(); const hiddenLeft = canScroll ? uw ? 0 : $container.scrollLeft : 0; const hiddenTop = canScroll ? uw ? 0 : $container.scrollTop : 0; const hiddenRight = canScroll ? this.scrollView[0] - hiddenLeft - width : 0; const hiddenBottom = canScroll ? this.scrollView[1] - hiddenTop - height : 0; this.targetBounds[0] = round((targetRect.top + sy) - (uw ? 0 : top), 0); this.targetBounds[1] = round((targetRect.right + sx) - (uw ? iw : right), 0); this.targetBounds[2] = round((targetRect.bottom + sy) - (uw ? ih : bottom), 0); this.targetBounds[3] = round((targetRect.left + sx) - (uw ? 0 : left), 0); if (this.containerArray) { this.containerBounds[0] = this.containerArray[0] + cpt; this.containerBounds[1] = this.containerArray[1] - cpr; this.containerBounds[2] = this.containerArray[2] - cpb; this.containerBounds[3] = this.containerArray[3] + cpl; } else { this.containerBounds[0] = -round(targetRect.top - (fx ? clamp(top, 0, ih) : top) + hiddenTop - cpt, 0); this.containerBounds[1] = -round(targetRect.right - (fx ? clamp(right, 0, iw) : right) - hiddenRight + cpr, 0); this.containerBounds[2] = -round(targetRect.bottom - (fx ? clamp(bottom, 0, ih) : bottom) - hiddenBottom + cpb, 0); this.containerBounds[3] = -round(targetRect.left - (fx ? clamp(left, 0, iw) : left) + hiddenLeft - cpl, 0); } } this.transforms.revert(); // Restore coordinates this.coords[2] = cx2; this.coords[3] = cy2; this.setX(cx, true); this.setY(cy, true); } /** * @param {Array} bounds * @param {Number} x * @param {Number} y * @return {Number} */ isOutOfBounds(bounds, x, y) { // Returns 0 if not OB, 1 if x is OB, 2 if y is OB, 3 if both x and y are OB if (!this.contained) return 0; const [ bt, br, bb, bl ] = bounds; const [ dx, dy ] = this.disabled; const obx = !dx && x < bl || !dx && x > br; const oby = !dy && y < bt || !dy && y > bb; return obx && !oby ? 1 : !obx && oby ? 2 : obx && oby ? 3 : 0; } refresh() { const params = this.parameters; const paramX = params.x; const paramY = params.y; const container = parseDraggableFunctionParameter(params.container, this); const cp = parseDraggableFunctionParameter(params.containerPadding, this) || 0; const containerPadding = /** @type {[Number, Number, Number, Number]} */(isArr(cp) ? cp : [cp, cp, cp, cp]); const cx = this.x; const cy = this.y; const parsedCursorStyles = parseDraggableFunctionParameter(params.cursor, this); const cursorStyles = { onHover: 'grab', onGrab: 'grabbing' }; if (parsedCursorStyles) { const { onHover, onGrab } = /** @type {DraggableCursorParams} */(parsedCursorStyles); if (onHover) cursorStyles.onHover = onHover; if (onGrab) cursorStyles.onGrab = onGrab; } const parsedDragThreshold = parseDraggableFunctionParameter(params.dragThreshold, this); const dragThreshold = { mouse: 3, touch: 7 }; if (isNum(parsedDragThreshold)) { dragThreshold.mouse = parsedDragThreshold; dragThreshold.touch = parsedDragThreshold; } else if (parsedDragThreshold) { const { mouse, touch } = parsedDragThreshold; if (!isUnd(mouse)) dragThreshold.mouse = mouse; if (!isUnd(touch)) dragThreshold.touch = touch; } this.containerArray = isArr(container) ? container : null; this.$container = /** @type {HTMLElement} */(container && !this.containerArray ? parseTargets(/** @type {DOMTarget} */(container))[0] : doc.body); this.useWin = this.$container === doc.body; /** @type {Window | HTMLElement} */ this.$scrollContainer = this.useWin ? win : this.$container; this.isFinePointer = matchMedia('(pointer:fine)').matches; this.containerPadding = setValue(containerPadding, [0, 0, 0, 0]); this.containerFriction = clamp(setValue(parseDraggableFunctionParameter(params.containerFriction, this), .8), 0, 1); this.releaseContainerFriction = clamp(setValue(parseDraggableFunctionParameter(params.releaseContainerFriction, this), this.containerFriction), 0, 1); this.snapX = parseDraggableFunctionParameter(isObj(paramX) && !isUnd(paramX.snap) ? paramX.snap : params.snap, this); this.snapY = parseDraggableFunctionParameter(isObj(paramY) && !isUnd(paramY.snap) ? paramY.snap : params.snap, this); this.scrollSpeed = setValue(parseDraggableFunctionParameter(params.scrollSpeed, this), 1.5); this.scrollThreshold = setValue(parseDraggableFunctionParameter(params.scrollThreshold, this), 20); this.dragSpeed = setValue(parseDraggableFunctionParameter(params.dragSpeed, this), 1); this.dragThreshold = this.isFinePointer ? dragThreshold.mouse : dragThreshold.touch; this.minVelocity = setValue(parseDraggableFunctionParameter(params.minVelocity, this), 0); this.maxVelocity = setValue(parseDraggableFunctionParameter(params.maxVelocity, this), 50); this.velocityMultiplier = setValue(parseDraggableFunctionParameter(params.velocityMultiplier, this), 1); this.cursor = parsedCursorStyles === false ? false : cursorStyles; this.updateBoundingValues(); // const ob = this.isOutOfBounds(this.containerBounds, this.x, this.y); // if (ob === 1 || ob === 3) this.progressX = px; // if (ob === 2 || ob === 3) this.progressY = py; // if (this.initialized && this.contained) { // if (this.progressX !== px) this.progressX = px; // if (this.progressY !== py) this.progressY = py; // } const [ bt, br, bb, bl ] = this.containerBounds; this.setX(clamp(cx, bl, br), true); this.setY(clamp(cy, bt, bb), true); } update() { this.updateScrollCoords(); if (this.canScroll) { const [ cpt, cpr, cpb, cpl ] = this.containerPadding; const [ sw, sh ] = this.scrollView; const daw = this.dragArea[2]; const dah = this.dragArea[3]; const csx = this.scroll.x; const csy = this.scroll.y; const nsw = this.$container.scrollWidth; const nsh = this.$container.scrollHeight; const csw = this.useWin ? clamp(nsw, this.window[0], nsw) : nsw; const csh = this.useWin ? clamp(nsh, this.window[1], nsh) : nsh; const swd = sw - csw; const shd = sh - csh; // Handle cases where the scrollarea dimensions changes during drag if (this.dragged && swd > 0) { this.coords[0] -= swd; this.scrollView[0] = csw; } if (this.dragged && shd > 0) { this.coords[1] -= shd; this.scrollView[1] = csh; } // Handle autoscroll when target is at the edges of the scroll bounds const s = this.scrollSpeed * 10; const threshold = this.scrollThreshold; const [ x, y ] = this.coords; const [ st, sr, sb, sl ] = this.scrollBounds; const t = round(clamp((y - st + cpt) / threshold, -1, 0) * s, 0); const r = round(clamp((x - sr - cpr) / threshold, 0, 1) * s, 0); const b = round(clamp((y - sb - cpb) / threshold, 0, 1) * s, 0); const l = round(clamp((x - sl + cpl) / threshold, -1, 0) * s, 0); if (t || b || l || r) { const [nx, ny] = this.disabled; let scrollX = csx; let scrollY = csy; if (!nx) { scrollX = round(clamp(csx + (l || r), 0, sw - daw), 0); this.coords[0] -= csx - scrollX; } if (!ny) { scrollY = round(clamp(csy + (t || b), 0, sh - dah), 0); this.coords[1] -= csy - scrollY; } // Note: Safari mobile requires to use different scroll methods depending if using the window or not if (this.useWin) { this.$scrollContainer.scrollBy(-(csx - scrollX), -(csy - scrollY)); } else { this.$scrollContainer.scrollTo(scrollX, scrollY); } } } const [ ct, cr, cb, cl ] = this.containerBounds; const [ px1, py1, px2, py2, px3, py3 ] = this.pointer; this.coords[0] += (px1 - px3) * this.dragSpeed; this.coords[1] += (py1 - py3) * this.dragSpeed; this.pointer[4] = px1; this.pointer[5] = py1; const [ cx, cy ] = this.coords; const [ sx, sy ] = this.snapped; const cf = (1 - this.containerFriction) * this.dragSpeed; this.setX(cx > cr ? cr + (cx - cr) * cf : cx < cl ? cl + (cx - cl) * cf : cx, false); this.setY(cy > cb ? cb + (cy - cb) * cf : cy < ct ? ct + (cy - ct) * cf : cy, false); this.computeVelocity(px1 - px3, py1 - py3); this.angle = atan2(py1 - py2, px1 - px2); const [ nsx, nsy ] = this.snapped; if (nsx !== sx && this.snapX || nsy !== sy && this.snapY) { this.onSnap(this); } } stop() { this.updateTicker.pause(); this.overshootTicker.pause(); // Pauses the in bounds onRelease animations for (let prop in this.animate.animations) this.animate.animations[prop].pause(); removeTargetsFromRenderable([this], null, 'x'); removeTargetsFromRenderable([this], null, 'y'); removeTargetsFromRenderable([this], null, 'progressX'); removeTargetsFromRenderable([this], null, 'progressY'); removeTargetsFromRenderable([this.scroll]); // Removes any active animations on the container scroll removeTargetsFromRenderable([this.overshootCoords]); // Removes active overshoot animations return this; } /** * @param {Number} [duration] * @param {Number} [gap] * @param {EasingParam} [ease] * @return {this} */ scrollInView(duration, gap = 0, ease = eases.inOutQuad) { this.updateScrollCoords(); const x = this.destX; const y = this.destY; const scroll = this.scroll; const scrollBounds = this.scrollBounds; const canScroll = this.canScroll; if (!this.containerArray && this.isOutOfBounds(scrollBounds, x, y)) { const [ st, sr, sb, sl ] = scrollBounds; const t = round(clamp(y - st, -maxValue, 0), 0); const r = round(clamp(x - sr, 0, maxValue), 0); const b = round(clamp(y - sb, 0, maxValue), 0); const l = round(clamp(x - sl, -maxValue, 0), 0); new JSAnimation(scroll, { x: round(scroll.x + (l ? l - gap : r ? r + gap : 0), 0), y: round(scroll.y + (t ? t - gap : b ? b + gap : 0), 0), duration: isUnd(duration) ? 350 * globals.timeScale : duration, ease, onUpdate: () => { this.canScroll = false; this.$scrollContainer.scrollTo(scroll.x, scroll.y); } }).init().then(() => { this.canScroll = canScroll; }) } return this; } handleHover() { if (this.isFinePointer && this.cursor && !this.cursorStyles) { this.cursorStyles = set(this.$trigger, { cursor: /** @type {DraggableCursorParams} */(this.cursor).onHover }); } } /** * @param {Number} [duration] * @param {Number} [gap] * @param {EasingParam} [ease] * @return {this} */ animateInView(duration, gap = 0, ease = eases.inOutQuad) { this.stop(); this.updateBoundingValues(); const x = this.x; const y = this.y; const [ cpt, cpr, cpb, cpl ] = this.containerPadding; const bt = this.scroll.y - this.targetBounds[0] + cpt + gap; const br = this.scroll.x - this.targetBounds[1] - cpr - gap; const bb = this.scroll.y - this.targetBounds[2] - cpb - gap; const bl = this.scroll.x - this.targetBounds[3] + cpl + gap; const ob = this.isOutOfBounds([bt, br, bb, bl], x, y); if (ob) { const [ disabledX, disabledY ] = this.disabled; const destX = clamp(snap(x, this.snapX), bl, br); const destY = clamp(snap(y, this.snapY), bt, bb); const dur = isUnd(duration) ? 350 * globals.timeScale : duration; if (!disabledX && (ob === 1 || ob === 3)) this.animate[this.xProp](destX, dur, ease); if (!disabledY && (ob === 2 || ob === 3)) this.animate[this.yProp](destY, dur, ease); } return this; } /** * @param {MouseEvent|TouchEvent} e */ handleDown(e) { const $eTarget = /** @type {HTMLElement} */(e.target); if (this.grabbed || /** @type {HTMLInputElement} */($eTarget).type === 'range') return; e.stopPropagation(); this.grabbed = true; this.released = false; this.stop(); this.updateBoundingValues(); const touches = /** @type {TouchEvent} */(e).changedTouches; const eventX = touches ? touches[0].clientX : /** @type {MouseEvent} */(e).clientX; const eventY = touches ? touches[0].clientY : /** @type {MouseEvent} */(e).clientY; const { x, y } = this.transforms.normalizePoint(eventX, eventY); const [ ct, cr, cb, cl ] = this.containerBounds; const cf = (1 - this.containerFriction) * this.dragSpeed; const cx = this.x; const cy = this.y; this.coords[0] = this.coords[2] = !cf ? cx : cx > cr ? cr + (cx - cr) / cf : cx < cl ? cl + (cx - cl) / cf : cx; this.coords[1] = this.coords[3] = !cf ? cy : cy > cb ? cb + (cy - cb) / cf : cy < ct ? ct + (cy - ct) / cf : cy; this.pointer[0] = x; this.pointer[1] = y; this.pointer[2] = x; this.pointer[3] = y; this.pointer[4] = x; this.pointer[5] = y; this.pointer[6] = x; this.pointer[7] = y; this.deltaX = 0; this.deltaY = 0; this.velocity = 0; this.velocityStack[0] = 0; this.velocityStack[1] = 0; this.velocityStack[2] = 0; this.velocityStackIndex = 0; this.angle = 0;
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
true
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/src/easings/index.js
src/easings/index.js
export * from './cubic-bezier/index.js'; export * from './steps/index.js'; export * from './linear/index.js'; export * from './irregular/index.js'; export * from './spring/index.js'; export * from './eases/index.js';
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/src/easings/none.js
src/easings/none.js
/** * @import { * EasingFunction, * } from '../types/index.js' */ /** @type {EasingFunction} */ export const none = t => t;
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/src/easings/linear/index.js
src/easings/linear/index.js
import { isStr, isUnd, parseNumber, } from '../../core/helpers.js'; import { none, } from '../none.js'; /** * @import { * EasingFunction, * } from '../../types/index.js' */ /** * Without parameters, the linear function creates a non-eased transition. * Parameters, if used, creates a piecewise linear easing by interpolating linearly between the specified points. * * @param {...(String|Number)} args - Points * @return {EasingFunction} */ export const linear = (...args) => { const argsLength = args.length; if (!argsLength) return none; const totalPoints = argsLength - 1; const firstArg = args[0]; const lastArg = args[totalPoints]; const xPoints = [0]; const yPoints = [parseNumber(firstArg)]; for (let i = 1; i < totalPoints; i++) { const arg = args[i]; const splitValue = isStr(arg) ? /** @type {String} */(arg).trim().split(' ') : [arg]; const value = splitValue[0]; const percent = splitValue[1]; xPoints.push(!isUnd(percent) ? parseNumber(percent) / 100 : i / totalPoints); yPoints.push(parseNumber(value)); } yPoints.push(parseNumber(lastArg)); xPoints.push(1); return function easeLinear(t) { for (let i = 1, l = xPoints.length; i < l; i++) { const currentX = xPoints[i]; if (t <= currentX) { const prevX = xPoints[i - 1]; const prevY = yPoints[i - 1]; return prevY + (yPoints[i] - prevY) * (t - prevX) / (currentX - prevX); } } return yPoints[yPoints.length - 1]; } }
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/src/easings/irregular/index.js
src/easings/irregular/index.js
import { clamp, } from "../../core/helpers.js"; import { linear, } from "../linear/index.js"; /** * @import { * EasingFunction, * } from '../../types/index.js' */ /** * Generate random steps * @param {Number} [length] - The number of steps * @param {Number} [randomness] - How strong the randomness is * @return {EasingFunction} */ export const irregular = (length = 10, randomness = 1) => { const values = [0]; const total = length - 1; for (let i = 1; i < total; i++) { const previousValue = values[i - 1]; const spacing = i / total; const segmentEnd = (i + 1) / total; const randomVariation = spacing + (segmentEnd - spacing) * Math.random(); // Mix the even spacing and random variation based on the randomness parameter const randomValue = spacing * (1 - randomness) + randomVariation * randomness; values.push(clamp(randomValue, previousValue, 1)); } values.push(1); return linear(...values); }
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/src/easings/cubic-bezier/index.js
src/easings/cubic-bezier/index.js
import { abs, } from '../../core/helpers.js'; import { none, } from '../none.js'; /** * @import { * EasingFunction, * } from '../../types/index.js' */ /** * Cubic Bezier solver adapted from https://github.com/gre/bezier-easing * (c) 2014 Gaëtan Renaudeau */ /** * @param {Number} aT * @param {Number} aA1 * @param {Number} aA2 * @return {Number} */ const calcBezier = (aT, aA1, aA2) => (((1 - 3 * aA2 + 3 * aA1) * aT + (3 * aA2 - 6 * aA1)) * aT + (3 * aA1)) * aT; /** * @param {Number} aX * @param {Number} mX1 * @param {Number} mX2 * @return {Number} */ const binarySubdivide = (aX, mX1, mX2) => { let aA = 0, aB = 1, currentX, currentT, i = 0; do { currentT = aA + (aB - aA) / 2; currentX = calcBezier(currentT, mX1, mX2) - aX; if (currentX > 0) { aB = currentT; } else { aA = currentT; } } while (abs(currentX) > .0000001 && ++i < 100); return currentT; } /** * @param {Number} [mX1] The x coordinate of the first point * @param {Number} [mY1] The y coordinate of the first point * @param {Number} [mX2] The x coordinate of the second point * @param {Number} [mY2] The y coordinate of the second point * @return {EasingFunction} */ export const cubicBezier = (mX1 = 0.5, mY1 = 0.0, mX2 = 0.5, mY2 = 1.0) => (mX1 === mY1 && mX2 === mY2) ? none : t => t === 0 || t === 1 ? t : calcBezier(binarySubdivide(t, mX1, mX2), mY1, mY2);
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/src/easings/eases/index.js
src/easings/eases/index.js
export { eases } from './parser.js';
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/src/easings/eases/parser.js
src/easings/eases/parser.js
import { minValue, emptyString, } from '../../core/consts.js'; import { isStr, isFnc, clamp, sqrt, cos, sin, asin, PI, pow, stringStartsWith, } from '../../core/helpers.js'; import { none } from '../none.js'; /** * @import { * EasingFunction, * EasingFunctionWithParams, * EasingParam, * BackEasing, * ElasticEasing, * PowerEasing, * } from '../../types/index.js' */ /** @type {PowerEasing} */ export const easeInPower = (p = 1.68) => t => pow(t, +p); /** * @callback EaseType * @param {EasingFunction} Ease * @return {EasingFunction} */ /** @type {Record<String, EaseType>} */ export const easeTypes = { in: easeIn => t => easeIn(t), out: easeIn => t => 1 - easeIn(1 - t), inOut: easeIn => t => t < .5 ? easeIn(t * 2) / 2 : 1 - easeIn(t * -2 + 2) / 2, outIn: easeIn => t => t < .5 ? (1 - easeIn(1 - t * 2)) / 2 : (easeIn(t * 2 - 1) + 1) / 2, } /** * Easing functions adapted and simplified from https://robertpenner.com/easing/ * (c) 2001 Robert Penner */ const halfPI = PI / 2; const doublePI = PI * 2; /** @type {Record<String, EasingFunctionWithParams|EasingFunction>} */ const easeInFunctions = { [emptyString]: easeInPower, Quad: easeInPower(2), Cubic: easeInPower(3), Quart: easeInPower(4), Quint: easeInPower(5), /** @type {EasingFunction} */ Sine: t => 1 - cos(t * halfPI), /** @type {EasingFunction} */ Circ: t => 1 - sqrt(1 - t * t), /** @type {EasingFunction} */ Expo: t => t ? pow(2, 10 * t - 10) : 0, /** @type {EasingFunction} */ Bounce: t => { let pow2, b = 4; while (t < ((pow2 = pow(2, --b)) - 1) / 11); return 1 / pow(4, 3 - b) - 7.5625 * pow((pow2 * 3 - 2) / 22 - t, 2); }, /** @type {BackEasing} */ Back: (overshoot = 1.7) => t => (+overshoot + 1) * t * t * t - +overshoot * t * t, /** @type {ElasticEasing} */ Elastic: (amplitude = 1, period = .3) => { const a = clamp(+amplitude, 1, 10); const p = clamp(+period, minValue, 2); const s = (p / doublePI) * asin(1 / a); const e = doublePI / p; return t => t === 0 || t === 1 ? t : -a * pow(2, -10 * (1 - t)) * sin(((1 - t) - s) * e); } } /** * @typedef {Object} EasesFunctions * @property {typeof none} linear * @property {typeof none} none * @property {PowerEasing} in * @property {PowerEasing} out * @property {PowerEasing} inOut * @property {PowerEasing} outIn * @property {EasingFunction} inQuad * @property {EasingFunction} outQuad * @property {EasingFunction} inOutQuad * @property {EasingFunction} outInQuad * @property {EasingFunction} inCubic * @property {EasingFunction} outCubic * @property {EasingFunction} inOutCubic * @property {EasingFunction} outInCubic * @property {EasingFunction} inQuart * @property {EasingFunction} outQuart * @property {EasingFunction} inOutQuart * @property {EasingFunction} outInQuart * @property {EasingFunction} inQuint * @property {EasingFunction} outQuint * @property {EasingFunction} inOutQuint * @property {EasingFunction} outInQuint * @property {EasingFunction} inSine * @property {EasingFunction} outSine * @property {EasingFunction} inOutSine * @property {EasingFunction} outInSine * @property {EasingFunction} inCirc * @property {EasingFunction} outCirc * @property {EasingFunction} inOutCirc * @property {EasingFunction} outInCirc * @property {EasingFunction} inExpo * @property {EasingFunction} outExpo * @property {EasingFunction} inOutExpo * @property {EasingFunction} outInExpo * @property {EasingFunction} inBounce * @property {EasingFunction} outBounce * @property {EasingFunction} inOutBounce * @property {EasingFunction} outInBounce * @property {BackEasing} inBack * @property {BackEasing} outBack * @property {BackEasing} inOutBack * @property {BackEasing} outInBack * @property {ElasticEasing} inElastic * @property {ElasticEasing} outElastic * @property {ElasticEasing} inOutElastic * @property {ElasticEasing} outInElastic */ export const eases = (/*#__PURE__ */ (() => { const list = { linear: none, none: none }; for (let type in easeTypes) { for (let name in easeInFunctions) { const easeIn = easeInFunctions[name]; const easeType = easeTypes[type]; list[type + name] = /** @type {EasingFunctionWithParams|EasingFunction} */( name === emptyString || name === 'Back' || name === 'Elastic' ? (a, b) => easeType(/** @type {EasingFunctionWithParams} */(easeIn)(a, b)) : easeType(/** @type {EasingFunction} */(easeIn)) ); } } return /** @type {EasesFunctions} */(list); })()); /** @type {Record<String, EasingFunction>} */ const easesLookups = { linear: none, none: none }; /** * @param {String} string * @return {EasingFunction} */ export const parseEaseString = (string) => { if (easesLookups[string]) return easesLookups[string]; if (string.indexOf('(') <= -1) { const hasParams = easeTypes[string] || string.includes('Back') || string.includes('Elastic'); const parsedFn = /** @type {EasingFunction} */(hasParams ? /** @type {EasingFunctionWithParams} */(eases[string])() : eases[string]); return parsedFn ? easesLookups[string] = parsedFn : none; } else { const split = string.slice(0, -1).split('('); const parsedFn = /** @type {EasingFunctionWithParams} */(eases[split[0]]); return parsedFn ? easesLookups[string] = parsedFn(...split[1].split(',')) : none; } } const deprecated = ['steps(', 'irregular(', 'linear(', 'cubicBezier(']; /** * @param {EasingParam} ease * @return {EasingFunction} */ export const parseEase = ease => { if (isStr(ease)) { for (let i = 0, l = deprecated.length; i < l; i++) { if (stringStartsWith(ease, deprecated[i])) { console.warn(`String syntax for \`ease: "${ease}"\` has been removed from the core and replaced by importing and passing the easing function directly: \`ease: ${ease}\``); return none; } } } const easeFunc = isFnc(ease) ? ease : isStr(ease) ? parseEaseString(/** @type {String} */(ease)) : none; return easeFunc; }
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/src/easings/spring/index.js
src/easings/spring/index.js
import { K, minValue, noop, } from '../../core/consts.js'; import { globals, } from '../../core/globals.js'; import { isUnd, round, clamp, sqrt, exp, cos, sin, abs, pow, PI, } from '../../core/helpers.js'; import { setValue, } from '../../core/values.js'; /** * @import { * JSAnimation, * } from '../../animation/animation.js' */ /** * @import { * EasingFunction, * SpringParams, * Callback, * } from '../../types/index.js' */ /* * Spring easing solver adapted from https://webkit.org/demos/spring/spring.js * (c) 2016 Webkit - Apple Inc */ const maxSpringParamValue = K * 10; export class Spring { /** * @param {SpringParams} [parameters] */ constructor(parameters = {}) { const hasBounceOrDuration = !isUnd(parameters.bounce) || !isUnd(parameters.duration); this.timeStep = .02; // Interval fed to the solver to calculate duration this.restThreshold = .0005; // Values below this threshold are considered resting position this.restDuration = 200; // Duration in ms used to check if the spring is resting after reaching restThreshold this.maxDuration = 60000; // The maximum allowed spring duration in ms (default 1 min) this.maxRestSteps = this.restDuration / this.timeStep / K; // How many steps allowed after reaching restThreshold before stopping the duration calculation this.maxIterations = this.maxDuration / this.timeStep / K; // Calculate the maximum iterations allowed based on maxDuration this.bn = clamp(setValue(parameters.bounce, .5), -1, 1); // The bounce percentage between -1 and 1. this.pd = clamp(setValue(parameters.duration, 628), 10 * globals.timeScale, maxSpringParamValue * globals.timeScale); // The perceived duration this.m = clamp(setValue(parameters.mass, 1), 1, maxSpringParamValue); this.s = clamp(setValue(parameters.stiffness, 100), minValue, maxSpringParamValue); this.d = clamp(setValue(parameters.damping, 10), minValue, maxSpringParamValue); this.v = clamp(setValue(parameters.velocity, 0), -maxSpringParamValue, maxSpringParamValue); this.w0 = 0; this.zeta = 0; this.wd = 0; this.b = 0; this.completed = false; this.solverDuration = 0; this.settlingDuration = 0; /** @type {JSAnimation} */ this.parent = null; /** @type {Callback<JSAnimation>} */ this.onComplete = parameters.onComplete || noop; if (hasBounceOrDuration) this.calculateSDFromBD(); this.compute(); /** @type {EasingFunction} */ this.ease = t => { const currentTime = t * this.settlingDuration; const completed = this.completed; const perceivedTime = this.pd; if (currentTime >= perceivedTime && !completed) { this.completed = true; this.onComplete(this.parent); } if (currentTime < perceivedTime && completed) { this.completed = false; } return t === 0 || t === 1 ? t : this.solve(t * this.solverDuration); } } /** @type {EasingFunction} */ solve(time) { const { zeta, w0, wd, b } = this; let t = time; if (zeta < 1) { // Underdamped t = exp(-t * zeta * w0) * (1 * cos(wd * t) + b * sin(wd * t)); } else if (zeta === 1) { // Critically damped t = (1 + b * t) * exp(-t * w0); } else { // Overdamped // Using exponential instead of cosh and sinh functions to prevent Infinity // Original exp(-zeta * w0 * t) * (cosh(wd * t) + b * sinh(wd * t)) t = ((1 + b) * exp((-zeta * w0 + wd) * t) + (1 - b) * exp((-zeta * w0 - wd) * t)) / 2; } return 1 - t; } calculateSDFromBD() { // Apple's SwiftUI perceived spring duration implementation https://developer.apple.com/videos/play/wwdc2023/10158/?time=1010 // Equations taken from Kevin Grajeda's article https://www.kvin.me/posts/effortless-ui-spring-animations const pds = globals.timeScale === 1 ? this.pd / K : this.pd; // Mass and velocity should be set to their default values this.m = 1; this.v = 0; // Stiffness = (2π ÷ perceptualDuration)² this.s = pow((2 * PI) / pds, 2); if (this.bn >= 0) { // For bounce ≥ 0 (critically damped to underdamped) // damping = ((1 - bounce) × 4π) ÷ perceptualDuration this.d = ((1 - this.bn) * 4 * PI) / pds; } else { // For bounce < 0 (overdamped) // damping = 4π ÷ (perceptualDuration × (1 + bounce)) // Note: (1 + bounce) is positive since bounce is negative this.d = (4 * PI) / (pds * (1 + this.bn)); } this.s = round(clamp(this.s, minValue, maxSpringParamValue), 3); this.d = round(clamp(this.d, minValue, 300), 3); // Clamping to 300 is needed to prevent insane values in the solver } calculateBDFromSD() { // Calculate perceived duration and bounce from stiffness and damping // Note: We assumes m = 1 and v = 0 for these calculations const pds = (2 * PI) / sqrt(this.s); this.pd = pds * (globals.timeScale === 1 ? K : 1); const zeta = this.d / (2 * sqrt(this.s)); if (zeta <= 1) { // Critically damped to underdamped this.bn = 1 - (this.d * pds) / (4 * PI); } else { // Overdamped this.bn = (4 * PI) / (this.d * pds) - 1; } this.bn = round(clamp(this.bn, -1, 1), 3); this.pd = round(clamp(this.pd, 10 * globals.timeScale, maxSpringParamValue * globals.timeScale), 3); } compute() { const { maxRestSteps, maxIterations, restThreshold, timeStep, m, d, s, v } = this; const w0 = this.w0 = clamp(sqrt(s / m), minValue, K); const bouncedZeta = this.zeta = d / (2 * sqrt(s * m)); // Calculate wd based on damping type if (bouncedZeta < 1) { // Underdamped this.wd = w0 * sqrt(1 - bouncedZeta * bouncedZeta); this.b = (bouncedZeta * w0 + -v) / this.wd; } else if (bouncedZeta === 1) { // Critically damped this.wd = 0; this.b = -v + w0; } else { // Overdamped this.wd = w0 * sqrt(bouncedZeta * bouncedZeta - 1); this.b = (bouncedZeta * w0 + -v) / this.wd; } let solverTime = 0; let restSteps = 0; let iterations = 0; while (restSteps <= maxRestSteps && iterations <= maxIterations) { if (abs(1 - this.solve(solverTime)) < restThreshold) { restSteps++; } else { restSteps = 0; } this.solverDuration = solverTime; solverTime += timeStep; iterations++; } this.settlingDuration = round(this.solverDuration * K, 0) * globals.timeScale; } get bounce() { return this.bn; } set bounce(v) { this.bn = clamp(setValue(v, 1), -1, 1); this.calculateSDFromBD(); this.compute(); } get duration() { return this.pd; } set duration(v) { this.pd = clamp(setValue(v, 1), 10 * globals.timeScale, maxSpringParamValue * globals.timeScale); this.calculateSDFromBD(); this.compute(); } get stiffness() { return this.s; } set stiffness(v) { this.s = clamp(setValue(v, 100), minValue, maxSpringParamValue); this.calculateBDFromSD(); this.compute(); } get damping() { return this.d; } set damping(v) { this.d = clamp(setValue(v, 10), minValue, maxSpringParamValue); this.calculateBDFromSD(); this.compute(); } get mass() { return this.m; } set mass(v) { this.m = clamp(setValue(v, 1), 1, maxSpringParamValue); this.compute(); } get velocity() { return this.v; } set velocity(v) { this.v = clamp(setValue(v, 0), -maxSpringParamValue, maxSpringParamValue); this.compute(); } } /** * @param {SpringParams} [parameters] * @returns {Spring} */ export const spring = (parameters) => new Spring(parameters); /** * @deprecated createSpring() is deprecated use spring() instead * * @param {SpringParams} [parameters] * @returns {Spring} */ export const createSpring = (parameters) => { console.warn('createSpring() is deprecated use spring() instead'); return new Spring(parameters); }
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/src/easings/steps/index.js
src/easings/steps/index.js
import { ceil, clamp, floor, } from "../../core/helpers.js"; /** * @import { * EasingFunction, * } from '../../types/index.js' */ /** * Steps ease implementation https://developer.mozilla.org/fr/docs/Web/CSS/transition-timing-function * Only covers 'end' and 'start' jumpterms * @param {Number} steps * @param {Boolean} [fromStart] * @return {EasingFunction} */ export const steps = (steps = 10, fromStart) => { const roundMethod = fromStart ? ceil : floor; return t => roundMethod(clamp(t, 0, 1) * steps) * (1 / steps); }
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/src/utils/index.js
src/utils/index.js
export * from './chainable.js'; export * from './random.js'; export * from './time.js'; export * from './target.js'; export * from './stagger.js';
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/src/utils/target.js
src/utils/target.js
import { globals, } from '../core/globals.js'; import { minValue, compositionTypes, valueTypes, } from '../core/consts.js'; import { isUnd, round, } from '../core/helpers.js'; import { parseTargets, registerTargets, } from '../core/targets.js'; import { sanitizePropertyName, } from '../core/styles.js'; import { setValue, getTweenType, getOriginalAnimatableValue, decomposeRawValue, decomposedOriginalValue, } from '../core/values.js'; import { convertValueUnit, } from '../core/units.js'; import { removeWAAPIAnimation, } from '../waapi/composition.js'; import { removeTargetsFromRenderable, } from '../animation/composition.js'; import { JSAnimation, } from '../animation/animation.js'; export { registerTargets as $ }; /** * @import { * Renderable, * DOMTargetSelector, * JSTargetsParam, * DOMTargetsParam, * TargetsParam, * DOMTarget, * AnimationParams, * TargetsArray, * } from '../types/index.js' */ /** * @import { * WAAPIAnimation * } from '../waapi/waapi.js' */ /** * @overload * @param {DOMTargetSelector} targetSelector * @param {String} propName * @return {String} * * @overload * @param {JSTargetsParam} targetSelector * @param {String} propName * @return {Number|String} * * @overload * @param {DOMTargetsParam} targetSelector * @param {String} propName * @param {String} unit * @return {String} * * @overload * @param {TargetsParam} targetSelector * @param {String} propName * @param {Boolean} unit * @return {Number} * * @param {TargetsParam} targetSelector * @param {String} propName * @param {String|Boolean} [unit] */ export function get(targetSelector, propName, unit) { const targets = registerTargets(targetSelector); if (!targets.length) return; const [ target ] = targets; const tweenType = getTweenType(target, propName); const normalizePropName = sanitizePropertyName(propName, target, tweenType); let originalValue = getOriginalAnimatableValue(target, normalizePropName); if (isUnd(unit)) { return originalValue; } else { decomposeRawValue(originalValue, decomposedOriginalValue); if (decomposedOriginalValue.t === valueTypes.NUMBER || decomposedOriginalValue.t === valueTypes.UNIT) { if (unit === false) { return decomposedOriginalValue.n; } else { const convertedValue = convertValueUnit(/** @type {DOMTarget} */(target), decomposedOriginalValue, /** @type {String} */(unit), false); return `${round(convertedValue.n, globals.precision)}${convertedValue.u}`; } } } } /** * @param {TargetsParam} targets * @param {AnimationParams} parameters * @return {JSAnimation} */ export const set = (targets, parameters) => { if (isUnd(parameters)) return; parameters.duration = minValue; // Do not overrides currently active tweens by default parameters.composition = setValue(parameters.composition, compositionTypes.none); // Skip init() and force rendering by playing the animation return new JSAnimation(targets, parameters, null, 0, true).resume(); } /** * @param {TargetsParam} targets * @param {Renderable|WAAPIAnimation} [renderable] * @param {String} [propertyName] * @return {TargetsArray} */ export const remove = (targets, renderable, propertyName) => { const targetsArray = parseTargets(targets); for (let i = 0, l = targetsArray.length; i < l; i++) { removeWAAPIAnimation( /** @type {DOMTarget} */(targetsArray[i]), propertyName, renderable && /** @type {WAAPIAnimation} */(renderable).controlAnimation && /** @type {WAAPIAnimation} */(renderable), ) } removeTargetsFromRenderable( targetsArray, /** @type {Renderable} */(renderable), propertyName ) return targetsArray; } export { cleanInlineStyles } from '../core/styles.js';
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/src/utils/time.js
src/utils/time.js
import { noop, } from '../core/consts.js'; import { globals, } from '../core/globals.js'; import { isFnc, isUnd, } from '../core/helpers.js'; import { Timer, } from '../timer/timer.js'; /** * @import { * Callback, * Tickable, * } from '../types/index.js' */ /** * @param {Callback<Timer>} [callback] * @return {Timer} */ export const sync = (callback = noop) => { return new Timer({ duration: 1 * globals.timeScale, onComplete: callback }, null, 0).resume(); } /** * @param {(...args: any[]) => Tickable | ((...args: any[]) => void)} constructor * @return {(...args: any[]) => Tickable | ((...args: any[]) => void)} */ export const keepTime = constructor => { /** @type {Tickable} */ let tracked; return (...args) => { let currentIteration, currentIterationProgress, reversed, alternate; if (tracked) { currentIteration = tracked.currentIteration; currentIterationProgress = tracked.iterationProgress; reversed = tracked.reversed; alternate = tracked._alternate; tracked.revert(); } const cleanup = constructor(...args); if (cleanup && !isFnc(cleanup) && cleanup.revert) tracked = cleanup; if (!isUnd(currentIterationProgress)) { /** @type {Tickable} */(tracked).currentIteration = currentIteration; /** @type {Tickable} */(tracked).iterationProgress = (alternate ? !(currentIteration % 2) ? reversed : !reversed : reversed) ? 1 - currentIterationProgress : currentIterationProgress; } return cleanup || noop; } }
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/src/utils/stagger.js
src/utils/stagger.js
import { emptyString, unitsExecRgx, } from '../core/consts.js'; import { isArr, isUnd, isNum, parseNumber, round, abs, floor, sqrt, max, isStr, isFnc, } from '../core/helpers.js'; import { parseEase, } from '../easings/eases/parser.js'; import { parseTimelinePosition, } from '../timeline/position.js'; import { getOriginalAnimatableValue, } from '../core/values.js'; import { registerTargets, } from '../core/targets.js'; import { shuffle, } from './random.js'; /** * @import { * StaggerParams, * StaggerFunction, * } from '../types/index.js' */ /** * @import { * Spring, * } from '../easings/spring/index.js' */ /** * @overload * @param {Number} val * @param {StaggerParams} [params] * @return {StaggerFunction<Number>} */ /** * @overload * @param {String} val * @param {StaggerParams} [params] * @return {StaggerFunction<String>} */ /** * @overload * @param {[Number, Number]} val * @param {StaggerParams} [params] * @return {StaggerFunction<Number>} */ /** * @overload * @param {[String, String]} val * @param {StaggerParams} [params] * @return {StaggerFunction<String>} */ /** * @param {Number|String|[Number, Number]|[String, String]} val The staggered value or range * @param {StaggerParams} [params] The stagger parameters * @return {StaggerFunction<Number|String>} */ export const stagger = (val, params = {}) => { let values = []; let maxValue = 0; const from = params.from; const reversed = params.reversed; const ease = params.ease; const hasEasing = !isUnd(ease); const hasSpring = hasEasing && !isUnd(/** @type {Spring} */(ease).ease); const staggerEase = hasSpring ? /** @type {Spring} */(ease).ease : hasEasing ? parseEase(ease) : null; const grid = params.grid; const axis = params.axis; const customTotal = params.total; const fromFirst = isUnd(from) || from === 0 || from === 'first'; const fromCenter = from === 'center'; const fromLast = from === 'last'; const fromRandom = from === 'random'; const isRange = isArr(val); const useProp = params.use; const val1 = isRange ? parseNumber(val[0]) : parseNumber(val); const val2 = isRange ? parseNumber(val[1]) : 0; const unitMatch = unitsExecRgx.exec((isRange ? val[1] : val) + emptyString); const start = params.start || 0 + (isRange ? val1 : 0); let fromIndex = fromFirst ? 0 : isNum(from) ? from : 0; return (target, i, t, tl) => { const [ registeredTarget ] = registerTargets(target); const total = isUnd(customTotal) ? t : customTotal; const customIndex = !isUnd(useProp) ? isFnc(useProp) ? useProp(registeredTarget, i, total) : getOriginalAnimatableValue(registeredTarget, useProp) : false; const staggerIndex = isNum(customIndex) || isStr(customIndex) && isNum(+customIndex) ? +customIndex : i; if (fromCenter) fromIndex = (total - 1) / 2; if (fromLast) fromIndex = total - 1; if (!values.length) { for (let index = 0; index < total; index++) { if (!grid) { values.push(abs(fromIndex - index)); } else { const fromX = !fromCenter ? fromIndex % grid[0] : (grid[0] - 1) / 2; const fromY = !fromCenter ? floor(fromIndex / grid[0]) : (grid[1] - 1) / 2; const toX = index % grid[0]; const toY = floor(index / grid[0]); const distanceX = fromX - toX; const distanceY = fromY - toY; let value = sqrt(distanceX * distanceX + distanceY * distanceY); if (axis === 'x') value = -distanceX; if (axis === 'y') value = -distanceY; values.push(value); } maxValue = max(...values); } if (staggerEase) values = values.map(val => staggerEase(val / maxValue) * maxValue); if (reversed) values = values.map(val => axis ? (val < 0) ? val * -1 : -val : abs(maxValue - val)); if (fromRandom) values = shuffle(values); } const spacing = isRange ? (val2 - val1) / maxValue : val1; const offset = tl ? parseTimelinePosition(tl, isUnd(params.start) ? tl.iterationDuration : start) : /** @type {Number} */(start); /** @type {String|Number} */ let output = offset + ((spacing * round(values[staggerIndex], 2)) || 0); if (params.modifier) output = params.modifier(output); if (unitMatch) output = `${output}${unitMatch[2]}`; return output; } }
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/src/utils/number.js
src/utils/number.js
import { lerp, } from '../core/helpers.js'; export { snap, clamp, round, lerp, } from '../core/helpers.js'; /** * Rounds a number to fixed decimal places * @param {Number|String} v - Value to round * @param {Number} decimalLength - Number of decimal places * @return {String} */ export const roundPad = (v, decimalLength) => (+v).toFixed(decimalLength); /** * Pads the start of a value with a string * @param {Number} v - Value to pad * @param {Number} totalLength - Target length * @param {String} padString - String to pad with * @return {String} */ export const padStart = (v, totalLength, padString) => `${v}`.padStart(totalLength, padString); /** * Pads the end of a value with a string * @param {Number} v - Value to pad * @param {Number} totalLength - Target length * @param {String} padString - String to pad with * @return {String} */ export const padEnd = (v, totalLength, padString) => `${v}`.padEnd(totalLength, padString); /** * Wraps a value within a range * @param {Number} v - Value to wrap * @param {Number} min - Minimum boundary * @param {Number} max - Maximum boundary * @return {Number} */ export const wrap = (v, min, max) => (((v - min) % (max - min) + (max - min)) % (max - min)) + min; /** * Maps a value from one range to another * @param {Number} value - Input value * @param {Number} inLow - Input range minimum * @param {Number} inHigh - Input range maximum * @param {Number} outLow - Output range minimum * @param {Number} outHigh - Output range maximum * @return {Number} */ export const mapRange = (value, inLow, inHigh, outLow, outHigh) => outLow + ((value - inLow) / (inHigh - inLow)) * (outHigh - outLow); /** * Converts degrees to radians * @param {Number} degrees - Angle in degrees * @return {Number} */ export const degToRad = degrees => degrees * Math.PI / 180; /** * Converts radians to degrees * @param {Number} radians - Angle in radians * @return {Number} */ export const radToDeg = radians => radians * 180 / Math.PI; /** * Frame rate independent damped lerp * Based on: https://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/ * * @param {Number} start - Starting value * @param {Number} end - Target value * @param {Number} deltaTime - Delta time in ms * @param {Number} factor - Interpolation factor in the range [0, 1] * @return {Number} The interpolated value */ export const damp = (start, end, deltaTime, factor) => { return !factor ? start : factor === 1 ? end : lerp(start, end, 1 - Math.exp(-factor * deltaTime * .1)); }
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/src/utils/random.js
src/utils/random.js
/** * Generate a random number between optional min and max (inclusive) and decimal precision * * @callback RandomNumberGenerator * @param {Number} [min=0] - The minimum value (inclusive) * @param {Number} [max=1] - The maximum value (inclusive) * @param {Number} [decimalLength=0] - Number of decimal places to round to * @return {Number} A random number between min and max */ /** * Generates a random number between min and max (inclusive) with optional decimal precision * * @type {RandomNumberGenerator} */ export const random = (min = 0, max = 1, decimalLength = 0) => { const m = 10 ** decimalLength; return Math.floor((Math.random() * (max - min + (1 / m)) + min) * m) / m; } let _seed = 0; /** * Creates a seeded pseudorandom number generator function * * @param {Number} [seed] - The seed value for the random number generator * @param {Number} [seededMin=0] - The minimum default value (inclusive) of the returned function * @param {Number} [seededMax=1] - The maximum default value (inclusive) of the returned function * @param {Number} [seededDecimalLength=0] - Default number of decimal places to round to of the returned function * @return {RandomNumberGenerator} A function to generate a random number between optional min and max (inclusive) and decimal precision */ export const createSeededRandom = (seed, seededMin = 0, seededMax = 1, seededDecimalLength = 0) => { let t = seed === undefined ? _seed++ : seed; return (min = seededMin, max = seededMax, decimalLength = seededDecimalLength) => { t += 0x6D2B79F5; t = Math.imul(t ^ t >>> 15, t | 1); t ^= t + Math.imul(t ^ t >>> 7, t | 61); const m = 10 ** decimalLength; return Math.floor(((((t ^ t >>> 14) >>> 0) / 4294967296) * (max - min + (1 / m)) + min) * m) / m; } } /** * Picks a random element from an array or a string * * @template T * @param {String|Array<T>} items - The array or string to pick from * @return {String|T} A random element from the array or character from the string */ export const randomPick = items => items[random(0, items.length - 1)]; /** * Shuffles an array in-place using the Fisher-Yates algorithm * Adapted from https://bost.ocks.org/mike/shuffle/ * * @param {Array} items - The array to shuffle (will be modified in-place) * @return {Array} The same array reference, now shuffled */ export const shuffle = items => { let m = items.length, t, i; while (m) { i = random(0, --m); t = items[m]; items[m] = items[i]; items[i] = t; } return items; }
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/src/utils/chainable.js
src/utils/chainable.js
import { noop, } from '../core/consts.js'; import * as numberImports from './number.js'; // Chain-able utilities const numberUtils = numberImports; // Needed to keep the import when bundling const chainables = {}; /** * @callback UtilityFunction * @param {...*} args * @return {Number|String} * * @param {UtilityFunction} fn * @param {Number} [last=0] * @return {function(...(Number|String)): function(Number|String): (Number|String)} */ const curry = (fn, last = 0) => (...args) => last ? v => fn(...args, v) : v => fn(v, ...args); /** * @param {Function} fn * @return {function(...(Number|String))} */ const chain = fn => { return (...args) => { const result = fn(...args); return new Proxy(noop, { apply: (_, __, [v]) => result(v), get: (_, prop) => chain(/**@param {...Number|String} nextArgs */(...nextArgs) => { const nextResult = chainables[prop](...nextArgs); return (/**@type {Number|String} */v) => nextResult(result(v)); }) }); } } /** * @param {UtilityFunction} fn * @param {String} name * @param {Number} [right] * @return {function(...(Number|String)): UtilityFunction} */ const makeChainable = (name, fn, right = 0) => { const chained = (...args) => (args.length < fn.length ? chain(curry(fn, right)) : fn)(...args); if (!chainables[name]) chainables[name] = chained; return chained; } /** * @typedef {Object} ChainablesMap * @property {ChainedClamp} clamp * @property {ChainedRound} round * @property {ChainedSnap} snap * @property {ChainedWrap} wrap * @property {ChainedLerp} lerp * @property {ChainedDamp} damp * @property {ChainedMapRange} mapRange * @property {ChainedRoundPad} roundPad * @property {ChainedPadStart} padStart * @property {ChainedPadEnd} padEnd * @property {ChainedDegToRad} degToRad * @property {ChainedRadToDeg} radToDeg */ /** * @callback ChainedUtilsResult * @param {Number} value - The value to process through the chained operations * @return {Number} The processed result */ /** * @typedef {ChainablesMap & ChainedUtilsResult} ChainableUtil */ // Chainable /** * @callback ChainedRoundPad * @param {Number} decimalLength - Number of decimal places * @return {ChainableUtil} */ export const roundPad = /** @type {typeof numberUtils.roundPad & ChainedRoundPad} */(makeChainable('roundPad', numberUtils.roundPad)); /** * @callback ChainedPadStart * @param {Number} totalLength - Target length * @param {String} padString - String to pad with * @return {ChainableUtil} */ export const padStart = /** @type {typeof numberUtils.padStart & ChainedPadStart} */(makeChainable('padStart', numberUtils.padStart)); /** * @callback ChainedPadEnd * @param {Number} totalLength - Target length * @param {String} padString - String to pad with * @return {ChainableUtil} */ export const padEnd = /** @type {typeof numberUtils.padEnd & ChainedPadEnd} */(makeChainable('padEnd', numberUtils.padEnd)); /** * @callback ChainedWrap * @param {Number} min - Minimum boundary * @param {Number} max - Maximum boundary * @return {ChainableUtil} */ export const wrap = /** @type {typeof numberUtils.wrap & ChainedWrap} */(makeChainable('wrap', numberUtils.wrap)); /** * @callback ChainedMapRange * @param {Number} inLow - Input range minimum * @param {Number} inHigh - Input range maximum * @param {Number} outLow - Output range minimum * @param {Number} outHigh - Output range maximum * @return {ChainableUtil} */ export const mapRange = /** @type {typeof numberUtils.mapRange & ChainedMapRange} */(makeChainable('mapRange', numberUtils.mapRange)); /** * @callback ChainedDegToRad * @return {ChainableUtil} */ export const degToRad = /** @type {typeof numberUtils.degToRad & ChainedDegToRad} */(makeChainable('degToRad', numberUtils.degToRad)); /** * @callback ChainedRadToDeg * @return {ChainableUtil} */ export const radToDeg = /** @type {typeof numberUtils.radToDeg & ChainedRadToDeg} */(makeChainable('radToDeg', numberUtils.radToDeg)); /** * @callback ChainedSnap * @param {Number|Array<Number>} increment - Step size or array of snap points * @return {ChainableUtil} */ export const snap = /** @type {typeof numberUtils.snap & ChainedSnap} */(makeChainable('snap', numberUtils.snap)); /** * @callback ChainedClamp * @param {Number} min - Minimum boundary * @param {Number} max - Maximum boundary * @return {ChainableUtil} */ export const clamp = /** @type {typeof numberUtils.clamp & ChainedClamp} */(makeChainable('clamp', numberUtils.clamp)); /** * @callback ChainedRound * @param {Number} decimalLength - Number of decimal places * @return {ChainableUtil} */ export const round = /** @type {typeof numberUtils.round & ChainedRound} */(makeChainable('round', numberUtils.round)); /** * @callback ChainedLerp * @param {Number} start - Starting value * @param {Number} end - Ending value * @return {ChainableUtil} */ export const lerp = /** @type {typeof numberUtils.lerp & ChainedLerp} */(makeChainable('lerp', numberUtils.lerp, 1)); /** * @callback ChainedDamp * @param {Number} start - Starting value * @param {Number} end - Target value * @param {Number} deltaTime - Delta time in ms * @return {ChainableUtil} */ export const damp = /** @type {typeof numberUtils.damp & ChainedDamp} */(makeChainable('damp', numberUtils.damp, 1));
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/src/types/index.js
src/types/index.js
// Needed to transform this file into a valid ESM module export {} // Private types /** * @import { ScrollObserver } from '../events/scroll.js'; * @import { JSAnimation } from '../animation/animation.js'; * @import { Animatable } from '../animatable/animatable.js'; * @import { Timeline } from '../timeline/timeline.js'; * @import { Timer } from '../timer/timer.js'; * @import { WAAPIAnimation } from '../waapi/waapi.js'; * @import { Draggable } from '../draggable/draggable.js'; * @import { TextSplitter } from '../text/split.js'; * @import { Scope } from '../scope/scope.js'; * @import { Spring } from '../easings/spring/index.js'; * @import { compositionTypes, tweenTypes, valueTypes } from '../core/consts.js'; */ // Exported types // Global types /** * @typedef {Object} DefaultsParams * @property {Number|String} [id] * @property {PercentageKeyframes|DurationKeyframes} [keyframes] * @property {EasingParam} [playbackEase] * @property {Number} [playbackRate] * @property {Number} [frameRate] * @property {Number|Boolean} [loop] * @property {Boolean} [reversed] * @property {Boolean} [alternate] * @property {Boolean} [persist] * @property {Boolean|ScrollObserver} [autoplay] * @property {Number|FunctionValue} [duration] * @property {Number|FunctionValue} [delay] * @property {Number} [loopDelay] * @property {EasingParam} [ease] * @property {'none'|'replace'|'blend'|compositionTypes} [composition] * @property {(v: any) => any} [modifier] * @property {Callback<Tickable>} [onBegin] * @property {Callback<Tickable>} [onBeforeUpdate] * @property {Callback<Tickable>} [onUpdate] * @property {Callback<Tickable>} [onLoop] * @property {Callback<Tickable>} [onPause] * @property {Callback<Tickable>} [onComplete] * @property {Callback<Renderable>} [onRender] */ /** @typedef {JSAnimation|Timeline} Renderable */ /** @typedef {Timer|Renderable} Tickable */ /** @typedef {Timer&JSAnimation&Timeline} CallbackArgument */ /** @typedef {Animatable|Tickable|WAAPIAnimation|Draggable|ScrollObserver|TextSplitter|Scope} Revertible */ // Stagger types /** * @template T * @callback StaggerFunction * @param {Target} [target] * @param {Number} [index] * @param {Number} [length] * @param {Timeline} [tl] * @return {T} */ /** * @typedef {Object} StaggerParams * @property {Number|String} [start] * @property {Number|'first'|'center'|'last'|'random'} [from] * @property {Boolean} [reversed] * @property {Array.<Number>} [grid] * @property {('x'|'y')} [axis] * @property {String|((target: Target, i: Number, length: Number) => Number)} [use] * @property {Number} [total] * @property {EasingParam} [ease] * @property {TweenModifier} [modifier] */ // Targets types /** @typedef {HTMLElement|SVGElement} DOMTarget */ /** @typedef {Record<String, any>} JSTarget */ /** @typedef {DOMTarget|JSTarget} Target */ /** @typedef {Target|NodeList|String} TargetSelector */ /** @typedef {DOMTarget|NodeList|String} DOMTargetSelector */ /** @typedef {Array.<DOMTargetSelector>|DOMTargetSelector} DOMTargetsParam */ /** @typedef {Array.<DOMTarget>} DOMTargetsArray */ /** @typedef {Array.<JSTarget>|JSTarget} JSTargetsParam */ /** @typedef {Array.<JSTarget>} JSTargetsArray */ /** @typedef {Array.<TargetSelector>|TargetSelector} TargetsParam */ /** @typedef {Array.<Target>} TargetsArray */ // Eases types /** * @callback EasingFunction * @param {Number} time * @return {Number} */ /** * @typedef {('linear'|'none'|'in'|'out'|'inOut'|'inQuad'|'outQuad'|'inOutQuad'|'inCubic'|'outCubic'|'inOutCubic'|'inQuart'|'outQuart'|'inOutQuart'|'inQuint'|'outQuint'|'inOutQuint'|'inSine'|'outSine'|'inOutSine'|'inCirc'|'outCirc'|'inOutCirc'|'inExpo'|'outExpo'|'inOutExpo'|'inBounce'|'outBounce'|'inOutBounce'|'inBack'|'outBack'|'inOutBack'|'inElastic'|'outElastic'|'inOutElastic'|'out(p = 1.675)'|'inOut(p = 1.675)'|'inBack(overshoot = 1.7)'|'outBack(overshoot = 1.7)'|'inOutBack(overshoot = 1.7)'|'inElastic(amplitude = 1, period = .3)'|'outElastic(amplitude = 1, period = .3)'|'inOutElastic(amplitude = 1, period = .3)')} EaseStringParamNames */ /** * @typedef {('ease'|'ease-in'|'ease-out'|'ease-in-out'|'linear(0, 0.25, 1)'|'steps'|'steps(6, start)'|'step-start'|'step-end'|'cubic-bezier(0.42, 0, 1, 1)') } WAAPIEaseStringParamNames */ /** * @callback PowerEasing * @param {Number|String} [power=1.675] * @return {EasingFunction} */ /** * @callback BackEasing * @param {Number|String} [overshoot=1.7] * @return {EasingFunction} */ /** * @callback ElasticEasing * @param {Number|String} [amplitude=1] * @param {Number|String} [period=.3] * @return {EasingFunction} */ /** @typedef {PowerEasing|BackEasing|ElasticEasing} EasingFunctionWithParams */ // A hack to get both ease names suggestions AND allow any strings // https://github.com/microsoft/TypeScript/issues/29729#issuecomment-460346421 /** @typedef {(String & {})|EaseStringParamNames|EasingFunction|Spring} EasingParam */ /** @typedef {(String & {})|EaseStringParamNames|WAAPIEaseStringParamNames|EasingFunction|Spring} WAAPIEasingParam */ // Spring types /** * @typedef {Object} SpringParams * @property {Number} [mass=1] - Mass, default 1 * @property {Number} [stiffness=100] - Stiffness, default 100 * @property {Number} [damping=10] - Damping, default 10 * @property {Number} [velocity=0] - Initial velocity, default 0 * @property {Number} [bounce=0] - Initial bounce, default 0 * @property {Number} [duration=0] - The perceived duration, default 0 * @property {Callback<JSAnimation>} [onComplete] - Callback function called when the spring currentTime hits the perceived duration */ // Callback types /** * @template T * @callback Callback * @param {T} self - Returns itself * @param {PointerEvent} [e] * @return {*} */ /** * @template {object} T * @typedef {Object} TickableCallbacks * @property {Callback<T>} [onBegin] * @property {Callback<T>} [onBeforeUpdate] * @property {Callback<T>} [onUpdate] * @property {Callback<T>} [onLoop] * @property {Callback<T>} [onPause] * @property {Callback<T>} [onComplete] */ /** * @template {object} T * @typedef {Object} RenderableCallbacks * @property {Callback<T>} [onRender] */ // Timer types /** * @typedef {Object} TimerOptions * @property {Number|String} [id] * @property {TweenParamValue} [duration] * @property {TweenParamValue} [delay] * @property {Number} [loopDelay] * @property {Boolean} [reversed] * @property {Boolean} [alternate] * @property {Boolean|Number} [loop] * @property {Boolean|ScrollObserver} [autoplay] * @property {Number} [frameRate] * @property {Number} [playbackRate] */ /** * @typedef {TimerOptions & TickableCallbacks<Timer>} TimerParams */ // Tween types /** * @callback FunctionValue * @param {Target} target - The animated target * @param {Number} index - The target index * @param {Number} length - The total number of animated targets * @return {Number|String|TweenObjectValue|Array.<Number|String|TweenObjectValue>} */ /** * @callback TweenModifier * @param {Number} value - The animated value * @return {Number|String} */ /** @typedef {[Number, Number, Number, Number]} ColorArray */ /** * @typedef {Object} Tween * @property {Number} id * @property {JSAnimation} parent * @property {String} property * @property {Target} target * @property {String|Number} _value * @property {Function|null} _func * @property {EasingFunction} _ease * @property {Array.<Number>} _fromNumbers * @property {Array.<Number>} _toNumbers * @property {Array.<String>} _strings * @property {Number} _fromNumber * @property {Number} _toNumber * @property {Array.<Number>} _numbers * @property {Number} _number * @property {String} _unit * @property {TweenModifier} _modifier * @property {Number} _currentTime * @property {Number} _delay * @property {Number} _updateDuration * @property {Number} _startTime * @property {Number} _changeDuration * @property {Number} _absoluteStartTime * @property {tweenTypes} _tweenType * @property {valueTypes} _valueType * @property {Number} _composition * @property {Number} _isOverlapped * @property {Number} _isOverridden * @property {Number} _renderTransforms * @property {String} _inlineValue * @property {Tween} _prevRep * @property {Tween} _nextRep * @property {Tween} _prevAdd * @property {Tween} _nextAdd * @property {Tween} _prev * @property {Tween} _next */ /** * @typedef TweenDecomposedValue * @property {Number} t - Type * @property {Number} n - Single number value * @property {String} u - Value unit * @property {String} o - Value operator * @property {Array.<Number>} d - Array of Numbers (in case of complex value type) * @property {Array.<String>} s - Strings (in case of complex value type) */ /** @typedef {{_head: null|Tween, _tail: null|Tween}} TweenPropertySiblings */ /** @typedef {Record<String, TweenPropertySiblings>} TweenLookups */ /** @typedef {WeakMap.<Target, TweenLookups>} TweenReplaceLookups */ /** @typedef {Map.<Target, TweenLookups>} TweenAdditiveLookups */ // JSAnimation types /** * @typedef {Number|String|FunctionValue} TweenParamValue */ /** * @typedef {TweenParamValue|[TweenParamValue, TweenParamValue]} TweenPropValue */ /** * @typedef {(String & {})|'none'|'replace'|'blend'|compositionTypes} TweenComposition */ /** * @typedef {Object} TweenParamsOptions * @property {TweenParamValue} [duration] * @property {TweenParamValue} [delay] * @property {EasingParam} [ease] * @property {TweenModifier} [modifier] * @property {TweenComposition} [composition] */ /** * @typedef {Object} TweenValues * @property {TweenParamValue} [from] * @property {TweenPropValue} [to] * @property {TweenPropValue} [fromTo] */ /** * @typedef {TweenParamsOptions & TweenValues} TweenKeyValue */ /** * @typedef {Array.<TweenKeyValue|TweenPropValue>} ArraySyntaxValue */ /** * @typedef {TweenParamValue|ArraySyntaxValue|TweenKeyValue} TweenOptions */ /** * @typedef {Partial<{to: TweenParamValue|Array.<TweenParamValue>; from: TweenParamValue|Array.<TweenParamValue>; fromTo: TweenParamValue|Array.<TweenParamValue>;}>} TweenObjectValue */ /** * @typedef {Object} PercentageKeyframeOptions * @property {EasingParam} [ease] */ /** * @typedef {Record<String, TweenParamValue>} PercentageKeyframeParams */ /** * @typedef {Record<String, PercentageKeyframeParams & PercentageKeyframeOptions>} PercentageKeyframes */ /** * @typedef {Array<Record<String, TweenOptions | TweenModifier | boolean> & TweenParamsOptions>} DurationKeyframes */ /** * @typedef {Object} AnimationOptions * @property {PercentageKeyframes|DurationKeyframes} [keyframes] * @property {EasingParam} [playbackEase] */ // TODO: Currently setting TweenModifier to the intersected Record<> makes the FunctionValue type target param any if only one parameter is set /** * @typedef {Record<String, TweenOptions | Callback<JSAnimation> | TweenModifier | boolean | PercentageKeyframes | DurationKeyframes | ScrollObserver> & TimerOptions & AnimationOptions & TweenParamsOptions & TickableCallbacks<JSAnimation> & RenderableCallbacks<JSAnimation>} AnimationParams */ // Timeline types /** * Accepts:<br> * - `Number` - Absolute position in milliseconds (e.g., `500` places element at exactly 500ms)<br> * - `'+=Number'` - Addition: Position element X ms after the last element (e.g., `'+=100'`)<br> * - `'-=Number'` - Subtraction: Position element X ms before the last element's end (e.g., `'-=100'`)<br> * - `'*=Number'` - Multiplier: Position element at a fraction of the total duration (e.g., `'*=.5'` for halfway)<br> * - `'<'` - Previous end: Position element at the end position of the previous element<br> * - `'<<'` - Previous start: Position element at the start position of the previous element<br> * - `'<<+=Number'` - Combined: Position element relative to previous element's start (e.g., `'<<+=250'`)<br> * - `'label'` - Label: Position element at a named label position (e.g., `'My Label'`) * * @typedef {Number|`+=${Number}`|`-=${Number}`|`*=${Number}`|'<'|'<<'|`<<+=${Number}`|`<<-=${Number}`|String} TimelinePosition */ /** * Accepts:<br> * - `Number` - Absolute position in milliseconds (e.g., `500` places animation at exactly 500ms)<br> * - `'+=Number'` - Addition: Position animation X ms after the last animation (e.g., `'+=100'`)<br> * - `'-=Number'` - Subtraction: Position animation X ms before the last animation's end (e.g., `'-=100'`)<br> * - `'*=Number'` - Multiplier: Position animation at a fraction of the total duration (e.g., `'*=.5'` for halfway)<br> * - `'<'` - Previous end: Position animation at the end position of the previous animation<br> * - `'<<'` - Previous start: Position animation at the start position of the previous animation<br> * - `'<<+=Number'` - Combined: Position animation relative to previous animation's start (e.g., `'<<+=250'`)<br> * - `'label'` - Label: Position animation at a named label position (e.g., `'My Label'`)<br> * - `stagger(String|Nummber)` - Stagger multi-elements animation positions (e.g., 10, 20, 30...) * * @typedef {TimelinePosition | StaggerFunction<Number|String>} TimelineAnimationPosition */ /** * @typedef {Object} TimelineOptions * @property {DefaultsParams} [defaults] * @property {EasingParam} [playbackEase] */ /** * @typedef {TimerOptions & TimelineOptions & TickableCallbacks<Timeline> & RenderableCallbacks<Timeline>} TimelineParams */ // WAAPIAnimation types /** * @typedef {String|Number|Array<String>|Array<Number>} WAAPITweenValue */ /** * @callback WAAPIFunctionValue * @param {DOMTarget} target - The animated target * @param {Number} index - The target index * @param {Number} length - The total number of animated targets * @return {WAAPITweenValue} */ /** * @typedef {WAAPITweenValue|WAAPIFunctionValue|Array<String|Number|WAAPIFunctionValue>} WAAPIKeyframeValue */ /** * @typedef {Object} WAAPITweenOptions * @property {WAAPIKeyframeValue} [to] * @property {WAAPIKeyframeValue} [from] * @property {Number|WAAPIFunctionValue} [duration] * @property {Number|WAAPIFunctionValue} [delay] * @property {WAAPIEasingParam} [ease] * @property {CompositeOperation} [composition] */ /** * @typedef {Object} WAAPIAnimationOptions * @property {Number|Boolean} [loop] * @property {Boolean} [Reversed] * @property {Boolean} [Alternate] * @property {Boolean|ScrollObserver} [autoplay] * @property {Number} [playbackRate] * @property {Number|WAAPIFunctionValue} [duration] * @property {Number|WAAPIFunctionValue} [delay] * @property {WAAPIEasingParam} [ease] * @property {CompositeOperation} [composition] * @property {Boolean} [persist] * @property {Callback<WAAPIAnimation>} [onComplete] */ /** * @typedef {Record<String, WAAPIKeyframeValue | WAAPIAnimationOptions | Boolean | ScrollObserver | Callback<WAAPIAnimation> | WAAPIEasingParam | WAAPITweenOptions> & WAAPIAnimationOptions} WAAPIAnimationParams */ // Animatable types /** * @callback AnimatablePropertySetter * @param {Number|Array.<Number>} to * @param {Number} [duration] * @param {EasingParam} [ease] * @return {AnimatableObject} */ /** * @callback AnimatablePropertyGetter * @return {Number|Array.<Number>} */ /** * @typedef {AnimatablePropertySetter & AnimatablePropertyGetter} AnimatableProperty */ /** * @typedef {Animatable & Record<String, AnimatableProperty>} AnimatableObject */ /** * @typedef {Object} AnimatablePropertyParamsOptions * @property {String} [unit] * @property {TweenParamValue} [duration] * @property {EasingParam} [ease] * @property {TweenModifier} [modifier] * @property {TweenComposition} [composition] */ /** * @typedef {Record<String, TweenParamValue | EasingParam | TweenModifier | TweenComposition | AnimatablePropertyParamsOptions> & AnimatablePropertyParamsOptions} AnimatableParams */ // Scope types /** * @typedef {Object} ReactRef * @property {HTMLElement|SVGElement|null} [current] */ /** * @typedef {Object} AngularRef * @property {HTMLElement|SVGElement} [nativeElement] */ /** * @typedef {Object} ScopeParams * @property {DOMTargetSelector|ReactRef|AngularRef} [root] * @property {DefaultsParams} [defaults] * @property {Record<String, String>} [mediaQueries] */ /** * @template T * @callback ScopedCallback * @param {Scope} scope * @return {T} */ /** * @callback ScopeCleanupCallback * @param {Scope} [scope] */ /** * @callback ScopeConstructorCallback * @param {Scope} [scope] * @return {ScopeCleanupCallback|void} */ /** * @callback ScopeMethod * @param {...*} args * @return {ScopeCleanupCallback|void} */ // Scroll types /** * @typedef {String|Number} ScrollThresholdValue */ /** * @typedef {Object} ScrollThresholdParam * @property {ScrollThresholdValue} [target] * @property {ScrollThresholdValue} [container] */ /** * @callback ScrollObserverAxisCallback * @param {ScrollObserver} self * @return {'x'|'y'} */ /** * @callback ScrollThresholdCallback * @param {ScrollObserver} self * @return {ScrollThresholdValue|ScrollThresholdParam} */ /** * @typedef {Object} ScrollObserverParams * @property {Number|String} [id] * @property {Boolean|Number|String|EasingParam} [sync] * @property {TargetsParam} [container] * @property {TargetsParam} [target] * @property {'x'|'y'|ScrollObserverAxisCallback|((observer: ScrollObserver) => 'x'|'y'|ScrollObserverAxisCallback)} [axis] * @property {ScrollThresholdValue|ScrollThresholdParam|ScrollThresholdCallback|((observer: ScrollObserver) => ScrollThresholdValue|ScrollThresholdParam|ScrollThresholdCallback)} [enter] * @property {ScrollThresholdValue|ScrollThresholdParam|ScrollThresholdCallback|((observer: ScrollObserver) => ScrollThresholdValue|ScrollThresholdParam|ScrollThresholdCallback)} [leave] * @property {Boolean|((observer: ScrollObserver) => Boolean)} [repeat] * @property {Boolean} [debug] * @property {Callback<ScrollObserver>} [onEnter] * @property {Callback<ScrollObserver>} [onLeave] * @property {Callback<ScrollObserver>} [onEnterForward] * @property {Callback<ScrollObserver>} [onLeaveForward] * @property {Callback<ScrollObserver>} [onEnterBackward] * @property {Callback<ScrollObserver>} [onLeaveBackward] * @property {Callback<ScrollObserver>} [onUpdate] * @property {Callback<ScrollObserver>} [onSyncComplete] */ // Draggable types /** * @typedef {Object} DraggableAxisParam * @property {String} [mapTo] * @property {TweenModifier} [modifier] * @property {TweenComposition} [composition] * @property {Number|Array<Number>|((draggable: Draggable) => Number|Array<Number>)} [snap] */ /** * @typedef {Object} DraggableCursorParams * @property {String} [onHover] * @property {String} [onGrab] */ /** * @typedef {Object} DraggableDragThresholdParams * @property {Number} [mouse] * @property {Number} [touch] */ /** * @typedef {Object} DraggableParams * @property {DOMTargetSelector} [trigger] * @property {DOMTargetSelector|Array<Number>|((draggable: Draggable) => DOMTargetSelector|Array<Number>)} [container] * @property {Boolean|DraggableAxisParam} [x] * @property {Boolean|DraggableAxisParam} [y] * @property {TweenModifier} [modifier] * @property {Number|Array<Number>|((draggable: Draggable) => Number|Array<Number>)} [snap] * @property {Number|Array<Number>|((draggable: Draggable) => Number|Array<Number>)} [containerPadding] * @property {Number|((draggable: Draggable) => Number)} [containerFriction] * @property {Number|((draggable: Draggable) => Number)} [releaseContainerFriction] * @property {Number|((draggable: Draggable) => Number)} [dragSpeed] * @property {Number|DraggableDragThresholdParams|((draggable: Draggable) => Number|DraggableDragThresholdParams)} [dragThreshold] * @property {Number|((draggable: Draggable) => Number)} [scrollSpeed] * @property {Number|((draggable: Draggable) => Number)} [scrollThreshold] * @property {Number|((draggable: Draggable) => Number)} [minVelocity] * @property {Number|((draggable: Draggable) => Number)} [maxVelocity] * @property {Number|((draggable: Draggable) => Number)} [velocityMultiplier] * @property {Number} [releaseMass] * @property {Number} [releaseStiffness] * @property {Number} [releaseDamping] * @property {Boolean} [releaseDamping] * @property {EasingParam} [releaseEase] * @property {Boolean|DraggableCursorParams|((draggable: Draggable) => Boolean|DraggableCursorParams)} [cursor] * @property {Callback<Draggable>} [onGrab] * @property {Callback<Draggable>} [onDrag] * @property {Callback<Draggable>} [onRelease] * @property {Callback<Draggable>} [onUpdate] * @property {Callback<Draggable>} [onSettle] * @property {Callback<Draggable>} [onSnap] * @property {Callback<Draggable>} [onResize] * @property {Callback<Draggable>} [onAfterResize] */ // Text types /** * @typedef {Object} SplitTemplateParams * @property {false|String} [class] * @property {Boolean|'hidden'|'clip'|'visible'|'scroll'|'auto'} [wrap] * @property {Boolean|'top'|'right'|'bottom'|'left'|'center'} [clone] */ /** * @typedef {Boolean|String} SplitValue */ /** * @callback SplitFunctionValue * @param {Node|HTMLElement} [value] * @return String */ /** * @typedef {Object} TextSplitterParams * @property {SplitValue|SplitTemplateParams|SplitFunctionValue} [lines] * @property {SplitValue|SplitTemplateParams|SplitFunctionValue} [words] * @property {SplitValue|SplitTemplateParams|SplitFunctionValue} [chars] * @property {Boolean} [accessible] * @property {Boolean} [includeSpaces] * @property {Boolean} [debug] */ // SVG types /** * @typedef {SVGGeometryElement & { * setAttribute(name: 'draw', value: `${number} ${number}`): void; * draw: `${number} ${number}`; * }} DrawableSVGGeometry */
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/src/timer/index.js
src/timer/index.js
export * from './timer.js';
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/src/timer/timer.js
src/timer/timer.js
import { minValue, compositionTypes, tickModes, noop, maxValue, } from '../core/consts.js'; import { now, isUnd, addChild, forEachChildren, clampInfinity, round, normalizeTime, isFnc, clamp, floor, } from '../core/helpers.js'; import { scope, globals, } from '../core/globals.js'; import { setValue, } from '../core/values.js'; import { tick, } from '../core/render.js'; import { composeTween, getTweenSiblings, removeTweenSliblings, } from '../animation/composition.js'; import { Clock, } from '../core/clock.js'; import { engine, } from '../engine/engine.js'; /** * @import { * Callback, * TimerParams, * Renderable, * Tween, * } from '../types/index.js' */ /** * @import { * ScrollObserver, * } from '../events/scroll.js' */ /** * @import { * Timeline, * } from '../timeline/timeline.js' */ /** * @param {Timer} timer * @return {Timer} */ const resetTimerProperties = timer => { timer.paused = true; timer.began = false; timer.completed = false; return timer; } /** * @param {Timer} timer * @return {Timer} */ const reviveTimer = timer => { if (!timer._cancelled) return timer; if (timer._hasChildren) { forEachChildren(timer, reviveTimer); } else { forEachChildren(timer, (/** @type {Tween} tween */tween) => { if (tween._composition !== compositionTypes.none) { composeTween(tween, getTweenSiblings(tween.target, tween.property)); } }); } timer._cancelled = 0; return timer; } let timerId = 0; /** * Base class used to create Timers, Animations and Timelines */ export class Timer extends Clock { /** * @param {TimerParams} [parameters] * @param {Timeline} [parent] * @param {Number} [parentPosition] */ constructor(parameters = {}, parent = null, parentPosition = 0) { super(0); const { id, delay, duration, reversed, alternate, loop, loopDelay, autoplay, frameRate, playbackRate, onComplete, onLoop, onPause, onBegin, onBeforeUpdate, onUpdate, } = parameters; if (scope.current) scope.current.register(this); const timerInitTime = parent ? 0 : engine._elapsedTime; const timerDefaults = parent ? parent.defaults : globals.defaults; const timerDelay = /** @type {Number} */(isFnc(delay) || isUnd(delay) ? timerDefaults.delay : +delay); const timerDuration = isFnc(duration) || isUnd(duration) ? Infinity : +duration; const timerLoop = setValue(loop, timerDefaults.loop); const timerLoopDelay = setValue(loopDelay, timerDefaults.loopDelay); const timerIterationCount = timerLoop === true || timerLoop === Infinity || /** @type {Number} */(timerLoop) < 0 ? Infinity : /** @type {Number} */(timerLoop) + 1; let offsetPosition = 0; if (parent) { offsetPosition = parentPosition; } else { // Make sure to tick the engine once if not currently running to get up to date engine._elapsedTime // to avoid big gaps with the following offsetPosition calculation if (!engine.reqId) engine.requestTick(now()); // Make sure to scale the offset position with globals.timeScale to properly handle seconds unit offsetPosition = (engine._elapsedTime - engine._startTime) * globals.timeScale; } // Timer's parameters this.id = !isUnd(id) ? id : ++timerId; /** @type {Timeline} */ this.parent = parent; // Total duration of the timer this.duration = clampInfinity(((timerDuration + timerLoopDelay) * timerIterationCount) - timerLoopDelay) || minValue; /** @type {Boolean} */ this.backwards = false; /** @type {Boolean} */ this.paused = true; /** @type {Boolean} */ this.began = false; /** @type {Boolean} */ this.completed = false; /** @type {Callback<this>} */ this.onBegin = onBegin || timerDefaults.onBegin; /** @type {Callback<this>} */ this.onBeforeUpdate = onBeforeUpdate || timerDefaults.onBeforeUpdate; /** @type {Callback<this>} */ this.onUpdate = onUpdate || timerDefaults.onUpdate; /** @type {Callback<this>} */ this.onLoop = onLoop || timerDefaults.onLoop; /** @type {Callback<this>} */ this.onPause = onPause || timerDefaults.onPause; /** @type {Callback<this>} */ this.onComplete = onComplete || timerDefaults.onComplete; /** @type {Number} */ this.iterationDuration = timerDuration; // Duration of one loop /** @type {Number} */ this.iterationCount = timerIterationCount; // Number of loops /** @type {Boolean|ScrollObserver} */ this._autoplay = parent ? false : setValue(autoplay, timerDefaults.autoplay); /** @type {Number} */ this._offset = offsetPosition; /** @type {Number} */ this._delay = timerDelay; /** @type {Number} */ this._loopDelay = timerLoopDelay; /** @type {Number} */ this._iterationTime = 0; /** @type {Number} */ this._currentIteration = 0; // Current loop index /** @type {Function} */ this._resolve = noop; // Used by .then() /** @type {Boolean} */ this._running = false; /** @type {Number} */ this._reversed = +setValue(reversed, timerDefaults.reversed); /** @type {Number} */ this._reverse = this._reversed; /** @type {Number} */ this._cancelled = 0; /** @type {Boolean} */ this._alternate = setValue(alternate, timerDefaults.alternate); /** @type {Renderable} */ this._prev = null; /** @type {Renderable} */ this._next = null; // Clock's parameters /** @type {Number} */ this._elapsedTime = timerInitTime; /** @type {Number} */ this._startTime = timerInitTime; /** @type {Number} */ this._lastTime = timerInitTime; /** @type {Number} */ this._fps = setValue(frameRate, timerDefaults.frameRate); /** @type {Number} */ this._speed = setValue(playbackRate, timerDefaults.playbackRate); } get cancelled() { return !!this._cancelled; } set cancelled(cancelled) { cancelled ? this.cancel() : this.reset(true).play(); } get currentTime() { return clamp(round(this._currentTime, globals.precision), -this._delay, this.duration); } set currentTime(time) { const paused = this.paused; // Pausing the timer is necessary to avoid time jumps on a running instance this.pause().seek(+time); if (!paused) this.resume(); } get iterationCurrentTime() { return round(this._iterationTime, globals.precision); } set iterationCurrentTime(time) { this.currentTime = (this.iterationDuration * this._currentIteration) + time; } get progress() { return clamp(round(this._currentTime / this.duration, 10), 0, 1); } set progress(progress) { this.currentTime = this.duration * progress; } get iterationProgress() { return clamp(round(this._iterationTime / this.iterationDuration, 10), 0, 1); } set iterationProgress(progress) { const iterationDuration = this.iterationDuration; this.currentTime = (iterationDuration * this._currentIteration) + (iterationDuration * progress); } get currentIteration() { return this._currentIteration; } set currentIteration(iterationCount) { this.currentTime = (this.iterationDuration * clamp(+iterationCount, 0, this.iterationCount - 1)); } get reversed() { return !!this._reversed; } set reversed(reverse) { reverse ? this.reverse() : this.play(); } get speed() { return super.speed; } set speed(playbackRate) { super.speed = playbackRate; this.resetTime(); } /** * @param {Boolean} [softReset] * @return {this} */ reset(softReset = false) { // If cancelled, revive the timer before rendering in order to have propertly composed tweens siblings reviveTimer(this); if (this._reversed && !this._reverse) this.reversed = false; // Rendering before updating the completed flag to prevent skips and to make sure the properties are not overridden // Setting the iterationTime at the end to force the rendering to happend backwards, otherwise calling .reset() on Timelines might not render children in the right order // NOTE: This is only required for Timelines and might be better to move to the Timeline class? this._iterationTime = this.iterationDuration; // Set tickMode to tickModes.FORCE to force rendering tick(this, 0, 1, ~~softReset, tickModes.FORCE); // Reset timer properties after revive / render to make sure the props are not updated again resetTimerProperties(this); // Also reset children properties if (this._hasChildren) { forEachChildren(this, resetTimerProperties); } return this; } /** * @param {Boolean} internalRender * @return {this} */ init(internalRender = false) { this.fps = this._fps; this.speed = this._speed; // Manually calling .init() on timelines should render all children intial state // Forces all children to render once then render to 0 when reseted if (!internalRender && this._hasChildren) { tick(this, this.duration, 1, ~~internalRender, tickModes.FORCE); } this.reset(internalRender); // Make sure to set autoplay to false to child timers so it doesn't attempt to autoplay / link const autoplay = this._autoplay; if (autoplay === true) { this.resume(); } else if (autoplay && !isUnd(/** @type {ScrollObserver} */(autoplay).linked)) { /** @type {ScrollObserver} */(autoplay).link(this); } return this; } /** @return {this} */ resetTime() { const timeScale = 1 / (this._speed * engine._speed); // TODO: See if we can safely use engine._elapsedTime here // if (!engine.reqId) engine.requestTick(now()) // this._startTime = engine._elapsedTime - (this._currentTime + this._delay) * timeScale; this._startTime = now() - (this._currentTime + this._delay) * timeScale; return this; } /** @return {this} */ pause() { if (this.paused) return this; this.paused = true; this.onPause(this); return this; } /** @return {this} */ resume() { if (!this.paused) return this; this.paused = false; // We can safely imediatly render a timer that has no duration and no children if (this.duration <= minValue && !this._hasChildren) { tick(this, minValue, 0, 0, tickModes.FORCE); } else { if (!this._running) { addChild(engine, this); engine._hasChildren = true; this._running = true; } this.resetTime(); // Forces the timer to advance by at least one frame when the next tick occurs this._startTime -= 12; engine.wake(); } return this; } /** @return {this} */ restart() { return this.reset().resume(); } /** * @param {Number} time * @param {Boolean|Number} [muteCallbacks] * @param {Boolean|Number} [internalRender] * @return {this} */ seek(time, muteCallbacks = 0, internalRender = 0) { // Recompose the tween siblings in case the timer has been cancelled reviveTimer(this); // If you seek a completed animation, otherwise the next play will starts at 0 this.completed = false; const isPaused = this.paused; this.paused = true; // timer, time, muteCallbacks, internalRender, tickMode tick(this, time + this._delay, ~~muteCallbacks, ~~internalRender, tickModes.AUTO); return isPaused ? this : this.resume(); } /** @return {this} */ alternate() { const reversed = this._reversed; const count = this.iterationCount; const duration = this.iterationDuration; // Calculate the maximum iterations possible given the iteration duration const iterations = count === Infinity ? floor(maxValue / duration) : count; this._reversed = +(this._alternate && !(iterations % 2) ? reversed : !reversed); if (count === Infinity) { // Handle infinite loops to loop on themself this.iterationProgress = this._reversed ? 1 - this.iterationProgress : this.iterationProgress; } else { this.seek((duration * iterations) - this._currentTime); } this.resetTime(); return this; } /** @return {this} */ play() { if (this._reversed) this.alternate(); return this.resume(); } /** @return {this} */ reverse() { if (!this._reversed) this.alternate(); return this.resume(); } // TODO: Move all the animation / tweens / children related code to Animation / Timeline /** @return {this} */ cancel() { if (this._hasChildren) { forEachChildren(this, (/** @type {Renderable} */child) => child.cancel(), true); } else { forEachChildren(this, removeTweenSliblings); } this._cancelled = 1; // Pausing the timer removes it from the engine return this.pause(); } /** * @param {Number} newDuration * @return {this} */ stretch(newDuration) { const currentDuration = this.duration; const normlizedDuration = normalizeTime(newDuration); if (currentDuration === normlizedDuration) return this; const timeScale = newDuration / currentDuration; const isSetter = newDuration <= minValue; this.duration = isSetter ? minValue : normlizedDuration; this.iterationDuration = isSetter ? minValue : normalizeTime(this.iterationDuration * timeScale); this._offset *= timeScale; this._delay *= timeScale; this._loopDelay *= timeScale; return this; } /** * Cancels the timer by seeking it back to 0 and reverting the attached scroller if necessary * @return {this} */ revert() { tick(this, 0, 1, 0, tickModes.AUTO); const ap = /** @type {ScrollObserver} */(this._autoplay); if (ap && ap.linked && ap.linked === this) ap.revert(); return this.cancel(); } /** * Imediatly completes the timer, cancels it and triggers the onComplete callback * @return {this} */ complete() { return this.seek(this.duration).cancel(); } /** * @typedef {this & {then: null}} ResolvedTimer */ /** * @param {Callback<ResolvedTimer>} [callback] * @return Promise<this> */ then(callback = noop) { const then = this.then; const onResolve = () => { // this.then = null prevents infinite recursion if returned by an async function // https://github.com/juliangarnierorg/anime-beta/issues/26 this.then = null; callback(/** @type {ResolvedTimer} */(this)); this.then = then; this._resolve = noop; } return new Promise(r => { this._resolve = () => r(onResolve()); // Make sure to resolve imediatly if the timer has already completed if (this.completed) this._resolve(); return this; }); } } /** * @param {TimerParams} [parameters] * @return {Timer} */ export const createTimer = parameters => new Timer(parameters, null, 0).init();
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/src/events/index.js
src/events/index.js
export * from './scroll.js';
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/src/events/scroll.js
src/events/scroll.js
import { win, doc, noop, isDomSymbol, relativeValuesExecRgx, } from '../core/consts.js'; import { scope, globals, } from '../core/globals.js'; import { addChild, removeChild, forEachChildren, lerp, clamp, round, isFnc, isNum, isObj, isStr, isUnd, } from '../core/helpers.js'; import { parseTargets, } from '../core/targets.js'; import { decomposeRawValue, decomposedOriginalValue, getRelativeValue, setValue, } from '../core/values.js'; import { convertValueUnit, } from '../core/units.js'; import { Timer, } from '../timer/timer.js'; import { get, set, } from '../utils/target.js'; import { sync, } from '../utils/time.js'; import { none, } from '../easings/none.js'; import { parseEase, } from '../easings/eases/parser.js'; /** * @import { * TargetsParam, * EasingFunction, * Callback, * EasingParam, * ScrollThresholdValue, * ScrollObserverParams, * Tickable, * ScrollThresholdParam, * ScrollThresholdCallback, * } from '../types/index.js' */ /** * @import { * JSAnimation, * } from '../animation/animation.js' */ /** * @import { * WAAPIAnimation, * } from '../waapi/waapi.js' */ /** * @import { * Timeline, * } from '../timeline/timeline.js' */ /** * @return {Number} */ const getMaxViewHeight = () => { const $el = doc.createElement('div'); doc.body.appendChild($el); $el.style.height = '100lvh'; const height = $el.offsetHeight; doc.body.removeChild($el); return height; } /** * @template {ScrollThresholdValue|String|Number|Boolean|Function|Object} T * @param {T | ((observer: ScrollObserver) => T)} value * @param {ScrollObserver} scroller * @return {T} */ const parseScrollObserverFunctionParameter = (value, scroller) => value && isFnc(value) ? /** @type {Function} */(value)(scroller) : /** @type {T} */(value); export const scrollContainers = new Map(); class ScrollContainer { /** * @param {HTMLElement} $el */ constructor($el) { /** @type {HTMLElement} */ this.element = $el; /** @type {Boolean} */ this.useWin = this.element === doc.body; /** @type {Number} */ this.winWidth = 0; /** @type {Number} */ this.winHeight = 0; /** @type {Number} */ this.width = 0; /** @type {Number} */ this.height = 0; /** @type {Number} */ this.left = 0; /** @type {Number} */ this.top = 0; /** @type {Number} */ this.scale = 1; /** @type {Number} */ this.zIndex = 0; /** @type {Number} */ this.scrollX = 0; /** @type {Number} */ this.scrollY = 0; /** @type {Number} */ this.prevScrollX = 0; /** @type {Number} */ this.prevScrollY = 0; /** @type {Number} */ this.scrollWidth = 0; /** @type {Number} */ this.scrollHeight = 0; /** @type {Number} */ this.velocity = 0; /** @type {Boolean} */ this.backwardX = false; /** @type {Boolean} */ this.backwardY = false; /** @type {Timer} */ this.scrollTicker = new Timer({ autoplay: false, onBegin: () => this.dataTimer.resume(), onUpdate: () => { const backwards = this.backwardX || this.backwardY; forEachChildren(this, (/** @type {ScrollObserver} */child) => child.handleScroll(), backwards); }, onComplete: () => this.dataTimer.pause() }).init(); /** @type {Timer} */ this.dataTimer = new Timer({ autoplay: false, frameRate: 30, onUpdate: (/** @type {Timer} */self) => { const dt = self.deltaTime; const px = this.prevScrollX; const py = this.prevScrollY; const nx = this.scrollX; const ny = this.scrollY; const dx = px - nx; const dy = py - ny; this.prevScrollX = nx; this.prevScrollY = ny; if (dx) this.backwardX = px > nx; if (dy) this.backwardY = py > ny; this.velocity = round(dt > 0 ? Math.sqrt(dx * dx + dy * dy) / dt : 0, 5); } }).init(); /** @type {Timer} */ this.resizeTicker = new Timer({ autoplay: false, duration: 250 * globals.timeScale, onComplete: () => { this.updateWindowBounds(); this.refreshScrollObservers(); this.handleScroll(); } }).init(); /** @type {Timer} */ this.wakeTicker = new Timer({ autoplay: false, duration: 500 * globals.timeScale, onBegin: () => { this.scrollTicker.resume(); }, onComplete: () => { this.scrollTicker.pause(); } }).init(); /** @type {ScrollObserver} */ this._head = null; /** @type {ScrollObserver} */ this._tail = null; this.updateScrollCoords(); this.updateWindowBounds(); this.updateBounds(); this.refreshScrollObservers(); this.handleScroll(); this.resizeObserver = new ResizeObserver(() => this.resizeTicker.restart()); this.resizeObserver.observe(this.element); (this.useWin ? win : this.element).addEventListener('scroll', this, false); } updateScrollCoords() { const useWin = this.useWin; const $el = this.element; this.scrollX = round(useWin ? win.scrollX : $el.scrollLeft, 0); this.scrollY = round(useWin ? win.scrollY : $el.scrollTop, 0); } updateWindowBounds() { this.winWidth = win.innerWidth; this.winHeight = getMaxViewHeight(); } updateBounds() { const style = getComputedStyle(this.element); const $el = this.element; this.scrollWidth = $el.scrollWidth + parseFloat(style.marginLeft) + parseFloat(style.marginRight); this.scrollHeight = $el.scrollHeight + parseFloat(style.marginTop) + parseFloat(style.marginBottom); this.updateWindowBounds(); let width, height; if (this.useWin) { width = this.winWidth; height = this.winHeight; } else { const elRect = $el.getBoundingClientRect(); width = $el.clientWidth; height = $el.clientHeight; this.top = elRect.top; this.left = elRect.left; this.scale = elRect.width ? width / elRect.width : (elRect.height ? height / elRect.height : 1); } this.width = width; this.height = height; } refreshScrollObservers() { forEachChildren(this, (/** @type {ScrollObserver} */child) => { if (child._debug) { child.removeDebug(); } }); this.updateBounds(); forEachChildren(this, (/** @type {ScrollObserver} */child) => { child.refresh(); if (child._debug) { child.debug(); } }); } refresh() { this.updateWindowBounds(); this.updateBounds(); this.refreshScrollObservers(); this.handleScroll(); } handleScroll() { this.updateScrollCoords(); this.wakeTicker.restart(); } /** * @param {Event} e */ handleEvent(e) { switch (e.type) { case 'scroll': this.handleScroll(); break; } } revert() { this.scrollTicker.cancel(); this.dataTimer.cancel(); this.resizeTicker.cancel(); this.wakeTicker.cancel(); this.resizeObserver.disconnect(); (this.useWin ? win : this.element).removeEventListener('scroll', this); scrollContainers.delete(this.element); } } /** * @param {TargetsParam} target * @return {ScrollContainer} */ const registerAndGetScrollContainer = target => { const $el = /** @type {HTMLElement} */(target ? parseTargets(target)[0] || doc.body : doc.body); let scrollContainer = scrollContainers.get($el); if (!scrollContainer) { scrollContainer = new ScrollContainer($el); scrollContainers.set($el, scrollContainer); } return scrollContainer; } /** * @param {HTMLElement} $el * @param {Number|string} v * @param {Number} size * @param {Number} [under] * @param {Number} [over] * @return {Number} */ const convertValueToPx = ($el, v, size, under, over) => { const clampMin = v === 'min'; const clampMax = v === 'max'; const value = v === 'top' || v === 'left' || v === 'start' || clampMin ? 0 : v === 'bottom' || v === 'right' || v === 'end' || clampMax ? '100%' : v === 'center' ? '50%' : v; const { n, u } = decomposeRawValue(value, decomposedOriginalValue); let px = n; if (u === '%') { px = (n / 100) * size; } else if (u) { px = convertValueUnit($el, decomposedOriginalValue, 'px', true).n; } if (clampMax && under < 0) px += under; if (clampMin && over > 0) px += over; return px; } /** * @param {HTMLElement} $el * @param {ScrollThresholdValue} v * @param {Number} size * @param {Number} [under] * @param {Number} [over] * @return {Number} */ const parseBoundValue = ($el, v, size, under, over) => { /** @type {Number} */ let value; if (isStr(v)) { const matchedOperator = relativeValuesExecRgx.exec(/** @type {String} */(v)); if (matchedOperator) { const splitter = matchedOperator[0]; const operator = splitter[0]; const splitted = /** @type {String} */(v).split(splitter); const clampMin = splitted[0] === 'min'; const clampMax = splitted[0] === 'max'; const valueAPx = convertValueToPx($el, splitted[0], size, under, over); const valueBPx = convertValueToPx($el, splitted[1], size, under, over); if (clampMin) { const min = getRelativeValue(convertValueToPx($el, 'min', size), valueBPx, operator); value = min < valueAPx ? valueAPx : min; } else if (clampMax) { const max = getRelativeValue(convertValueToPx($el, 'max', size), valueBPx, operator); value = max > valueAPx ? valueAPx : max; } else { value = getRelativeValue(valueAPx, valueBPx, operator); } } else { value = convertValueToPx($el, v, size, under, over); } } else { value = /** @type {Number} */(v); } return round(value, 0); } /** * @param {JSAnimation} linked * @return {HTMLElement} */ const getAnimationDomTarget = linked => { let $linkedTarget; const linkedTargets = linked.targets; for (let i = 0, l = linkedTargets.length; i < l; i++) { const target = linkedTargets[i]; if (target[isDomSymbol]) { $linkedTarget = /** @type {HTMLElement} */(target); break; } } return $linkedTarget; } let scrollerIndex = 0; const debugColors = ['#FF4B4B','#FF971B','#FFC730','#F9F640','#7AFF5A','#18FF74','#17E09B','#3CFFEC','#05DBE9','#33B3F1','#638CF9','#C563FE','#FF4FCF','#F93F8A']; export class ScrollObserver { /** * @param {ScrollObserverParams} parameters */ constructor(parameters = {}) { if (scope.current) scope.current.register(this); const syncMode = setValue(parameters.sync, 'play pause'); const ease = syncMode ? parseEase(/** @type {EasingParam} */(syncMode)) : null; const isLinear = syncMode && (syncMode === 'linear' || syncMode === none); const isEase = syncMode && !(ease === none && !isLinear); const isSmooth = syncMode && (isNum(syncMode) || syncMode === true || isLinear); const isMethods = syncMode && (isStr(syncMode) && !isEase && !isSmooth); const syncMethods = isMethods ? /** @type {String} */(syncMode).split(' ').map( (/** @type {String} */m) => () => { const linked = this.linked; return linked && linked[m] ? linked[m]() : null; } ) : null; const biDirSync = isMethods && syncMethods.length > 2; /** @type {Number} */ this.index = scrollerIndex++; /** @type {String|Number} */ this.id = !isUnd(parameters.id) ? parameters.id : this.index; /** @type {ScrollContainer} */ this.container = registerAndGetScrollContainer(parameters.container); /** @type {HTMLElement} */ this.target = null; /** @type {Tickable|WAAPIAnimation} */ this.linked = null; /** @type {Boolean} */ this.repeat = null; /** @type {Boolean} */ this.horizontal = null; /** @type {ScrollThresholdParam|ScrollThresholdValue|ScrollThresholdCallback} */ this.enter = null; /** @type {ScrollThresholdParam|ScrollThresholdValue|ScrollThresholdCallback} */ this.leave = null; /** @type {Boolean} */ this.sync = isEase || isSmooth || !!syncMethods; /** @type {EasingFunction} */ this.syncEase = isEase ? ease : null; /** @type {Number} */ this.syncSmooth = isSmooth ? syncMode === true || isLinear ? 1 : /** @type {Number} */(syncMode) : null; /** @type {Callback<ScrollObserver>} */ this.onSyncEnter = syncMethods && !biDirSync && syncMethods[0] ? syncMethods[0] : noop; /** @type {Callback<ScrollObserver>} */ this.onSyncLeave = syncMethods && !biDirSync && syncMethods[1] ? syncMethods[1] : noop; /** @type {Callback<ScrollObserver>} */ this.onSyncEnterForward = syncMethods && biDirSync && syncMethods[0] ? syncMethods[0] : noop; /** @type {Callback<ScrollObserver>} */ this.onSyncLeaveForward = syncMethods && biDirSync && syncMethods[1] ? syncMethods[1] : noop; /** @type {Callback<ScrollObserver>} */ this.onSyncEnterBackward = syncMethods && biDirSync && syncMethods[2] ? syncMethods[2] : noop; /** @type {Callback<ScrollObserver>} */ this.onSyncLeaveBackward = syncMethods && biDirSync && syncMethods[3] ? syncMethods[3] : noop; /** @type {Callback<ScrollObserver>} */ this.onEnter = parameters.onEnter || noop; /** @type {Callback<ScrollObserver>} */ this.onLeave = parameters.onLeave || noop; /** @type {Callback<ScrollObserver>} */ this.onEnterForward = parameters.onEnterForward || noop; /** @type {Callback<ScrollObserver>} */ this.onLeaveForward = parameters.onLeaveForward || noop; /** @type {Callback<ScrollObserver>} */ this.onEnterBackward = parameters.onEnterBackward || noop; /** @type {Callback<ScrollObserver>} */ this.onLeaveBackward = parameters.onLeaveBackward || noop; /** @type {Callback<ScrollObserver>} */ this.onUpdate = parameters.onUpdate || noop; /** @type {Callback<ScrollObserver>} */ this.onSyncComplete = parameters.onSyncComplete || noop; /** @type {Boolean} */ this.reverted = false; /** @type {Boolean} */ this.ready = false; /** @type {Boolean} */ this.completed = false; /** @type {Boolean} */ this.began = false; /** @type {Boolean} */ this.isInView = false; /** @type {Boolean} */ this.forceEnter = false; /** @type {Boolean} */ this.hasEntered = false; /** @type {Number} */ this.offset = 0; /** @type {Number} */ this.offsetStart = 0; /** @type {Number} */ this.offsetEnd = 0; /** @type {Number} */ this.distance = 0; /** @type {Number} */ this.prevProgress = 0; /** @type {Array} */ this.thresholds = ['start', 'end', 'end', 'start']; /** @type {[Number, Number, Number, Number]} */ this.coords = [0, 0, 0, 0]; /** @type {JSAnimation} */ this.debugStyles = null; /** @type {HTMLElement} */ this.$debug = null; /** @type {ScrollObserverParams} */ this._params = parameters; /** @type {Boolean} */ this._debug = setValue(parameters.debug, false); /** @type {ScrollObserver} */ this._next = null; /** @type {ScrollObserver} */ this._prev = null; addChild(this.container, this); // Wait for the next frame to add to the container in order to handle calls to link() sync(() => { if (this.reverted) return; if (!this.target) { const target = /** @type {HTMLElement} */(parseTargets(parameters.target)[0]); this.target = target || doc.body; this.refresh(); } if (this._debug) this.debug(); }); } /** * @param {Tickable|WAAPIAnimation} linked */ link(linked) { if (linked) { // Make sure to pause the linked object in case it's added later linked.pause(); this.linked = linked; // Forces WAAPI Animation to persist; otherwise, they will stop syncing on finish. if (!isUnd(/** @type {WAAPIAnimation} */(linked))) /** @type {WAAPIAnimation} */(linked).persist = true; // Try to use a target of the linked object if no target parameters specified if (!this._params.target) { /** @type {HTMLElement} */ let $linkedTarget; if (!isUnd(/** @type {JSAnimation} */(linked).targets)) { $linkedTarget = getAnimationDomTarget(/** @type {JSAnimation} */(linked)); } else { forEachChildren(/** @type {Timeline} */(linked), (/** @type {JSAnimation} */child) => { if (child.targets && !$linkedTarget) { $linkedTarget = getAnimationDomTarget(/** @type {JSAnimation} */(child)); } }); } // Fallback to body if no target found this.target = $linkedTarget || doc.body; this.refresh(); } } return this; } get velocity() { return this.container.velocity; } get backward() { return this.horizontal ? this.container.backwardX : this.container.backwardY; } get scroll() { return this.horizontal ? this.container.scrollX : this.container.scrollY; } get progress() { const p = (this.scroll - this.offsetStart) / this.distance; return p === Infinity || isNaN(p) ? 0 : round(clamp(p, 0, 1), 6); } refresh() { // This flag is used to prevent running handleScroll() outside of this.refresh() with values not yet calculated this.ready = true; this.reverted = false; const params = this._params; this.repeat = setValue(parseScrollObserverFunctionParameter(params.repeat, this), true); this.horizontal = setValue(parseScrollObserverFunctionParameter(params.axis, this), 'y') === 'x'; this.enter = setValue(parseScrollObserverFunctionParameter(params.enter, this), 'end start'); this.leave = setValue(parseScrollObserverFunctionParameter(params.leave, this), 'start end'); this.updateBounds(); this.handleScroll(); return this; } removeDebug() { if (this.$debug) { this.$debug.parentNode.removeChild(this.$debug); this.$debug = null; } if (this.debugStyles) { this.debugStyles.revert(); this.$debug = null; } return this; } debug() { this.removeDebug(); const container = this.container; const isHori = this.horizontal; const $existingDebug = container.element.querySelector(':scope > .animejs-onscroll-debug'); const $debug = doc.createElement('div'); const $thresholds = doc.createElement('div'); const $triggers = doc.createElement('div'); const color = debugColors[this.index % debugColors.length]; const useWin = container.useWin; const containerWidth = useWin ? container.winWidth : container.width; const containerHeight = useWin ? container.winHeight : container.height; const scrollWidth = container.scrollWidth; const scrollHeight = container.scrollHeight; const size = this.container.width > 360 ? 320 : 260; const offLeft = isHori ? 0 : 10; const offTop = isHori ? 10 : 0; const half = isHori ? 24 : size / 2; const labelHeight = isHori ? half : 15; const labelWidth = isHori ? 60 : half; const labelSize = isHori ? labelWidth : labelHeight; const repeat = isHori ? 'repeat-x' : 'repeat-y'; /** * @param {Number} v * @return {String} */ const gradientOffset = v => isHori ? '0px '+(v)+'px' : (v)+'px'+' 2px'; /** * @param {String} c * @return {String} */ const lineCSS = (c) => `linear-gradient(${isHori ? 90 : 0}deg, ${c} 2px, transparent 1px)`; /** * @param {String} p * @param {Number} l * @param {Number} t * @param {Number} w * @param {Number} h * @return {String} */ const baseCSS = (p, l, t, w, h) => `position:${p};left:${l}px;top:${t}px;width:${w}px;height:${h}px;`; $debug.style.cssText = `${baseCSS('absolute', offLeft, offTop, isHori ? scrollWidth : size, isHori ? size : scrollHeight)} pointer-events: none; z-index: ${this.container.zIndex++}; display: flex; flex-direction: ${isHori ? 'column' : 'row'}; filter: drop-shadow(0px 1px 0px rgba(0,0,0,.75)); `; $thresholds.style.cssText = `${baseCSS('sticky', 0, 0, isHori ? containerWidth : half, isHori ? half : containerHeight)}`; if (!$existingDebug) { $thresholds.style.cssText += `background: ${lineCSS('#FFFF')}${gradientOffset(half-10)} / ${isHori ? '100px 100px' : '100px 100px'} ${repeat}, ${lineCSS('#FFF8')}${gradientOffset(half-10)} / ${isHori ? '10px 10px' : '10px 10px'} ${repeat}; `; } $triggers.style.cssText = `${baseCSS('relative', 0, 0, isHori ? scrollWidth : half, isHori ? half : scrollHeight)}`; if (!$existingDebug) { $triggers.style.cssText += `background: ${lineCSS('#FFFF')}${gradientOffset(0)} / ${isHori ? '100px 10px' : '10px 100px'} ${repeat}, ${lineCSS('#FFF8')}${gradientOffset(0)} / ${isHori ? '10px 0px' : '0px 10px'} ${repeat}; `; } const labels = [' enter: ', ' leave: ']; this.coords.forEach((v, i) => { const isView = i > 1; const value = (isView ? 0 : this.offset) + v; const isTail = i % 2; const isFirst = value < labelSize; const isOver = value > (isView ? isHori ? containerWidth : containerHeight : isHori ? scrollWidth : scrollHeight) - labelSize; const isFlip = (isView ? isTail && !isFirst : !isTail && !isFirst) || isOver; const $label = doc.createElement('div'); const $text = doc.createElement('div'); const dirProp = isHori ? isFlip ? 'right' : 'left' : isFlip ? 'bottom' : 'top'; const flipOffset = isFlip ? (isHori ? labelWidth : labelHeight) + (!isView ? isHori ? -1 : -2 : isHori ? -1 : isOver ? 0 : -2) : !isView ? isHori ? 1 : 0 : isHori ? 1 : 0; // $text.innerHTML = `${!isView ? '' : labels[isTail] + ' '}${this.id}: ${this.thresholds[i]} ${isView ? '' : labels[isTail]}`; $text.innerHTML = `${this.id}${labels[isTail]}${this.thresholds[i]}`; $label.style.cssText = `${baseCSS('absolute', 0, 0, labelWidth, labelHeight)} display: flex; flex-direction: ${isHori ? 'column' : 'row'}; justify-content: flex-${isView ? 'start' : 'end'}; align-items: flex-${isFlip ? 'end' : 'start'}; border-${dirProp}: 2px ${isTail ? 'solid' : 'solid'} ${color}; `; $text.style.cssText = ` overflow: hidden; max-width: ${(size / 2) - 10}px; height: ${labelHeight}; margin-${isHori ? isFlip ? 'right' : 'left' : isFlip ? 'bottom' : 'top'}: -2px; padding: 1px; font-family: ui-monospace, monospace; font-size: 10px; letter-spacing: -.025em; line-height: 9px; font-weight: 600; text-align: ${isHori && isFlip || !isHori && !isView ? 'right' : 'left'}; white-space: pre; text-overflow: ellipsis; color: ${isTail ? color : 'rgba(0,0,0,.75)'}; background-color: ${isTail ? 'rgba(0,0,0,.65)' : color}; border: 2px solid ${isTail ? color : 'transparent'}; border-${isHori ? isFlip ? 'top-left' : 'top-right' : isFlip ? 'top-left' : 'bottom-left'}-radius: 5px; border-${isHori ? isFlip ? 'bottom-left' : 'bottom-right' : isFlip ? 'top-right' : 'bottom-right'}-radius: 5px; `; $label.appendChild($text); let position = value - flipOffset + (isHori ? 1 : 0); $label.style[isHori ? 'left' : 'top'] = `${position}px`; // $label.style[isHori ? 'left' : 'top'] = value - flipOffset + (!isFlip && isFirst && !isView ? 1 : isFlip ? 0 : -2) + 'px'; (isView ? $thresholds : $triggers).appendChild($label); }); $debug.appendChild($thresholds); $debug.appendChild($triggers); container.element.appendChild($debug); if (!$existingDebug) $debug.classList.add('animejs-onscroll-debug'); this.$debug = $debug; const containerPosition = get(container.element, 'position'); if (containerPosition === 'static') { this.debugStyles = set(container.element, { position: 'relative '}); } } updateBounds() { if (this._debug) { this.removeDebug(); } let stickys; const $target = this.target; const container = this.container; const isHori = this.horizontal; const linked = this.linked; let linkedTime; let $el = $target; // let offsetX = 0; // let offsetY = 0; // let $offsetParent = $el; /** @type {Element} */ if (linked) { linkedTime = linked.currentTime; linked.seek(0, true); } /* Old implementation to get offset and targetSize before fixing https://github.com/juliangarnier/anime/issues/1021 // const isContainerStatic = get(container.element, 'position') === 'static' ? set(container.element, { position: 'relative '}) : false; // while ($el && $el !== container.element && $el !== doc.body) { // const isSticky = get($el, 'position') === 'sticky' ? // set($el, { position: 'static' }) : // false; // if ($el === $offsetParent) { // offsetX += $el.offsetLeft || 0; // offsetY += $el.offsetTop || 0; // $offsetParent = $el.offsetParent; // } // $el = /** @type {HTMLElement} */($el.parentElement); // if (isSticky) { // if (!stickys) stickys = []; // stickys.push(isSticky); // } // } // if (isContainerStatic) isContainerStatic.revert(); // const offset = isHori ? offsetX : offsetY; // const targetSize = isHori ? $target.offsetWidth : $target.offsetHeight; while ($el && $el !== container.element && $el !== doc.body) { const isSticky = get($el, 'position') === 'sticky' ? set($el, { position: 'static' }) : false; $el = $el.parentElement; if (isSticky) { if (!stickys) stickys = []; stickys.push(isSticky); } } const rect = $target.getBoundingClientRect(); const scale = container.scale; const offset = (isHori ? rect.left + container.scrollX - container.left : rect.top + container.scrollY - container.top) * scale; const targetSize = (isHori ? rect.width : rect.height) * scale; const containerSize = isHori ? container.width : container.height; const scrollSize = isHori ? container.scrollWidth : container.scrollHeight; const maxScroll = scrollSize - containerSize; const enter = this.enter; const leave = this.leave; /** @type {ScrollThresholdValue} */ let enterTarget = 'start'; /** @type {ScrollThresholdValue} */ let leaveTarget = 'end'; /** @type {ScrollThresholdValue} */ let enterContainer = 'end'; /** @type {ScrollThresholdValue} */ let leaveContainer = 'start'; if (isStr(enter)) { const splitted = /** @type {String} */(enter).split(' '); enterContainer = splitted[0]; enterTarget = splitted.length > 1 ? splitted[1] : enterTarget; } else if (isObj(enter)) { const e = /** @type {ScrollThresholdParam} */(enter); if (!isUnd(e.container)) enterContainer = e.container; if (!isUnd(e.target)) enterTarget = e.target; } else if (isNum(enter)) { enterContainer = /** @type {Number} */(enter); } if (isStr(leave)) { const splitted = /** @type {String} */(leave).split(' '); leaveContainer = splitted[0]; leaveTarget = splitted.length > 1 ? splitted[1] : leaveTarget; } else if (isObj(leave)) { const t = /** @type {ScrollThresholdParam} */(leave); if (!isUnd(t.container)) leaveContainer = t.container; if (!isUnd(t.target)) leaveTarget = t.target; } else if (isNum(leave)) { leaveContainer = /** @type {Number} */(leave); } const parsedEnterTarget = parseBoundValue($target, enterTarget, targetSize); const parsedLeaveTarget = parseBoundValue($target, leaveTarget, targetSize); const under = (parsedEnterTarget + offset) - containerSize; const over = (parsedLeaveTarget + offset) - maxScroll; const parsedEnterContainer = parseBoundValue($target, enterContainer, containerSize, under, over); const parsedLeaveContainer = parseBoundValue($target, leaveContainer, containerSize, under, over); const offsetStart = parsedEnterTarget + offset - parsedEnterContainer; const offsetEnd = parsedLeaveTarget + offset - parsedLeaveContainer; const scrollDelta = offsetEnd - offsetStart; this.offset = offset; this.offsetStart = offsetStart; this.offsetEnd = offsetEnd; this.distance = scrollDelta <= 0 ? 0 : scrollDelta; this.thresholds = [enterTarget, leaveTarget, enterContainer, leaveContainer]; this.coords = [parsedEnterTarget, parsedLeaveTarget, parsedEnterContainer, parsedLeaveContainer]; if (stickys) { stickys.forEach(sticky => sticky.revert()); } if (linked) { linked.seek(linkedTime, true); } if (this._debug) { this.debug(); } } handleScroll() { if (!this.ready) return; const linked = this.linked; const sync = this.sync; const syncEase = this.syncEase; const syncSmooth = this.syncSmooth; const shouldSeek = linked && (syncEase || syncSmooth); const isHori = this.horizontal; const container = this.container; const scroll = this.scroll; const isBefore = scroll <= this.offsetStart; const isAfter = scroll >= this.offsetEnd; const isInView = !isBefore && !isAfter; const isOnTheEdge = scroll === this.offsetStart || scroll === this.offsetEnd; const forceEnter = !this.hasEntered && isOnTheEdge; const $debug = this._debug && this.$debug; let hasUpdated = false; let syncCompleted = false; let p = this.progress; if (isBefore && this.began) { this.began = false; } if (p > 0 && !this.began) { this.began = true; } if (shouldSeek) { const lp = linked.progress; if (syncSmooth && isNum(syncSmooth)) { if (/** @type {Number} */(syncSmooth) < 1) { const step = 0.0001; const snap = lp < p && p === 1 ? step : lp > p && !p ? -step : 0; p = round(lerp(lp, p, lerp(.01, .2, /** @type {Number} */(syncSmooth))) + snap, 6); } } else if (syncEase) { p = syncEase(p); } hasUpdated = p !== this.prevProgress; syncCompleted = lp === 1; if (hasUpdated && !syncCompleted && (syncSmooth && lp)) { container.wakeTicker.restart(); } } if ($debug) { const sticky = isHori ? container.scrollY : container.scrollX; $debug.style[isHori ? 'top' : 'left'] = sticky + 10 + 'px'; } // Trigger enter callbacks if already in view or when entering the view if ((isInView && !this.isInView) || (forceEnter && !this.forceEnter && !this.hasEntered)) { if (isInView) this.isInView = true; if (!this.forceEnter || !this.hasEntered) { if ($debug && isInView) $debug.style.zIndex = `${this.container.zIndex++}`; this.onSyncEnter(this); this.onEnter(this); if (this.backward) { this.onSyncEnterBackward(this); this.onEnterBackward(this); } else { this.onSyncEnterForward(this); this.onEnterForward(this); } this.hasEntered = true; if (forceEnter) this.forceEnter = true; } else if (isInView) { this.forceEnter = false; } } if (isInView || !isInView && this.isInView) { hasUpdated = true; } if (hasUpdated) { if (shouldSeek) linked.seek(linked.duration * p); this.onUpdate(this); } if (!isInView && this.isInView) { this.isInView = false; this.onSyncLeave(this); this.onLeave(this); if (this.backward) { this.onSyncLeaveBackward(this); this.onLeaveBackward(this); } else { this.onSyncLeaveForward(this); this.onLeaveForward(this); } if (sync && !syncSmooth) { syncCompleted = true; } } if (p >= 1 && this.began && !this.completed && (sync && syncCompleted || !sync)) { if (sync) { this.onSyncComplete(this); } this.completed = true; if ((!this.repeat && !linked) || (!this.repeat && linked && linked.completed)) { this.revert(); } } if (p < 1 && this.completed) { this.completed = false; } this.prevProgress = p; } revert() { if (this.reverted) return; const container = this.container; removeChild(container, this); if (!container._head) { container.revert(); } if (this._debug) { this.removeDebug(); } this.reverted = true; this.ready = false; return this; } } /** * @param {ScrollObserverParams} [parameters={}] * @return {ScrollObserver} */ export const onScroll = (parameters = {}) => new ScrollObserver(parameters);
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/src/core/clock.js
src/core/clock.js
import { K, maxFps, minValue, tickModes, } from './consts.js'; import { round, } from './helpers.js'; /** * @import { * Tickable, * Tween, * } from '../types/index.js' */ /* * Base class to control framerate and playback rate. * Inherited by Engine, Timer, Animation and Timeline. */ export class Clock { /** @param {Number} [initTime] */ constructor(initTime = 0) { /** @type {Number} */ this.deltaTime = 0; /** @type {Number} */ this._currentTime = initTime; /** @type {Number} */ this._elapsedTime = initTime; /** @type {Number} */ this._startTime = initTime; /** @type {Number} */ this._lastTime = initTime; /** @type {Number} */ this._scheduledTime = 0; /** @type {Number} */ this._frameDuration = round(K / maxFps, 0); /** @type {Number} */ this._fps = maxFps; /** @type {Number} */ this._speed = 1; /** @type {Boolean} */ this._hasChildren = false; /** @type {Tickable|Tween} */ this._head = null; /** @type {Tickable|Tween} */ this._tail = null; } get fps() { return this._fps; } set fps(frameRate) { const previousFrameDuration = this._frameDuration; const fr = +frameRate; const fps = fr < minValue ? minValue : fr; const frameDuration = round(K / fps, 0); this._fps = fps; this._frameDuration = frameDuration; this._scheduledTime += frameDuration - previousFrameDuration; } get speed() { return this._speed; } set speed(playbackRate) { const pbr = +playbackRate; this._speed = pbr < minValue ? minValue : pbr; } /** * @param {Number} time * @return {tickModes} */ requestTick(time) { const scheduledTime = this._scheduledTime; const elapsedTime = this._elapsedTime; this._elapsedTime += (time - elapsedTime); // If the elapsed time is lower than the scheduled time // this means not enough time has passed to hit one frameDuration // so skip that frame if (elapsedTime < scheduledTime) return tickModes.NONE; const frameDuration = this._frameDuration; const frameDelta = elapsedTime - scheduledTime; // Ensures that _scheduledTime progresses in steps of at least 1 frameDuration. // Skips ahead if the actual elapsed time is higher. this._scheduledTime += frameDelta < frameDuration ? frameDuration : frameDelta; return tickModes.AUTO; } /** * @param {Number} time * @return {Number} */ computeDeltaTime(time) { const delta = time - this._lastTime; this.deltaTime = delta; this._lastTime = time; return delta; } }
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/src/core/consts.js
src/core/consts.js
// Environments // TODO: Do we need to check if we're running inside a worker ? export const isBrowser = typeof window !== 'undefined'; /** @type {Window & {AnimeJS: Array}|null} */ export const win = isBrowser ? /** @type {Window & {AnimeJS: Array}} */(/** @type {unknown} */(window)) : null; /** @type {Document|null} */ export const doc = isBrowser ? document : null; // Enums /** @enum {Number} */ export const tweenTypes = { OBJECT: 0, ATTRIBUTE: 1, CSS: 2, TRANSFORM: 3, CSS_VAR: 4, } /** @enum {Number} */ export const valueTypes = { NUMBER: 0, UNIT: 1, COLOR: 2, COMPLEX: 3, } /** @enum {Number} */ export const tickModes = { NONE: 0, AUTO: 1, FORCE: 2, } /** @enum {Number} */ export const compositionTypes = { replace: 0, none: 1, blend: 2, } // Cache symbols export const isRegisteredTargetSymbol = Symbol(); export const isDomSymbol = Symbol(); export const isSvgSymbol = Symbol(); export const transformsSymbol = Symbol(); export const morphPointsSymbol = Symbol(); export const proxyTargetSymbol = Symbol(); // Numbers export const minValue = 1e-11; export const maxValue = 1e12; export const K = 1e3; export const maxFps = 120; // Strings export const emptyString = ''; export const cssVarPrefix = 'var('; export const shortTransforms = /*#__PURE__*/ (() => { const map = new Map(); map.set('x', 'translateX'); map.set('y', 'translateY'); map.set('z', 'translateZ'); return map; })(); export const validTransforms = [ 'translateX', 'translateY', 'translateZ', 'rotate', 'rotateX', 'rotateY', 'rotateZ', 'scale', 'scaleX', 'scaleY', 'scaleZ', 'skew', 'skewX', 'skewY', 'matrix', 'matrix3d', 'perspective', ]; export const transformsFragmentStrings = /*#__PURE__*/ validTransforms.reduce((a, v) => ({...a, [v]: v + '('}), {}); // Functions /** @return {void} */ export const noop = () => {}; // Regex export const hexTestRgx = /(^#([\da-f]{3}){1,2}$)|(^#([\da-f]{4}){1,2}$)/i; export const rgbExecRgx = /rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/i export const rgbaExecRgx = /rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(-?\d+|-?\d*.\d+)\s*\)/i export const hslExecRgx = /hsl\(\s*(-?\d+|-?\d*.\d+)\s*,\s*(-?\d+|-?\d*.\d+)%\s*,\s*(-?\d+|-?\d*.\d+)%\s*\)/i; export const hslaExecRgx = /hsla\(\s*(-?\d+|-?\d*.\d+)\s*,\s*(-?\d+|-?\d*.\d+)%\s*,\s*(-?\d+|-?\d*.\d+)%\s*,\s*(-?\d+|-?\d*.\d+)\s*\)/i; // export const digitWithExponentRgx = /[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?/g; export const digitWithExponentRgx = /[-+]?\d*\.?\d+(?:e[-+]?\d)?/gi; // export const unitsExecRgx = /^([-+]?\d*\.?\d+(?:[eE][-+]?\d+)?)+([a-z]+|%)$/i; export const unitsExecRgx = /^([-+]?\d*\.?\d+(?:e[-+]?\d+)?)([a-z]+|%)$/i export const lowerCaseRgx = /([a-z])([A-Z])/g; export const transformsExecRgx = /(\w+)(\([^)]+\)+)/g; // Match inline transforms with cacl() values, returns the value wrapped in () export const relativeValuesExecRgx = /(\*=|\+=|-=)/; export const cssVariableMatchRgx = /var\(\s*(--[\w-]+)(?:\s*,\s*([^)]+))?\s*\)/;
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/src/core/colors.js
src/core/colors.js
import { rgbExecRgx, rgbaExecRgx, hslExecRgx, hslaExecRgx, } from './consts.js'; import { round, isRgb, isHex, isHsl, isUnd, } from './helpers.js'; /** * @import { * ColorArray, * } from '../types/index.js' */ /** * RGB / RGBA Color value string -> RGBA values array * @param {String} rgbValue * @return {ColorArray} */ const rgbToRgba = rgbValue => { const rgba = rgbExecRgx.exec(rgbValue) || rgbaExecRgx.exec(rgbValue); const a = !isUnd(rgba[4]) ? +rgba[4] : 1; return [ +rgba[1], +rgba[2], +rgba[3], a ] } /** * HEX3 / HEX3A / HEX6 / HEX6A Color value string -> RGBA values array * @param {String} hexValue * @return {ColorArray} */ const hexToRgba = hexValue => { const hexLength = hexValue.length; const isShort = hexLength === 4 || hexLength === 5; return [ +('0x' + hexValue[1] + hexValue[isShort ? 1 : 2]), +('0x' + hexValue[isShort ? 2 : 3] + hexValue[isShort ? 2 : 4]), +('0x' + hexValue[isShort ? 3 : 5] + hexValue[isShort ? 3 : 6]), ((hexLength === 5 || hexLength === 9) ? +(+('0x' + hexValue[isShort ? 4 : 7] + hexValue[isShort ? 4 : 8]) / 255).toFixed(3) : 1) ] } /** * @param {Number} p * @param {Number} q * @param {Number} t * @return {Number} */ const hue2rgb = (p, q, t) => { if (t < 0) t += 1; if (t > 1) t -= 1; return t < 1 / 6 ? p + (q - p) * 6 * t : t < 1 / 2 ? q : t < 2 / 3 ? p + (q - p) * (2 / 3 - t) * 6 : p; } /** * HSL / HSLA Color value string -> RGBA values array * @param {String} hslValue * @return {ColorArray} */ const hslToRgba = hslValue => { const hsla = hslExecRgx.exec(hslValue) || hslaExecRgx.exec(hslValue); const h = +hsla[1] / 360; const s = +hsla[2] / 100; const l = +hsla[3] / 100; const a = !isUnd(hsla[4]) ? +hsla[4] : 1; let r, g, b; if (s === 0) { r = g = b = l; } else { const q = l < .5 ? l * (1 + s) : l + s - l * s; const p = 2 * l - q; r = round(hue2rgb(p, q, h + 1 / 3) * 255, 0); g = round(hue2rgb(p, q, h) * 255, 0); b = round(hue2rgb(p, q, h - 1 / 3) * 255, 0); } return [r, g, b, a]; } /** * All in one color converter that converts a color string value into an array of RGBA values * @param {String} colorString * @return {ColorArray} */ export const convertColorStringValuesToRgbaArray = colorString => { return isRgb(colorString) ? rgbToRgba(colorString) : isHex(colorString) ? hexToRgba(colorString) : isHsl(colorString) ? hslToRgba(colorString) : [0, 0, 0, 1]; }
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/src/core/transforms.js
src/core/transforms.js
import { transformsExecRgx, transformsSymbol, } from './consts.js'; import { isUnd, stringStartsWith, } from './helpers.js'; /** * @import { * DOMTarget, * } from '../types/index.js' */ /** * @param {DOMTarget} target * @param {String} propName * @param {Object} animationInlineStyles * @return {String} */ export const parseInlineTransforms = (target, propName, animationInlineStyles) => { const inlineTransforms = target.style.transform; let inlinedStylesPropertyValue; if (inlineTransforms) { const cachedTransforms = target[transformsSymbol]; let t; while (t = transformsExecRgx.exec(inlineTransforms)) { const inlinePropertyName = t[1]; // const inlinePropertyValue = t[2]; const inlinePropertyValue = t[2].slice(1, -1); cachedTransforms[inlinePropertyName] = inlinePropertyValue; if (inlinePropertyName === propName) { inlinedStylesPropertyValue = inlinePropertyValue; // Store the new parsed inline styles if animationInlineStyles is provided if (animationInlineStyles) { animationInlineStyles[propName] = inlinePropertyValue; } } } } return inlineTransforms && !isUnd(inlinedStylesPropertyValue) ? inlinedStylesPropertyValue : stringStartsWith(propName, 'scale') ? '1' : stringStartsWith(propName, 'rotate') || stringStartsWith(propName, 'skew') ? '0deg' : '0px'; }
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/src/core/styles.js
src/core/styles.js
import { tweenTypes, shortTransforms, isDomSymbol, transformsSymbol, emptyString, transformsFragmentStrings, } from './consts.js'; import { forEachChildren, isNil, isSvg, isUnd, toLowerCase, } from './helpers.js'; /** * @import { * JSAnimation, * } from '../animation/animation.js' */ /** * @import { * Target, * DOMTarget, * Renderable, * Tween, * } from '../types/index.js' */ const propertyNamesCache = {}; /** * @param {String} propertyName * @param {Target} target * @param {tweenTypes} tweenType * @return {String} */ export const sanitizePropertyName = (propertyName, target, tweenType) => { if (tweenType === tweenTypes.TRANSFORM) { const t = shortTransforms.get(propertyName); return t ? t : propertyName; } else if ( tweenType === tweenTypes.CSS || // Handle special cases where properties like "strokeDashoffset" needs to be set as "stroke-dashoffset" // but properties like "baseFrequency" should stay in lowerCamelCase (tweenType === tweenTypes.ATTRIBUTE && (isSvg(target) && propertyName in /** @type {DOMTarget} */(target).style)) ) { const cachedPropertyName = propertyNamesCache[propertyName]; if (cachedPropertyName) { return cachedPropertyName; } else { const lowerCaseName = propertyName ? toLowerCase(propertyName) : propertyName; propertyNamesCache[propertyName] = lowerCaseName; return lowerCaseName; } } else { return propertyName; } } /** * @template {Renderable} T * @param {T} renderable * @return {T} */ export const cleanInlineStyles = renderable => { // Allow cleanInlineStyles() to be called on timelines if (renderable._hasChildren) { forEachChildren(renderable, cleanInlineStyles, true); } else { const animation = /** @type {JSAnimation} */(renderable); animation.pause(); forEachChildren(animation, (/** @type {Tween} */tween) => { const tweenProperty = tween.property; const tweenTarget = tween.target; if (tweenTarget[isDomSymbol]) { const targetStyle = /** @type {DOMTarget} */(tweenTarget).style; const originalInlinedValue = tween._inlineValue; const tweenHadNoInlineValue = isNil(originalInlinedValue) || originalInlinedValue === emptyString; if (tween._tweenType === tweenTypes.TRANSFORM) { const cachedTransforms = tweenTarget[transformsSymbol]; if (tweenHadNoInlineValue) { delete cachedTransforms[tweenProperty]; } else { cachedTransforms[tweenProperty] = originalInlinedValue; } if (tween._renderTransforms) { if (!Object.keys(cachedTransforms).length) { targetStyle.removeProperty('transform'); } else { let str = emptyString; for (let key in cachedTransforms) { str += transformsFragmentStrings[key] + cachedTransforms[key] + ') '; } targetStyle.transform = str; } } } else { if (tweenHadNoInlineValue) { targetStyle.removeProperty(toLowerCase(tweenProperty)); } else { targetStyle[tweenProperty] = originalInlinedValue; } } if (animation._tail === tween) { animation.targets.forEach(t => { if (t.getAttribute && t.getAttribute('style') === emptyString) { t.removeAttribute('style'); }; }); } } }) } return renderable; }
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/src/core/globals.js
src/core/globals.js
import { K, noop, maxFps, compositionTypes, win, doc, isBrowser, } from './consts.js'; /** * @import { * DefaultsParams, * DOMTarget, * } from '../types/index.js' * * @import { * Scope, * } from '../scope/index.js' */ /** @type {DefaultsParams} */ export const defaults = { id: null, keyframes: null, playbackEase: null, playbackRate: 1, frameRate: maxFps, loop: 0, reversed: false, alternate: false, autoplay: true, persist: false, duration: K, delay: 0, loopDelay: 0, ease: 'out(2)', composition: compositionTypes.replace, modifier: v => v, onBegin: noop, onBeforeUpdate: noop, onUpdate: noop, onLoop: noop, onPause: noop, onComplete: noop, onRender: noop, } export const scope = { /** @type {Scope} */ current: null, /** @type {Document|DOMTarget} */ root: doc, } export const globals = { /** @type {DefaultsParams} */ defaults, /** @type {Number} */ precision: 4, /** @type {Number} equals 1 in ms mode, 0.001 in s mode */ timeScale: 1, /** @type {Number} */ tickThreshold: 200, } export const globalVersions = { version: '__packageVersion__', engine: null }; if (isBrowser) { if (!win.AnimeJS) win.AnimeJS = []; win.AnimeJS.push(globalVersions); }
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/src/core/render.js
src/core/render.js
import { globals, } from './globals.js'; import { tweenTypes, valueTypes, tickModes, compositionTypes, emptyString, transformsFragmentStrings, transformsSymbol, minValue, } from './consts.js'; import { now, clamp, round, lerp, forEachChildren, } from './helpers.js'; /** * @import { * Tickable, * Renderable, * CallbackArgument, * Tween, * DOMTarget, * } from '../types/index.js' */ /** * @import { * JSAnimation, * } from '../animation/animation.js' */ /** * @import { * Timeline, * } from '../timeline/timeline.js' */ /** * @param {Tickable} tickable * @param {Number} time * @param {Number} muteCallbacks * @param {Number} internalRender * @param {tickModes} tickMode * @return {Number} */ export const render = (tickable, time, muteCallbacks, internalRender, tickMode) => { const parent = tickable.parent; const duration = tickable.duration; const completed = tickable.completed; const iterationDuration = tickable.iterationDuration; const iterationCount = tickable.iterationCount; const _currentIteration = tickable._currentIteration; const _loopDelay = tickable._loopDelay; const _reversed = tickable._reversed; const _alternate = tickable._alternate; const _hasChildren = tickable._hasChildren; const tickableDelay = tickable._delay; const tickablePrevAbsoluteTime = tickable._currentTime; // TODO: rename ._currentTime to ._absoluteCurrentTime const tickableEndTime = tickableDelay + iterationDuration; const tickableAbsoluteTime = time - tickableDelay; const tickablePrevTime = clamp(tickablePrevAbsoluteTime, -tickableDelay, duration); const tickableCurrentTime = clamp(tickableAbsoluteTime, -tickableDelay, duration); const deltaTime = tickableAbsoluteTime - tickablePrevAbsoluteTime; const isCurrentTimeAboveZero = tickableCurrentTime > 0; const isCurrentTimeEqualOrAboveDuration = tickableCurrentTime >= duration; const isSetter = duration <= minValue; const forcedTick = tickMode === tickModes.FORCE; let isOdd = 0; let iterationElapsedTime = tickableAbsoluteTime; // Render checks // Used to also check if the children have rendered in order to trigger the onRender callback on the parent timer let hasRendered = 0; // Execute the "expensive" iterations calculations only when necessary if (iterationCount > 1) { // bitwise NOT operator seems to be generally faster than Math.floor() across browsers const currentIteration = ~~(tickableCurrentTime / (iterationDuration + (isCurrentTimeEqualOrAboveDuration ? 0 : _loopDelay))); tickable._currentIteration = clamp(currentIteration, 0, iterationCount); // Prevent the iteration count to go above the max iterations when reaching the end of the animation if (isCurrentTimeEqualOrAboveDuration) tickable._currentIteration--; isOdd = tickable._currentIteration % 2; iterationElapsedTime = tickableCurrentTime % (iterationDuration + _loopDelay) || 0; } // Checks if exactly one of _reversed and (_alternate && isOdd) is true const isReversed = _reversed ^ (_alternate && isOdd); const _ease = /** @type {Renderable} */(tickable)._ease; let iterationTime = isCurrentTimeEqualOrAboveDuration ? isReversed ? 0 : duration : isReversed ? iterationDuration - iterationElapsedTime : iterationElapsedTime; if (_ease) iterationTime = iterationDuration * _ease(iterationTime / iterationDuration) || 0; const isRunningBackwards = (parent ? parent.backwards : tickableAbsoluteTime < tickablePrevAbsoluteTime) ? !isReversed : !!isReversed; tickable._currentTime = tickableAbsoluteTime; tickable._iterationTime = iterationTime; tickable.backwards = isRunningBackwards; if (isCurrentTimeAboveZero && !tickable.began) { tickable.began = true; if (!muteCallbacks && !(parent && (isRunningBackwards || !parent.began))) { tickable.onBegin(/** @type {CallbackArgument} */(tickable)); } } else if (tickableAbsoluteTime <= 0) { tickable.began = false; } // Only triggers onLoop for tickable without children, otherwise call the the onLoop callback in the tick function // Make sure to trigger the onLoop before rendering to allow .refresh() to pickup the current values if (!muteCallbacks && !_hasChildren && isCurrentTimeAboveZero && tickable._currentIteration !== _currentIteration) { tickable.onLoop(/** @type {CallbackArgument} */(tickable)); } if ( forcedTick || tickMode === tickModes.AUTO && ( time >= tickableDelay && time <= tickableEndTime || // Normal render time <= tickableDelay && tickablePrevTime > tickableDelay || // Playhead is before the animation start time so make sure the animation is at its initial state time >= tickableEndTime && tickablePrevTime !== duration // Playhead is after the animation end time so make sure the animation is at its end state ) || iterationTime >= tickableEndTime && tickablePrevTime !== duration || iterationTime <= tickableDelay && tickablePrevTime > 0 || time <= tickablePrevTime && tickablePrevTime === duration && completed || // Force a render if a seek occurs on an completed animation isCurrentTimeEqualOrAboveDuration && !completed && isSetter // This prevents 0 duration tickables to be skipped ) { if (isCurrentTimeAboveZero) { // Trigger onUpdate callback before rendering tickable.computeDeltaTime(tickablePrevTime); if (!muteCallbacks) tickable.onBeforeUpdate(/** @type {CallbackArgument} */(tickable)); } // Start tweens rendering if (!_hasChildren) { // Time has jumped more than globals.tickThreshold so consider this tick manual const forcedRender = forcedTick || (isRunningBackwards ? deltaTime * -1 : deltaTime) >= globals.tickThreshold; const absoluteTime = tickable._offset + (parent ? parent._offset : 0) + tickableDelay + iterationTime; // Only Animation can have tweens, Timer returns undefined let tween = /** @type {Tween} */(/** @type {JSAnimation} */(tickable)._head); let tweenTarget; let tweenStyle; let tweenTargetTransforms; let tweenTargetTransformsProperties; let tweenTransformsNeedUpdate = 0; while (tween) { const tweenComposition = tween._composition; const tweenCurrentTime = tween._currentTime; const tweenChangeDuration = tween._changeDuration; const tweenAbsEndTime = tween._absoluteStartTime + tween._changeDuration; const tweenNextRep = tween._nextRep; const tweenPrevRep = tween._prevRep; const tweenHasComposition = tweenComposition !== compositionTypes.none; if ((forcedRender || ( (tweenCurrentTime !== tweenChangeDuration || absoluteTime <= tweenAbsEndTime + (tweenNextRep ? tweenNextRep._delay : 0)) && (tweenCurrentTime !== 0 || absoluteTime >= tween._absoluteStartTime) )) && (!tweenHasComposition || ( !tween._isOverridden && (!tween._isOverlapped || absoluteTime <= tweenAbsEndTime) && (!tweenNextRep || (tweenNextRep._isOverridden || absoluteTime <= tweenNextRep._absoluteStartTime)) && (!tweenPrevRep || (tweenPrevRep._isOverridden || (absoluteTime >= (tweenPrevRep._absoluteStartTime + tweenPrevRep._changeDuration) + tween._delay))) )) ) { const tweenNewTime = tween._currentTime = clamp(iterationTime - tween._startTime, 0, tweenChangeDuration); const tweenProgress = tween._ease(tweenNewTime / tween._updateDuration); const tweenModifier = tween._modifier; const tweenValueType = tween._valueType; const tweenType = tween._tweenType; const tweenIsObject = tweenType === tweenTypes.OBJECT; const tweenIsNumber = tweenValueType === valueTypes.NUMBER; // Only round the in-between frames values if the final value is a string const tweenPrecision = (tweenIsNumber && tweenIsObject) || tweenProgress === 0 || tweenProgress === 1 ? -1 : globals.precision; // Recompose tween value /** @type {String|Number} */ let value; /** @type {Number} */ let number; if (tweenIsNumber) { value = number = /** @type {Number} */(tweenModifier(round(lerp(tween._fromNumber, tween._toNumber, tweenProgress), tweenPrecision ))); } else if (tweenValueType === valueTypes.UNIT) { // Rounding the values speed up string composition number = /** @type {Number} */(tweenModifier(round(lerp(tween._fromNumber, tween._toNumber, tweenProgress), tweenPrecision))); value = `${number}${tween._unit}`; } else if (tweenValueType === valueTypes.COLOR) { const fn = tween._fromNumbers; const tn = tween._toNumbers; const r = round(clamp(/** @type {Number} */(tweenModifier(lerp(fn[0], tn[0], tweenProgress))), 0, 255), 0); const g = round(clamp(/** @type {Number} */(tweenModifier(lerp(fn[1], tn[1], tweenProgress))), 0, 255), 0); const b = round(clamp(/** @type {Number} */(tweenModifier(lerp(fn[2], tn[2], tweenProgress))), 0, 255), 0); const a = clamp(/** @type {Number} */(tweenModifier(round(lerp(fn[3], tn[3], tweenProgress), tweenPrecision))), 0, 1); value = `rgba(${r},${g},${b},${a})`; if (tweenHasComposition) { const ns = tween._numbers; ns[0] = r; ns[1] = g; ns[2] = b; ns[3] = a; } } else if (tweenValueType === valueTypes.COMPLEX) { value = tween._strings[0]; for (let j = 0, l = tween._toNumbers.length; j < l; j++) { const n = /** @type {Number} */(tweenModifier(round(lerp(tween._fromNumbers[j], tween._toNumbers[j], tweenProgress), tweenPrecision))); const s = tween._strings[j + 1]; value += `${s ? n + s : n}`; if (tweenHasComposition) { tween._numbers[j] = n; } } } // For additive tweens and Animatables if (tweenHasComposition) { tween._number = number; } if (!internalRender && tweenComposition !== compositionTypes.blend) { const tweenProperty = tween.property; tweenTarget = tween.target; if (tweenIsObject) { tweenTarget[tweenProperty] = value; } else if (tweenType === tweenTypes.ATTRIBUTE) { /** @type {DOMTarget} */(tweenTarget).setAttribute(tweenProperty, /** @type {String} */(value)); } else { tweenStyle = /** @type {DOMTarget} */(tweenTarget).style; if (tweenType === tweenTypes.TRANSFORM) { if (tweenTarget !== tweenTargetTransforms) { tweenTargetTransforms = tweenTarget; // NOTE: Referencing the cachedTransforms in the tween property directly can be a little bit faster but appears to increase memory usage. tweenTargetTransformsProperties = tweenTarget[transformsSymbol]; } tweenTargetTransformsProperties[tweenProperty] = value; tweenTransformsNeedUpdate = 1; } else if (tweenType === tweenTypes.CSS) { tweenStyle[tweenProperty] = value; } else if (tweenType === tweenTypes.CSS_VAR) { tweenStyle.setProperty(tweenProperty,/** @type {String} */(value)); } } if (isCurrentTimeAboveZero) hasRendered = 1; } else { // Used for composing timeline tweens without having to do a real render tween._value = value; } } // NOTE: Possible improvement: Use translate(x,y) / translate3d(x,y,z) syntax // to reduce memory usage on string composition if (tweenTransformsNeedUpdate && tween._renderTransforms) { let str = emptyString; for (let key in tweenTargetTransformsProperties) { str += `${transformsFragmentStrings[key]}${tweenTargetTransformsProperties[key]}) `; } tweenStyle.transform = str; tweenTransformsNeedUpdate = 0; } tween = tween._next; } if (!muteCallbacks && hasRendered) { /** @type {JSAnimation} */(tickable).onRender(/** @type {JSAnimation} */(tickable)); } } if (!muteCallbacks && isCurrentTimeAboveZero) { tickable.onUpdate(/** @type {CallbackArgument} */(tickable)); } } // End tweens rendering // Handle setters on timeline differently and allow re-trigering the onComplete callback when seeking backwards if (parent && isSetter) { if (!muteCallbacks && ( // (tickableAbsoluteTime > 0 instead) of (tickableAbsoluteTime >= duration) to prevent floating point precision issues // see: https://github.com/juliangarnier/anime/issues/1088 (parent.began && !isRunningBackwards && tickableAbsoluteTime > 0 && !completed) || (isRunningBackwards && tickableAbsoluteTime <= minValue && completed) )) { tickable.onComplete(/** @type {CallbackArgument} */(tickable)); tickable.completed = !isRunningBackwards; } // If currentTime is both above 0 and at least equals to duration, handles normal onComplete or infinite loops } else if (isCurrentTimeAboveZero && isCurrentTimeEqualOrAboveDuration) { if (iterationCount === Infinity) { // Offset the tickable _startTime with its duration to reset _currentTime to 0 and continue the infinite timer tickable._startTime += tickable.duration; } else if (tickable._currentIteration >= iterationCount - 1) { // By setting paused to true, we tell the engine loop to not render this tickable and removes it from the list on the next tick tickable.paused = true; if (!completed && !_hasChildren) { // If the tickable has children, triggers onComplete() only when all children have completed in the tick function tickable.completed = true; if (!muteCallbacks && !(parent && (isRunningBackwards || !parent.began))) { tickable.onComplete(/** @type {CallbackArgument} */(tickable)); tickable._resolve(/** @type {CallbackArgument} */(tickable)); } } } // Otherwise set the completed flag to false } else { tickable.completed = false; } // NOTE: hasRendered * direction (negative for backwards) this way we can remove the tickable.backwards property completly ? return hasRendered; } /** * @param {Tickable} tickable * @param {Number} time * @param {Number} muteCallbacks * @param {Number} internalRender * @param {Number} tickMode * @return {void} */ export const tick = (tickable, time, muteCallbacks, internalRender, tickMode) => { const _currentIteration = tickable._currentIteration; render(tickable, time, muteCallbacks, internalRender, tickMode); if (tickable._hasChildren) { const tl = /** @type {Timeline} */(tickable); const tlIsRunningBackwards = tl.backwards; const tlChildrenTime = internalRender ? time : tl._iterationTime; const tlCildrenTickTime = now(); let tlChildrenHasRendered = 0; let tlChildrenHaveCompleted = true; // If the timeline has looped forward, we need to manually triggers children skipped callbacks if (!internalRender && tl._currentIteration !== _currentIteration) { const tlIterationDuration = tl.iterationDuration; forEachChildren(tl, (/** @type {JSAnimation} */child) => { if (!tlIsRunningBackwards) { // Force an internal render to trigger the callbacks if the child has not completed on loop if (!child.completed && !child.backwards && child._currentTime < child.iterationDuration) { render(child, tlIterationDuration, muteCallbacks, 1, tickModes.FORCE); } // Reset their began and completed flags to allow retrigering callbacks on the next iteration child.began = false; child.completed = false; } else { const childDuration = child.duration; const childStartTime = child._offset + child._delay; const childEndTime = childStartTime + childDuration; // Triggers the onComplete callback on reverse for children on the edges of the timeline if (!muteCallbacks && childDuration <= minValue && (!childStartTime || childEndTime === tlIterationDuration)) { child.onComplete(child); } } }); if (!muteCallbacks) tl.onLoop(/** @type {CallbackArgument} */(tl)); } forEachChildren(tl, (/** @type {JSAnimation} */child) => { const childTime = round((tlChildrenTime - child._offset) * child._speed, 12); // Rounding is needed when using seconds const childTickMode = child._fps < tl._fps ? child.requestTick(tlCildrenTickTime) : tickMode; tlChildrenHasRendered += render(child, childTime, muteCallbacks, internalRender, childTickMode); if (!child.completed && tlChildrenHaveCompleted) tlChildrenHaveCompleted = false; }, tlIsRunningBackwards); // Renders on timeline are triggered by its children so it needs to be set after rendering the children if (!muteCallbacks && tlChildrenHasRendered) tl.onRender(/** @type {CallbackArgument} */(tl)); // Triggers the timeline onComplete() once all chindren all completed and the current time has reached the end if ((tlChildrenHaveCompleted || tlIsRunningBackwards) && tl._currentTime >= tl.duration) { // Make sure the paused flag is false in case it has been skipped in the render function tl.paused = true; if (!tl.completed) { tl.completed = true; if (!muteCallbacks) { tl.onComplete(/** @type {CallbackArgument} */(tl)); tl._resolve(/** @type {CallbackArgument} */(tl)); } } } } }
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/src/core/targets.js
src/core/targets.js
import { scope, } from './globals.js'; import { isRegisteredTargetSymbol, isDomSymbol, isSvgSymbol, transformsSymbol, isBrowser, } from './consts.js'; import { isSvg, isNil, isArr, isStr, } from './helpers.js'; /** * @import { * DOMTarget, * DOMTargetsParam, * JSTargetsArray, * TargetsParam, * JSTargetsParam, * TargetsArray, * DOMTargetsArray, * } from '../types/index.js' */ /** * @param {DOMTargetsParam|TargetsParam} v * @return {NodeList|HTMLCollection} */ export function getNodeList(v) { const n = isStr(v) ? scope.root.querySelectorAll(v) : v; if (n instanceof NodeList || n instanceof HTMLCollection) return n; } /** * @overload * @param {DOMTargetsParam} targets * @return {DOMTargetsArray} * * @overload * @param {JSTargetsParam} targets * @return {JSTargetsArray} * * @overload * @param {TargetsParam} targets * @return {TargetsArray} * * @param {DOMTargetsParam|JSTargetsParam|TargetsParam} targets */ export function parseTargets(targets) { if (isNil(targets)) return /** @type {TargetsArray} */([]); if (!isBrowser) return /** @type {JSTargetsArray} */(isArr(targets) && targets.flat(Infinity) || [targets]); if (isArr(targets)) { const flattened = targets.flat(Infinity); /** @type {TargetsArray} */ const parsed = []; for (let i = 0, l = flattened.length; i < l; i++) { const item = flattened[i]; if (!isNil(item)) { const nodeList = getNodeList(item); if (nodeList) { for (let j = 0, jl = nodeList.length; j < jl; j++) { const subItem = nodeList[j]; if (!isNil(subItem)) { let isDuplicate = false; for (let k = 0, kl = parsed.length; k < kl; k++) { if (parsed[k] === subItem) { isDuplicate = true; break; } } if (!isDuplicate) { parsed.push(subItem); } } } } else { let isDuplicate = false; for (let j = 0, jl = parsed.length; j < jl; j++) { if (parsed[j] === item) { isDuplicate = true; break; } } if (!isDuplicate) { parsed.push(item); } } } } return parsed; } const nodeList = getNodeList(targets); if (nodeList) return /** @type {DOMTargetsArray} */(Array.from(nodeList)); return /** @type {TargetsArray} */([targets]); } /** * @overload * @param {DOMTargetsParam} targets * @return {DOMTargetsArray} * * @overload * @param {JSTargetsParam} targets * @return {JSTargetsArray} * * @overload * @param {TargetsParam} targets * @return {TargetsArray} * * @param {DOMTargetsParam|JSTargetsParam|TargetsParam} targets */ export function registerTargets(targets) { const parsedTargetsArray = parseTargets(targets); const parsedTargetsLength = parsedTargetsArray.length; if (parsedTargetsLength) { for (let i = 0; i < parsedTargetsLength; i++) { const target = parsedTargetsArray[i]; if (!target[isRegisteredTargetSymbol]) { target[isRegisteredTargetSymbol] = true; const isSvgType = isSvg(target); const isDom = /** @type {DOMTarget} */(target).nodeType || isSvgType; if (isDom) { target[isDomSymbol] = true; target[isSvgSymbol] = isSvgType; target[transformsSymbol] = {}; } } } } return parsedTargetsArray; }
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/src/core/helpers.js
src/core/helpers.js
import { isBrowser, lowerCaseRgx, hexTestRgx, maxValue, minValue, } from './consts.js'; import { globals, } from './globals.js'; /** * @import { * Target, * DOMTarget, * } from '../types/index.js' */ // Strings /** * @param {String} str * @return {String} */ export const toLowerCase = str => str.replace(lowerCaseRgx, '$1-$2').toLowerCase(); /** * Prioritize this method instead of regex when possible * @param {String} str * @param {String} sub * @return {Boolean} */ export const stringStartsWith = (str, sub) => str.indexOf(sub) === 0; // Note: Date.now is used instead of performance.now since it is precise enough for timings calculations, performs slightly faster and works in Node.js environement. export const now = Date.now; // Types checkers export const isArr = Array.isArray; /**@param {any} a @return {a is Record<String, any>} */ export const isObj = a => a && a.constructor === Object; /**@param {any} a @return {a is Number} */ export const isNum = a => typeof a === 'number' && !isNaN(a); /**@param {any} a @return {a is String} */ export const isStr = a => typeof a === 'string'; /**@param {any} a @return {a is Function} */ export const isFnc = a => typeof a === 'function'; /**@param {any} a @return {a is undefined} */ export const isUnd = a => typeof a === 'undefined'; /**@param {any} a @return {a is null | undefined} */ export const isNil = a => isUnd(a) || a === null; /**@param {any} a @return {a is SVGElement} */ export const isSvg = a => isBrowser && a instanceof SVGElement; /**@param {any} a @return {Boolean} */ export const isHex = a => hexTestRgx.test(a); /**@param {any} a @return {Boolean} */ export const isRgb = a => stringStartsWith(a, 'rgb'); /**@param {any} a @return {Boolean} */ export const isHsl = a => stringStartsWith(a, 'hsl'); /**@param {any} a @return {Boolean} */ export const isCol = a => isHex(a) || isRgb(a) || isHsl(a); /**@param {any} a @return {Boolean} */ export const isKey = a => !globals.defaults.hasOwnProperty(a); // SVG // Consider the following as CSS animation // CSS opacity animation has better default values (opacity: 1 instead of 0)) // rotate is more commonly intended to be used as a transform const svgCssReservedProperties = ['opacity', 'rotate', 'overflow', 'color']; /** * @param {Target} el * @param {String} propertyName * @return {Boolean} */ export const isValidSVGAttribute = (el, propertyName) => { if (svgCssReservedProperties.includes(propertyName)) return false; if (el.getAttribute(propertyName) || propertyName in el) { if (propertyName === 'scale') { // Scale const elParentNode = /** @type {SVGGeometryElement} */(/** @type {DOMTarget} */(el).parentNode); // Only consider scale as a valid SVG attribute on filter element return elParentNode && elParentNode.tagName === 'filter'; } return true; } } // Number /** * @param {Number|String} str * @return {Number} */ export const parseNumber = str => isStr(str) ? parseFloat(/** @type {String} */(str)) : /** @type {Number} */(str); // Math export const pow = Math.pow; export const sqrt = Math.sqrt; export const sin = Math.sin; export const cos = Math.cos; export const abs = Math.abs; export const exp = Math.exp; export const ceil = Math.ceil; export const floor = Math.floor; export const asin = Math.asin; export const max = Math.max; export const atan2 = Math.atan2; export const PI = Math.PI; export const _round = Math.round; /** * Clamps a value between min and max bounds * * @param {Number} v - Value to clamp * @param {Number} min - Minimum boundary * @param {Number} max - Maximum boundary * @return {Number} */ export const clamp = (v, min, max) => v < min ? min : v > max ? max : v; const powCache = {}; /** * Rounds a number to specified decimal places * * @param {Number} v - Value to round * @param {Number} decimalLength - Number of decimal places * @return {Number} */ export const round = (v, decimalLength) => { if (decimalLength < 0) return v; if (!decimalLength) return _round(v); let p = powCache[decimalLength]; if (!p) p = powCache[decimalLength] = 10 ** decimalLength; return _round(v * p) / p; }; /** * Snaps a value to nearest increment or array value * * @param {Number} v - Value to snap * @param {Number|Array<Number>} increment - Step size or array of snap points * @return {Number} */ export const snap = (v, increment) => isArr(increment) ? increment.reduce((closest, cv) => (abs(cv - v) < abs(closest - v) ? cv : closest)) : increment ? _round(v / increment) * increment : v; /** * Linear interpolation between two values * * @param {Number} start - Starting value * @param {Number} end - Ending value * @param {Number} factor - Interpolation factor in the range [0, 1] * @return {Number} The interpolated value */ export const lerp = (start, end, factor) => start + (end - start) * factor; /** * Replaces infinity with maximum safe value * * @param {Number} v - Value to check * @return {Number} */ export const clampInfinity = v => v === Infinity ? maxValue : v === -Infinity ? -maxValue : v; /** * Normalizes time value with minimum threshold * * @param {Number} v - Time value to normalize * @return {Number} */ export const normalizeTime = v => v <= minValue ? minValue : clampInfinity(round(v, 11)); // Arrays /** * @template T * @param {T[]} a * @return {T[]} */ export const cloneArray = a => isArr(a) ? [ ...a ] : a; // Objects /** * @template T * @template U * @param {T} o1 * @param {U} o2 * @return {T & U} */ export const mergeObjects = (o1, o2) => { const merged = /** @type {T & U} */({ ...o1 }); for (let p in o2) { const o1p = /** @type {T & U} */(o1)[p]; merged[p] = isUnd(o1p) ? /** @type {T & U} */(o2)[p] : o1p; }; return merged; } // Linked lists /** * @param {Object} parent * @param {Function} callback * @param {Boolean} [reverse] * @param {String} [prevProp] * @param {String} [nextProp] * @return {void} */ export const forEachChildren = (parent, callback, reverse, prevProp = '_prev', nextProp = '_next') => { let next = parent._head; let adjustedNextProp = nextProp; if (reverse) { next = parent._tail; adjustedNextProp = prevProp; } while (next) { const currentNext = next[adjustedNextProp]; callback(next); next = currentNext; } } /** * @param {Object} parent * @param {Object} child * @param {String} [prevProp] * @param {String} [nextProp] * @return {void} */ export const removeChild = (parent, child, prevProp = '_prev', nextProp = '_next') => { const prev = child[prevProp]; const next = child[nextProp]; prev ? prev[nextProp] = next : parent._head = next; next ? next[prevProp] = prev : parent._tail = prev; child[prevProp] = null; child[nextProp] = null; } /** * @param {Object} parent * @param {Object} child * @param {Function} [sortMethod] * @param {String} prevProp * @param {String} nextProp * @return {void} */ export const addChild = (parent, child, sortMethod, prevProp = '_prev', nextProp = '_next') => { let prev = parent._tail; while (prev && sortMethod && sortMethod(prev, child)) prev = prev[prevProp]; const next = prev ? prev[nextProp] : parent._head; prev ? prev[nextProp] = child : parent._head = child; next ? next[prevProp] = child : parent._tail = child; child[prevProp] = prev; child[nextProp] = next; }
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/src/core/values.js
src/core/values.js
import { shortTransforms, validTransforms, tweenTypes, valueTypes, digitWithExponentRgx, unitsExecRgx, isDomSymbol, isSvgSymbol, proxyTargetSymbol, cssVarPrefix, cssVariableMatchRgx, emptyString, } from './consts.js'; import { stringStartsWith, cloneArray, isFnc, isUnd, isCol, isValidSVGAttribute, isStr, } from './helpers.js'; import { parseInlineTransforms, } from './transforms.js'; import { convertColorStringValuesToRgbaArray } from './colors.js'; /** * @import { * Target, * DOMTarget, * Tween, * TweenPropValue, * TweenDecomposedValue, * } from '../types/index.js' */ /** * @template T, D * @param {T|undefined} targetValue * @param {D} defaultValue * @return {T|D} */ export const setValue = (targetValue, defaultValue) => { return isUnd(targetValue) ? defaultValue : targetValue; } /** * @param {TweenPropValue} value * @param {Target} target * @param {Number} index * @param {Number} total * @param {Object} [store] * @return {any} */ export const getFunctionValue = (value, target, index, total, store) => { let func; if (isFnc(value)) { func = () => { const computed = /** @type {Function} */(value)(target, index, total); // Fallback to 0 if the function returns undefined / NaN / null / false / 0 return !isNaN(+computed) ? +computed : computed || 0; } } else if (isStr(value) && stringStartsWith(value, cssVarPrefix)) { func = () => { const match = value.match(cssVariableMatchRgx); const cssVarName = match[1]; const fallbackValue = match[2]; let computed = getComputedStyle(/** @type {HTMLElement} */(target))?.getPropertyValue(cssVarName); // Use fallback if CSS variable is not set or empty if ((!computed || computed.trim() === emptyString) && fallbackValue) { computed = fallbackValue.trim(); } return computed || 0; } } else { return value; } if (store) store.func = func; return func(); } /** * @param {Target} target * @param {String} prop * @return {tweenTypes} */ export const getTweenType = (target, prop) => { return !target[isDomSymbol] ? tweenTypes.OBJECT : // Handle SVG attributes target[isSvgSymbol] && isValidSVGAttribute(target, prop) ? tweenTypes.ATTRIBUTE : // Handle CSS Transform properties differently than CSS to allow individual animations validTransforms.includes(prop) || shortTransforms.get(prop) ? tweenTypes.TRANSFORM : // CSS variables stringStartsWith(prop, '--') ? tweenTypes.CSS_VAR : // All other CSS properties prop in /** @type {DOMTarget} */(target).style ? tweenTypes.CSS : // Handle other DOM Attributes prop in target ? tweenTypes.OBJECT : tweenTypes.ATTRIBUTE; } /** * @param {DOMTarget} target * @param {String} propName * @param {Object} animationInlineStyles * @return {String} */ const getCSSValue = (target, propName, animationInlineStyles) => { const inlineStyles = target.style[propName]; if (inlineStyles && animationInlineStyles) { animationInlineStyles[propName] = inlineStyles; } const value = inlineStyles || getComputedStyle(target[proxyTargetSymbol] || target).getPropertyValue(propName); return value === 'auto' ? '0' : value; } /** * @param {Target} target * @param {String} propName * @param {tweenTypes} [tweenType] * @param {Object|void} [animationInlineStyles] * @return {String|Number} */ export const getOriginalAnimatableValue = (target, propName, tweenType, animationInlineStyles) => { const type = !isUnd(tweenType) ? tweenType : getTweenType(target, propName); return type === tweenTypes.OBJECT ? target[propName] || 0 : type === tweenTypes.ATTRIBUTE ? /** @type {DOMTarget} */(target).getAttribute(propName) : type === tweenTypes.TRANSFORM ? parseInlineTransforms(/** @type {DOMTarget} */(target), propName, animationInlineStyles) : type === tweenTypes.CSS_VAR ? getCSSValue(/** @type {DOMTarget} */(target), propName, animationInlineStyles).trimStart() : getCSSValue(/** @type {DOMTarget} */(target), propName, animationInlineStyles); } /** * @param {Number} x * @param {Number} y * @param {String} operator * @return {Number} */ export const getRelativeValue = (x, y, operator) => { return operator === '-' ? x - y : operator === '+' ? x + y : x * y; } /** @return {TweenDecomposedValue} */ export const createDecomposedValueTargetObject = () => { return { /** @type {valueTypes} */ t: valueTypes.NUMBER, n: 0, u: null, o: null, d: null, s: null, } } /** * @param {String|Number} rawValue * @param {TweenDecomposedValue} targetObject * @return {TweenDecomposedValue} */ export const decomposeRawValue = (rawValue, targetObject) => { /** @type {valueTypes} */ targetObject.t = valueTypes.NUMBER; targetObject.n = 0; targetObject.u = null; targetObject.o = null; targetObject.d = null; targetObject.s = null; if (!rawValue) return targetObject; const num = +rawValue; if (!isNaN(num)) { // It's a number targetObject.n = num; return targetObject; } else { // let str = /** @type {String} */(rawValue).trim(); let str = /** @type {String} */(rawValue); // Parsing operators (+=, -=, *=) manually is much faster than using regex here if (str[1] === '=') { targetObject.o = str[0]; str = str.slice(2); } // Skip exec regex if the value type is complex or color to avoid long regex backtracking const unitMatch = str.includes(' ') ? false : unitsExecRgx.exec(str); if (unitMatch) { // Has a number and a unit targetObject.t = valueTypes.UNIT; targetObject.n = +unitMatch[1]; targetObject.u = unitMatch[2]; return targetObject; } else if (targetObject.o) { // Has an operator (+=, -=, *=) targetObject.n = +str; return targetObject; } else if (isCol(str)) { // Is a color targetObject.t = valueTypes.COLOR; targetObject.d = convertColorStringValuesToRgbaArray(str); return targetObject; } else { // Is a more complex string (generally svg coords, calc() or filters CSS values) const matchedNumbers = str.match(digitWithExponentRgx); targetObject.t = valueTypes.COMPLEX; targetObject.d = matchedNumbers ? matchedNumbers.map(Number) : []; targetObject.s = str.split(digitWithExponentRgx) || []; return targetObject; } } } /** * @param {Tween} tween * @param {TweenDecomposedValue} targetObject * @return {TweenDecomposedValue} */ export const decomposeTweenValue = (tween, targetObject) => { targetObject.t = tween._valueType; targetObject.n = tween._toNumber; targetObject.u = tween._unit; targetObject.o = null; targetObject.d = cloneArray(tween._toNumbers); targetObject.s = cloneArray(tween._strings); return targetObject; } export const decomposedOriginalValue = createDecomposedValueTargetObject();
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/src/core/units.js
src/core/units.js
import { doc, valueTypes, } from './consts.js'; import { isUnd, PI } from './helpers.js'; const angleUnitsMap = { 'deg': 1, 'rad': 180 / PI, 'turn': 360 }; const convertedValuesCache = {}; /** * @import { * DOMTarget, * TweenDecomposedValue, * } from '../types/index.js' */ /** * @param {DOMTarget} el * @param {TweenDecomposedValue} decomposedValue * @param {String} unit * @param {Boolean} [force] * @return {TweenDecomposedValue} */ export const convertValueUnit = (el, decomposedValue, unit, force = false) => { const currentUnit = decomposedValue.u; const currentNumber = decomposedValue.n; if (decomposedValue.t === valueTypes.UNIT && currentUnit === unit) { // TODO: Check if checking against the same unit string is necessary return decomposedValue; } const cachedKey = currentNumber + currentUnit + unit; const cached = convertedValuesCache[cachedKey]; if (!isUnd(cached) && !force) { decomposedValue.n = cached; } else { let convertedValue; if (currentUnit in angleUnitsMap) { convertedValue = currentNumber * angleUnitsMap[currentUnit] / angleUnitsMap[unit]; } else { const baseline = 100; const tempEl = /** @type {DOMTarget} */(el.cloneNode()); const parentNode = el.parentNode; const parentEl = (parentNode && (parentNode !== doc)) ? parentNode : doc.body; parentEl.appendChild(tempEl); const elStyle = tempEl.style; elStyle.width = baseline + currentUnit; const currentUnitWidth = /** @type {HTMLElement} */(tempEl).offsetWidth || baseline; elStyle.width = baseline + unit; const newUnitWidth = /** @type {HTMLElement} */(tempEl).offsetWidth || baseline; const factor = currentUnitWidth / newUnitWidth; parentEl.removeChild(tempEl); convertedValue = factor * currentNumber; } decomposedValue.n = convertedValue; convertedValuesCache[cachedKey] = convertedValue; } decomposedValue.t === valueTypes.UNIT; decomposedValue.u = unit; return decomposedValue; }
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/src/timeline/timeline.js
src/timeline/timeline.js
import { globals, } from '../core/globals.js'; import { minValue, tickModes, compositionTypes, } from '../core/consts.js'; import { isObj, isFnc, isUnd, isNum, isStr, addChild, forEachChildren, mergeObjects, clampInfinity, normalizeTime, } from '../core/helpers.js'; import { setValue, } from '../core/values.js'; import { parseTargets, } from '../core/targets.js'; import { tick, } from '../core/render.js'; import { cleanInlineStyles, } from '../utils/target.js'; import { Timer, } from '../timer/timer.js'; import { removeTargetsFromRenderable, } from '../animation/composition.js'; import { JSAnimation, } from '../animation/animation.js'; import { parseEase, } from '../easings/eases/parser.js'; import { parseTimelinePosition, } from './position.js'; /** * @import { * TargetsParam, * Callback, * Tickable, * TimerParams, * AnimationParams, * Target, * Renderable, * TimelineParams, * DefaultsParams, * TimelinePosition, * StaggerFunction, * } from '../types/index.js' */ /** * @import { * WAAPIAnimation, * } from '../waapi/waapi.js' */ /** * @param {Timeline} tl * @return {Number} */ function getTimelineTotalDuration(tl) { return clampInfinity(((tl.iterationDuration + tl._loopDelay) * tl.iterationCount) - tl._loopDelay) || minValue; } /** * @overload * @param {TimerParams} childParams * @param {Timeline} tl * @param {Number} timePosition * @return {Timeline} * * @overload * @param {AnimationParams} childParams * @param {Timeline} tl * @param {Number} timePosition * @param {TargetsParam} targets * @param {Number} [index] * @param {Number} [length] * @return {Timeline} * * @param {TimerParams|AnimationParams} childParams * @param {Timeline} tl * @param {Number} timePosition * @param {TargetsParam} [targets] * @param {Number} [index] * @param {Number} [length] */ function addTlChild(childParams, tl, timePosition, targets, index, length) { const isSetter = isNum(childParams.duration) && /** @type {Number} */(childParams.duration) <= minValue; // Offset the tl position with -minValue for 0 duration animations or .set() calls in order to align their end value with the defined position const adjustedPosition = isSetter ? timePosition - minValue : timePosition; tick(tl, adjustedPosition, 1, 1, tickModes.AUTO); const tlChild = targets ? new JSAnimation(targets,/** @type {AnimationParams} */(childParams), tl, adjustedPosition, false, index, length) : new Timer(/** @type {TimerParams} */(childParams), tl, adjustedPosition); tlChild.init(true); // TODO: Might be better to insert at a position relative to startTime? addChild(tl, tlChild); forEachChildren(tl, (/** @type {Renderable} */child) => { const childTLOffset = child._offset + child._delay; const childDur = childTLOffset + child.duration; if (childDur > tl.iterationDuration) tl.iterationDuration = childDur; }); tl.duration = getTimelineTotalDuration(tl); return tl; } export class Timeline extends Timer { /** * @param {TimelineParams} [parameters] */ constructor(parameters = {}) { super(/** @type {TimerParams&TimelineParams} */(parameters), null, 0); /** @type {Number} */ this.duration = 0; // TL duration starts at 0 and grows when adding children /** @type {Record<String, Number>} */ this.labels = {}; const defaultsParams = parameters.defaults; const globalDefaults = globals.defaults; /** @type {DefaultsParams} */ this.defaults = defaultsParams ? mergeObjects(defaultsParams, globalDefaults) : globalDefaults; /** @type {Callback<this>} */ this.onRender = parameters.onRender || globalDefaults.onRender; const tlPlaybackEase = setValue(parameters.playbackEase, globalDefaults.playbackEase); this._ease = tlPlaybackEase ? parseEase(tlPlaybackEase) : null; /** @type {Number} */ this.iterationDuration = 0; } /** * @overload * @param {TargetsParam} a1 * @param {AnimationParams} a2 * @param {TimelinePosition|StaggerFunction<Number|String>} [a3] * @return {this} * * @overload * @param {TimerParams} a1 * @param {TimelinePosition} [a2] * @return {this} * * @param {TargetsParam|TimerParams} a1 * @param {TimelinePosition|AnimationParams} a2 * @param {TimelinePosition|StaggerFunction<Number|String>} [a3] */ add(a1, a2, a3) { const isAnim = isObj(a2); const isTimer = isObj(a1); if (isAnim || isTimer) { this._hasChildren = true; if (isAnim) { const childParams = /** @type {AnimationParams} */(a2); // Check for function for children stagger positions if (isFnc(a3)) { const staggeredPosition = a3; const parsedTargetsArray = parseTargets(/** @type {TargetsParam} */(a1)); // Store initial duration before adding new children that will change the duration const tlDuration = this.duration; // Store initial _iterationDuration before adding new children that will change the duration const tlIterationDuration = this.iterationDuration; // Store the original id in order to add specific indexes to the new animations ids const id = childParams.id; let i = 0; /** @type {Number} */ const parsedLength = (parsedTargetsArray.length); parsedTargetsArray.forEach((/** @type {Target} */target) => { // Create a new parameter object for each staggered children const staggeredChildParams = { ...childParams }; // Reset the duration of the timeline iteration before each stagger to prevent wrong start value calculation this.duration = tlDuration; this.iterationDuration = tlIterationDuration; if (!isUnd(id)) staggeredChildParams.id = id + '-' + i; addTlChild( staggeredChildParams, this, parseTimelinePosition(this, staggeredPosition(target, i, parsedLength, this)), target, i, parsedLength ); i++; }); } else { addTlChild( childParams, this, parseTimelinePosition(this, a3), /** @type {TargetsParam} */(a1), ); } } else { // It's a Timer addTlChild( /** @type TimerParams */(a1), this, parseTimelinePosition(this,a2), ); } return this.init(true); } } /** * @overload * @param {Tickable} [synced] * @param {TimelinePosition} [position] * @return {this} * * @overload * @param {globalThis.Animation} [synced] * @param {TimelinePosition} [position] * @return {this} * * @overload * @param {WAAPIAnimation} [synced] * @param {TimelinePosition} [position] * @return {this} * * @param {Tickable|WAAPIAnimation|globalThis.Animation} [synced] * @param {TimelinePosition} [position] */ sync(synced, position) { if (isUnd(synced) || synced && isUnd(synced.pause)) return this; synced.pause(); const duration = +(/** @type {globalThis.Animation} */(synced).effect ? /** @type {globalThis.Animation} */(synced).effect.getTiming().duration : /** @type {Tickable} */(synced).duration); return this.add(synced, { currentTime: [0, duration], duration, ease: 'linear' }, position); } /** * @param {TargetsParam} targets * @param {AnimationParams} parameters * @param {TimelinePosition} [position] * @return {this} */ set(targets, parameters, position) { if (isUnd(parameters)) return this; parameters.duration = minValue; parameters.composition = compositionTypes.replace; return this.add(targets, parameters, position); } /** * @param {Callback<Timer>} callback * @param {TimelinePosition} [position] * @return {this} */ call(callback, position) { if (isUnd(callback) || callback && !isFnc(callback)) return this; return this.add({ duration: 0, onComplete: () => callback(this) }, position); } /** * @param {String} labelName * @param {TimelinePosition} [position] * @return {this} * */ label(labelName, position) { if (isUnd(labelName) || labelName && !isStr(labelName)) return this; this.labels[labelName] = parseTimelinePosition(this, position); return this; } /** * @param {TargetsParam} targets * @param {String} [propertyName] * @return {this} */ remove(targets, propertyName) { removeTargetsFromRenderable(parseTargets(targets), this, propertyName); return this; } /** * @param {Number} newDuration * @return {this} */ stretch(newDuration) { const currentDuration = this.duration; if (currentDuration === normalizeTime(newDuration)) return this; const timeScale = newDuration / currentDuration; const labels = this.labels; forEachChildren(this, (/** @type {JSAnimation} */child) => child.stretch(child.duration * timeScale)); for (let labelName in labels) labels[labelName] *= timeScale; return super.stretch(newDuration); } /** * @return {this} */ refresh() { forEachChildren(this, (/** @type {JSAnimation} */child) => { if (child.refresh) child.refresh(); }); return this; } /** * @return {this} */ revert() { super.revert(); forEachChildren(this, (/** @type {JSAnimation} */child) => child.revert, true); return cleanInlineStyles(this); } /** * @typedef {this & {then: null}} ResolvedTimeline */ /** * @param {Callback<ResolvedTimeline>} [callback] * @return Promise<this> */ then(callback) { return super.then(callback); } } /** * @param {TimelineParams} [parameters] * @return {Timeline} */ export const createTimeline = parameters => new Timeline(parameters).init();
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/src/timeline/index.js
src/timeline/index.js
export * from './timeline.js';
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/src/timeline/position.js
src/timeline/position.js
import { minValue, relativeValuesExecRgx, } from "../core/consts.js"; import { isNil, isNum, isUnd, stringStartsWith, } from "../core/helpers.js"; import { getRelativeValue, } from "../core/values.js"; /** * @import { * Tickable, * TimelinePosition, * } from '../types/index.js' */ /** * @import { * Timeline, * } from './timeline.js' */ /** * Timeline's children offsets positions parser * @param {Timeline} timeline * @param {String} timePosition * @return {Number} */ const getPrevChildOffset = (timeline, timePosition) => { if (stringStartsWith(timePosition, '<')) { const goToPrevAnimationOffset = timePosition[1] === '<'; const prevAnimation = /** @type {Tickable} */(timeline._tail); const prevOffset = prevAnimation ? prevAnimation._offset + prevAnimation._delay : 0; return goToPrevAnimationOffset ? prevOffset : prevOffset + prevAnimation.duration; } } /** * @param {Timeline} timeline * @param {TimelinePosition} [timePosition] * @return {Number} */ export const parseTimelinePosition = (timeline, timePosition) => { let tlDuration = timeline.iterationDuration; if (tlDuration === minValue) tlDuration = 0; if (isUnd(timePosition)) return tlDuration; if (isNum(+timePosition)) return +timePosition; const timePosStr = /** @type {String} */(timePosition); const tlLabels = timeline ? timeline.labels : null; const hasLabels = !isNil(tlLabels); const prevOffset = getPrevChildOffset(timeline, timePosStr); const hasSibling = !isUnd(prevOffset); const matchedRelativeOperator = relativeValuesExecRgx.exec(timePosStr); if (matchedRelativeOperator) { const fullOperator = matchedRelativeOperator[0]; const split = timePosStr.split(fullOperator); const labelOffset = hasLabels && split[0] ? tlLabels[split[0]] : tlDuration; const parsedOffset = hasSibling ? prevOffset : hasLabels ? labelOffset : tlDuration; const parsedNumericalOffset = +split[1]; return getRelativeValue(parsedOffset, parsedNumericalOffset, fullOperator[0]); } else { return hasSibling ? prevOffset : hasLabels ? !isUnd(tlLabels[timePosStr]) ? tlLabels[timePosStr] : tlDuration : tlDuration; } }
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/src/engine/index.js
src/engine/index.js
export * from './engine.js';
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/src/engine/engine.js
src/engine/engine.js
import { defaults, globals, globalVersions, } from '../core/globals.js'; import { tickModes, isBrowser, K, doc, } from '../core/consts.js'; import { now, forEachChildren, removeChild, } from '../core/helpers.js'; import { Clock, } from '../core/clock.js'; import { tick, } from '../core/render.js'; import { additive, } from '../animation/additive.js'; /** * @import { * DefaultsParams, * } from '../types/index.js' */ /** * @import { * Tickable, * } from '../types/index.js' */ const engineTickMethod = /*#__PURE__*/ (() => isBrowser ? requestAnimationFrame : setImmediate)(); const engineCancelMethod = /*#__PURE__*/ (() => isBrowser ? cancelAnimationFrame : clearImmediate)(); class Engine extends Clock { /** @param {Number} [initTime] */ constructor(initTime) { super(initTime); this.useDefaultMainLoop = true; this.pauseOnDocumentHidden = true; /** @type {DefaultsParams} */ this.defaults = defaults; // this.paused = isBrowser && doc.hidden ? true : false; this.paused = true; /** @type {Number|NodeJS.Immediate} */ this.reqId = 0; } update() { const time = this._currentTime = now(); if (this.requestTick(time)) { this.computeDeltaTime(time); const engineSpeed = this._speed; const engineFps = this._fps; let activeTickable = /** @type {Tickable} */(this._head); while (activeTickable) { const nextTickable = activeTickable._next; if (!activeTickable.paused) { tick( activeTickable, (time - activeTickable._startTime) * activeTickable._speed * engineSpeed, 0, // !muteCallbacks 0, // !internalRender activeTickable._fps < engineFps ? activeTickable.requestTick(time) : tickModes.AUTO ); } else { removeChild(this, activeTickable); this._hasChildren = !!this._tail; activeTickable._running = false; if (activeTickable.completed && !activeTickable._cancelled) { activeTickable.cancel(); } } activeTickable = nextTickable; } additive.update(); } } wake() { if (this.useDefaultMainLoop && !this.reqId) { // Imediatly request a tick to update engine._elapsedTime and get accurate offsetPosition calculation in timer.js this.requestTick(now()); this.reqId = engineTickMethod(tickEngine); } return this; } pause() { if (!this.reqId) return; this.paused = true; return killEngine(); } resume() { if (!this.paused) return; this.paused = false; forEachChildren(this, (/** @type {Tickable} */child) => child.resetTime()); return this.wake(); } // Getter and setter for speed get speed() { return this._speed * (globals.timeScale === 1 ? 1 : K); } set speed(playbackRate) { this._speed = playbackRate * globals.timeScale; forEachChildren(this, (/** @type {Tickable} */child) => child.speed = child._speed); } // Getter and setter for timeUnit get timeUnit() { return globals.timeScale === 1 ? 'ms' : 's'; } set timeUnit(unit) { const secondsScale = 0.001; const isSecond = unit === 's'; const newScale = isSecond ? secondsScale : 1; if (globals.timeScale !== newScale) { globals.timeScale = newScale; globals.tickThreshold = 200 * newScale; const scaleFactor = isSecond ? secondsScale : K; /** @type {Number} */ (this.defaults.duration) *= scaleFactor; this._speed *= scaleFactor; } } // Getter and setter for precision get precision() { return globals.precision; } set precision(precision) { globals.precision = precision; } } export const engine = /*#__PURE__*/(() => { const engine = new Engine(now()); if (isBrowser) { globalVersions.engine = engine; doc.addEventListener('visibilitychange', () => { if (!engine.pauseOnDocumentHidden) return; doc.hidden ? engine.pause() : engine.resume(); }); } return engine; })(); const tickEngine = () => { if (engine._head) { engine.reqId = engineTickMethod(tickEngine); engine.update(); } else { engine.reqId = 0; } } const killEngine = () => { engineCancelMethod(/** @type {NodeJS.Immediate & Number} */(engine.reqId)); engine.reqId = 0; return engine; }
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/src/text/index.js
src/text/index.js
export * from './split.js';
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/src/text/split.js
src/text/split.js
import { doc, isBrowser, } from '../core/consts.js'; import { scope, } from '../core/globals.js'; import { isFnc, isNum, isStr, isObj, isUnd, isArr, } from '../core/helpers.js'; import { getNodeList, } from '../core/targets.js'; import { setValue, } from '../core/values.js'; import { keepTime, } from '../utils/time.js'; /** * @import { * Tickable, * DOMTarget, * SplitTemplateParams, * SplitFunctionValue, * TextSplitterParams, * } from '../types/index.js' */ const segmenter = (typeof Intl !== 'undefined') && Intl.Segmenter; const valueRgx = /\{value\}/g; const indexRgx = /\{i\}/g; const whiteSpaceGroupRgx = /(\s+)/; const whiteSpaceRgx = /^\s+$/; const lineType = 'line'; const wordType = 'word'; const charType = 'char'; const dataLine = `data-line`; /** * @typedef {Object} Segment * @property {String} segment * @property {Boolean} [isWordLike] */ /** * @typedef {Object} Segmenter * @property {function(String): Iterable<Segment>} segment */ /** @type {Segmenter} */ let wordSegmenter = null; /** @type {Segmenter} */ let graphemeSegmenter = null; let $splitTemplate = null; /** * @param {Segment} seg * @return {Boolean} */ const isSegmentWordLike = seg => { return seg.isWordLike || seg.segment === ' ' || // Consider spaces as words first, then handle them diffrently later isNum(+seg.segment); // Safari doesn't considers numbers as words } /** * @param {HTMLElement} $el */ const setAriaHidden = $el => $el.setAttribute('aria-hidden', 'true'); /** * @param {DOMTarget} $el * @param {String} type * @return {Array<HTMLElement>} */ const getAllTopLevelElements = ($el, type) => [.../** @type {*} */($el.querySelectorAll(`[data-${type}]:not([data-${type}] [data-${type}])`))]; const debugColors = { line: '#00D672', word: '#FF4B4B', char: '#5A87FF' }; /** * @param {HTMLElement} $el */ const filterEmptyElements = $el => { if (!$el.childElementCount && !$el.textContent.trim()) { const $parent = $el.parentElement; $el.remove(); if ($parent) filterEmptyElements($parent); } }; /** * @param {HTMLElement} $el * @param {Number} lineIndex * @param {Set<HTMLElement>} bin * @returns {Set<HTMLElement>} */ const filterLineElements = ($el, lineIndex, bin) => { const dataLineAttr = $el.getAttribute(dataLine); if (dataLineAttr !== null && +dataLineAttr !== lineIndex || $el.tagName === 'BR') bin.add($el); let i = $el.childElementCount; while (i--) filterLineElements(/** @type {HTMLElement} */($el.children[i]), lineIndex, bin); return bin; } /** * @param {'line'|'word'|'char'} type * @param {SplitTemplateParams} params * @return {String} */ const generateTemplate = (type, params = {}) => { let template = ``; const classString = isStr(params.class) ? ` class="${params.class}"` : ''; const cloneType = setValue(params.clone, false); const wrapType = setValue(params.wrap, false); const overflow = wrapType ? wrapType === true ? 'clip' : wrapType : cloneType ? 'clip' : false; if (wrapType) template += `<span${overflow ? ` style="overflow:${overflow};"` : ''}>`; template += `<span${classString}${cloneType ? ` style="position:relative;"` : ''} data-${type}="{i}">`; if (cloneType) { const left = cloneType === 'left' ? '-100%' : cloneType === 'right' ? '100%' : '0'; const top = cloneType === 'top' ? '-100%' : cloneType === 'bottom' ? '100%' : '0'; template += `<span>{value}</span>`; template += `<span inert style="position:absolute;top:${top};left:${left};white-space:nowrap;">{value}</span>`; } else { template += `{value}`; } template += `</span>`; if (wrapType) template += `</span>`; return template; } /** * @param {String|SplitFunctionValue} htmlTemplate * @param {Array<HTMLElement>} store * @param {Node|HTMLElement} node * @param {DocumentFragment} $parentFragment * @param {'line'|'word'|'char'} type * @param {Boolean} debug * @param {Number} lineIndex * @param {Number} [wordIndex] * @param {Number} [charIndex] * @return {HTMLElement} */ const processHTMLTemplate = (htmlTemplate, store, node, $parentFragment, type, debug, lineIndex, wordIndex, charIndex) => { const isLine = type === lineType; const isChar = type === charType; const className = `_${type}_`; const template = isFnc(htmlTemplate) ? htmlTemplate(node) : htmlTemplate; const displayStyle = isLine ? 'block' : 'inline-block'; $splitTemplate.innerHTML = template .replace(valueRgx, `<i class="${className}"></i>`) .replace(indexRgx, `${isChar ? charIndex : isLine ? lineIndex : wordIndex}`); const $content = $splitTemplate.content; const $highestParent = /** @type {HTMLElement} */($content.firstElementChild); const $split = /** @type {HTMLElement} */($content.querySelector(`[data-${type}]`)) || $highestParent; const $replacables = /** @type {NodeListOf<HTMLElement>} */($content.querySelectorAll(`i.${className}`)); const replacablesLength = $replacables.length; if (replacablesLength) { $highestParent.style.display = displayStyle; $split.style.display = displayStyle; $split.setAttribute(dataLine, `${lineIndex}`); if (!isLine) { $split.setAttribute('data-word', `${wordIndex}`); if (isChar) $split.setAttribute('data-char', `${charIndex}`); } let i = replacablesLength; while (i--) { const $replace = $replacables[i]; const $closestParent = $replace.parentElement; $closestParent.style.display = displayStyle; if (isLine) { $closestParent.innerHTML = /** @type {HTMLElement} */(node).innerHTML; } else { $closestParent.replaceChild(node.cloneNode(true), $replace); } } store.push($split); $parentFragment.appendChild($content); } else { console.warn(`The expression "{value}" is missing from the provided template.`); } if (debug) $highestParent.style.outline = `1px dotted ${debugColors[type]}`; return $highestParent; } /** * A class that splits text into words and wraps them in span elements while preserving the original HTML structure. * @class */ export class TextSplitter { /** * @param {HTMLElement|NodeList|String|Array<HTMLElement>} target * @param {TextSplitterParams} [parameters] */ constructor(target, parameters = {}) { // Only init segmenters when needed if (!wordSegmenter) wordSegmenter = segmenter ? new segmenter([], { granularity: wordType }) : { segment: (text) => { const segments = []; const words = text.split(whiteSpaceGroupRgx); for (let i = 0, l = words.length; i < l; i++) { const segment = words[i]; segments.push({ segment, isWordLike: !whiteSpaceRgx.test(segment), // Consider non-whitespace as word-like }); } return segments; } } if (!graphemeSegmenter) graphemeSegmenter = segmenter ? new segmenter([], { granularity: 'grapheme' }) : { segment: text => [...text].map(char => ({ segment: char })) } if (!$splitTemplate && isBrowser) $splitTemplate = doc.createElement('template'); if (scope.current) scope.current.register(this); const { words, chars, lines, accessible, includeSpaces, debug } = parameters; const $target = /** @type {HTMLElement} */((target = isArr(target) ? target[0] : target) && /** @type {Node} */(target).nodeType ? target : (getNodeList(target) || [])[0]); const lineParams = lines === true ? {} : lines; const wordParams = words === true || isUnd(words) ? {} : words; const charParams = chars === true ? {} : chars; this.debug = setValue(debug, false); this.includeSpaces = setValue(includeSpaces, false); this.accessible = setValue(accessible, true); this.linesOnly = lineParams && (!wordParams && !charParams); /** @type {String|false|SplitFunctionValue} */ this.lineTemplate = isObj(lineParams) ? generateTemplate(lineType, /** @type {SplitTemplateParams} */(lineParams)) : lineParams; /** @type {String|false|SplitFunctionValue} */ this.wordTemplate = isObj(wordParams) || this.linesOnly ? generateTemplate(wordType, /** @type {SplitTemplateParams} */(wordParams)) : wordParams; /** @type {String|false|SplitFunctionValue} */ this.charTemplate = isObj(charParams) ? generateTemplate(charType, /** @type {SplitTemplateParams} */(charParams)) : charParams; this.$target = $target; this.html = $target && $target.innerHTML; this.lines = []; this.words = []; this.chars = []; this.effects = []; this.effectsCleanups = []; this.cache = null; this.ready = false; this.width = 0; this.resizeTimeout = null; const handleSplit = () => this.html && (lineParams || wordParams || charParams) && this.split(); // Make sure this is declared before calling handleSplit() in case revert() is called inside an effect callback this.resizeObserver = new ResizeObserver(() => { // Use a setTimeout instead of a Timer for better tree shaking clearTimeout(this.resizeTimeout); this.resizeTimeout = setTimeout(() => { const currentWidth = /** @type {HTMLElement} */($target).offsetWidth; if (currentWidth === this.width) return; this.width = currentWidth; handleSplit(); }, 150); }); // Only declare the font ready promise when splitting by lines and not alreay split if (this.lineTemplate && !this.ready) { doc.fonts.ready.then(handleSplit); } else { handleSplit(); } $target ? this.resizeObserver.observe($target) : console.warn('No Text Splitter target found.'); } /** * @param {(...args: any[]) => Tickable | (() => void)} effect * @return this */ addEffect(effect) { if (!isFnc(effect)) return console.warn('Effect must return a function.'); const refreshableEffect = keepTime(effect); this.effects.push(refreshableEffect); if (this.ready) this.effectsCleanups[this.effects.length - 1] = refreshableEffect(this); return this; } revert() { clearTimeout(this.resizeTimeout); this.lines.length = this.words.length = this.chars.length = 0; this.resizeObserver.disconnect(); // Make sure to revert the effects after disconnecting the resizeObserver to avoid triggering it in the process this.effectsCleanups.forEach(cleanup => isFnc(cleanup) ? cleanup(this) : cleanup.revert && cleanup.revert()); this.$target.innerHTML = this.html; return this; } /** * Recursively processes a node and its children * @param {Node} node */ splitNode(node) { const wordTemplate = this.wordTemplate; const charTemplate = this.charTemplate; const includeSpaces = this.includeSpaces; const debug = this.debug; const nodeType = node.nodeType; if (nodeType === 3) { const nodeText = node.nodeValue; // If the nodeText is only whitespace, leave it as is if (nodeText.trim()) { const tempWords = []; const words = this.words; const chars = this.chars; const wordSegments = wordSegmenter.segment(nodeText); const $wordsFragment = doc.createDocumentFragment(); let prevSeg = null; for (const wordSegment of wordSegments) { const segment = wordSegment.segment; const isWordLike = isSegmentWordLike(wordSegment); // Determine if this segment should be a new word, first segment always becomes a new word if (!prevSeg || (isWordLike && (prevSeg && (isSegmentWordLike(prevSeg))))) { tempWords.push(segment); } else { // Only concatenate if both current and previous are non-word-like and don't contain spaces const lastWordIndex = tempWords.length - 1; const lastWord = tempWords[lastWordIndex]; if (!lastWord.includes(' ') && !segment.includes(' ')) { tempWords[lastWordIndex] += segment; } else { tempWords.push(segment); } } prevSeg = wordSegment; } for (let i = 0, l = tempWords.length; i < l; i++) { const word = tempWords[i]; if (!word.trim()) { // Preserve whitespace only if includeSpaces is false and if the current space is not the first node if (i && includeSpaces) continue; $wordsFragment.appendChild(doc.createTextNode(word)); } else { const nextWord = tempWords[i + 1]; const hasWordFollowingSpace = includeSpaces && nextWord && !nextWord.trim(); const wordToProcess = word; const charSegments = charTemplate ? graphemeSegmenter.segment(wordToProcess) : null; const $charsFragment = charTemplate ? doc.createDocumentFragment() : doc.createTextNode(hasWordFollowingSpace ? word + '\xa0' : word); if (charTemplate) { const charSegmentsArray = [...charSegments]; for (let j = 0, jl = charSegmentsArray.length; j < jl; j++) { const charSegment = charSegmentsArray[j]; const isLastChar = j === jl - 1; // If this is the last character and includeSpaces is true with a following space, append the space const charText = isLastChar && hasWordFollowingSpace ? charSegment.segment + '\xa0' : charSegment.segment; const $charNode = doc.createTextNode(charText); processHTMLTemplate(charTemplate, chars, $charNode, /** @type {DocumentFragment} */($charsFragment), charType, debug, -1, words.length, chars.length); } } if (wordTemplate) { processHTMLTemplate(wordTemplate, words, $charsFragment, $wordsFragment, wordType, debug, -1, words.length, chars.length); // Chars elements must be re-parsed in the split() method if both words and chars are parsed } else if (charTemplate) { $wordsFragment.appendChild($charsFragment); } else { $wordsFragment.appendChild(doc.createTextNode(word)); } // Skip the next iteration if we included a space if (hasWordFollowingSpace) i++; } } node.parentNode.replaceChild($wordsFragment, node); } } else if (nodeType === 1) { // Converting to an array is necessary to work around childNodes pottential mutation const childNodes = /** @type {Array<Node>} */([.../** @type {*} */(node.childNodes)]); for (let i = 0, l = childNodes.length; i < l; i++) this.splitNode(childNodes[i]); } } /** * @param {Boolean} clearCache * @return {this} */ split(clearCache = false) { const $el = this.$target; const isCached = !!this.cache && !clearCache; const lineTemplate = this.lineTemplate; const wordTemplate = this.wordTemplate; const charTemplate = this.charTemplate; const fontsReady = doc.fonts.status !== 'loading'; const canSplitLines = lineTemplate && fontsReady; this.ready = !lineTemplate || fontsReady; if (canSplitLines || clearCache) { // No need to revert effects animations here since it's already taken care by the refreshable this.effectsCleanups.forEach(cleanup => isFnc(cleanup) && cleanup(this)); } if (!isCached) { if (clearCache) { $el.innerHTML = this.html; this.words.length = this.chars.length = 0; } this.splitNode($el); this.cache = $el.innerHTML; } if (canSplitLines) { if (isCached) $el.innerHTML = this.cache; this.lines.length = 0; if (wordTemplate) this.words = getAllTopLevelElements($el, wordType); } // Always reparse characters after a line reset or if both words and chars are activated if (charTemplate && (canSplitLines || wordTemplate)) { this.chars = getAllTopLevelElements($el, charType); } // Words are used when lines only and prioritized over chars const elementsArray = this.words.length ? this.words : this.chars; let y, linesCount = 0; for (let i = 0, l = elementsArray.length; i < l; i++) { const $el = elementsArray[i]; const { top, height } = $el.getBoundingClientRect(); if (y && top - y > height * .5) linesCount++; $el.setAttribute(dataLine, `${linesCount}`); const nested = $el.querySelectorAll(`[${dataLine}]`); let c = nested.length; while (c--) nested[c].setAttribute(dataLine, `${linesCount}`); y = top; } if (canSplitLines) { const linesFragment = doc.createDocumentFragment(); const parents = new Set(); const clones = []; for (let lineIndex = 0; lineIndex < linesCount + 1; lineIndex++) { const $clone = /** @type {HTMLElement} */($el.cloneNode(true)); filterLineElements($clone, lineIndex, new Set()).forEach($el => { const $parent = $el.parentElement; if ($parent) parents.add($parent); $el.remove(); }); clones.push($clone); } parents.forEach(filterEmptyElements); for (let cloneIndex = 0, clonesLength = clones.length; cloneIndex < clonesLength; cloneIndex++) { processHTMLTemplate(lineTemplate, this.lines, clones[cloneIndex], linesFragment, lineType, this.debug, cloneIndex); } $el.innerHTML = ''; $el.appendChild(linesFragment); if (wordTemplate) this.words = getAllTopLevelElements($el, wordType); if (charTemplate) this.chars = getAllTopLevelElements($el, charType); } // Remove the word wrappers and clear the words array if lines split only if (this.linesOnly) { const words = this.words; let w = words.length; while (w--) { const $word = words[w]; $word.replaceWith($word.textContent); } words.length = 0; } if (this.accessible && (canSplitLines || !isCached)) { const $accessible = doc.createElement('span'); // Make the accessible element visually-hidden (https://www.scottohara.me/blog/2017/04/14/inclusively-hidden.html) $accessible.style.cssText = `position:absolute;overflow:hidden;clip:rect(0 0 0 0);clip-path:inset(50%);width:1px;height:1px;white-space:nowrap;`; // $accessible.setAttribute('tabindex', '-1'); $accessible.innerHTML = this.html; $el.insertBefore($accessible, $el.firstChild); this.lines.forEach(setAriaHidden); this.words.forEach(setAriaHidden); this.chars.forEach(setAriaHidden); } this.width = /** @type {HTMLElement} */($el).offsetWidth; if (canSplitLines || clearCache) { this.effects.forEach((effect, i) => this.effectsCleanups[i] = effect(this)); } return this; } refresh() { this.split(true); } } /** * @param {HTMLElement|NodeList|String|Array<HTMLElement>} target * @param {TextSplitterParams} [parameters] * @return {TextSplitter} */ export const splitText = (target, parameters) => new TextSplitter(target, parameters); /** * @deprecated text.split() is deprecated, import splitText() directly, or text.splitText() * * @param {HTMLElement|NodeList|String|Array<HTMLElement>} target * @param {TextSplitterParams} [parameters] * @return {TextSplitter} */ export const split = (target, parameters) => { console.warn('text.split() is deprecated, import splitText() directly, or text.splitText()'); return new TextSplitter(target, parameters); }
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/src/animation/additive.js
src/animation/additive.js
import { minValue, noop, valueTypes, tickModes, } from '../core/consts.js'; import { cloneArray, } from '../core/helpers.js'; import { render, } from '../core/render.js'; export const additive = { animation: null, update: noop, } /** * @import { * Tween, * TweenAdditiveLookups, * } from '../types/index.js' */ /** * @typedef AdditiveAnimation * @property {Number} duration * @property {Number} _offset * @property {Number} _delay * @property {Tween} _head * @property {Tween} _tail */ /** * @param {TweenAdditiveLookups} lookups * @return {AdditiveAnimation} */ export const addAdditiveAnimation = lookups => { let animation = additive.animation; if (!animation) { animation = { duration: minValue, computeDeltaTime: noop, _offset: 0, _delay: 0, _head: null, _tail: null, } additive.animation = animation; additive.update = () => { lookups.forEach(propertyAnimation => { for (let propertyName in propertyAnimation) { const tweens = propertyAnimation[propertyName]; const lookupTween = tweens._head; if (lookupTween) { const valueType = lookupTween._valueType; const additiveValues = valueType === valueTypes.COMPLEX || valueType === valueTypes.COLOR ? cloneArray(lookupTween._fromNumbers) : null; let additiveValue = lookupTween._fromNumber; let tween = tweens._tail; while (tween && tween !== lookupTween) { if (additiveValues) { for (let i = 0, l = tween._numbers.length; i < l; i++) additiveValues[i] += tween._numbers[i]; } else { additiveValue += tween._number; } tween = tween._prevAdd; } lookupTween._toNumber = additiveValue; lookupTween._toNumbers = additiveValues; } } }); // TODO: Avoid polymorphism here, idealy the additive animation should be a regular animation with a higher priority in the render loop render(animation, 1, 1, 0, tickModes.FORCE); } } return animation; }
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/src/animation/composition.js
src/animation/composition.js
import { compositionTypes, minValue, tweenTypes, } from '../core/consts.js'; import { cloneArray, addChild, removeChild, forEachChildren, round, isUnd, } from '../core/helpers.js'; import { sanitizePropertyName, } from '../core/styles.js'; import { engine, } from '../engine/engine.js'; import { additive, addAdditiveAnimation, } from './additive.js'; /** * @import { * TweenReplaceLookups, * TweenAdditiveLookups, * TweenPropertySiblings, * Tween, * Target, * TargetsArray, * Renderable, * } from '../types/index.js' * * @import { * JSAnimation, * } from '../animation/animation.js' */ const lookups = { /** @type {TweenReplaceLookups} */ _rep: new WeakMap(), /** @type {TweenAdditiveLookups} */ _add: new Map(), } /** * @param {Target} target * @param {String} property * @param {String} lookup * @return {TweenPropertySiblings} */ export const getTweenSiblings = (target, property, lookup = '_rep') => { const lookupMap = lookups[lookup]; let targetLookup = lookupMap.get(target); if (!targetLookup) { targetLookup = {}; lookupMap.set(target, targetLookup); } return targetLookup[property] ? targetLookup[property] : targetLookup[property] = { _head: null, _tail: null, } } /** * @param {Tween} p * @param {Tween} c * @return {Number|Boolean} */ const addTweenSortMethod = (p, c) => { return p._isOverridden || p._absoluteStartTime > c._absoluteStartTime; } /** * @param {Tween} tween */ export const overrideTween = tween => { tween._isOverlapped = 1; tween._isOverridden = 1; tween._changeDuration = minValue; tween._currentTime = minValue; } /** * @param {Tween} tween * @param {TweenPropertySiblings} siblings * @return {Tween} */ export const composeTween = (tween, siblings) => { const tweenCompositionType = tween._composition; // Handle replaced tweens if (tweenCompositionType === compositionTypes.replace) { const tweenAbsStartTime = tween._absoluteStartTime; addChild(siblings, tween, addTweenSortMethod, '_prevRep', '_nextRep'); const prevSibling = tween._prevRep; // Update the previous siblings for composition replace tweens if (prevSibling) { const prevParent = prevSibling.parent; const prevAbsEndTime = prevSibling._absoluteStartTime + prevSibling._changeDuration; // Handle looped animations tween if ( // Check if the previous tween is from a different animation tween.parent.id !== prevParent.id && // Check if the animation has loops prevParent.iterationCount> 1 && // Check if _absoluteChangeEndTime of last loop overlaps the current tween prevAbsEndTime + (prevParent.duration - prevParent.iterationDuration) > tweenAbsStartTime ) { // TODO: Find a way to only override the iterations overlapping with the tween overrideTween(prevSibling); let prevPrevSibling = prevSibling._prevRep; // If the tween was part of a set of keyframes, override its siblings while (prevPrevSibling && prevPrevSibling.parent.id === prevParent.id) { overrideTween(prevPrevSibling); prevPrevSibling = prevPrevSibling._prevRep; } } const absoluteUpdateStartTime = tweenAbsStartTime - tween._delay; if (prevAbsEndTime > absoluteUpdateStartTime) { const prevChangeStartTime = prevSibling._startTime; const prevTLOffset = prevAbsEndTime - (prevChangeStartTime + prevSibling._updateDuration); // Rounding is necessary here to minimize floating point errors when working in seconds const updatedPrevChangeDuration = round(absoluteUpdateStartTime - prevTLOffset - prevChangeStartTime, 12); prevSibling._changeDuration = updatedPrevChangeDuration; prevSibling._currentTime = updatedPrevChangeDuration; prevSibling._isOverlapped = 1; // Override the previous tween if its new _changeDuration is lower than minValue // TODO: See if it's even neceseeary to test against minValue, checking for 0 might be enough if (updatedPrevChangeDuration < minValue) { overrideTween(prevSibling); } } // Pause (and cancel) the parent if it only contains overlapped tweens let pausePrevParentAnimation = true; forEachChildren(prevParent, (/** @type Tween */t) => { if (!t._isOverlapped) pausePrevParentAnimation = false; }); if (pausePrevParentAnimation) { const prevParentTL = prevParent.parent; if (prevParentTL) { let pausePrevParentTL = true; forEachChildren(prevParentTL, (/** @type JSAnimation */a) => { if (a !== prevParent) { forEachChildren(a, (/** @type Tween */t) => { if (!t._isOverlapped) pausePrevParentTL = false; }); } }); if (pausePrevParentTL) { prevParentTL.cancel(); } } else { prevParent.cancel(); // Previously, calling .cancel() on a timeline child would affect the render order of other children // Worked around this by marking it as .completed and using .pause() for safe removal in the engine loop // This is no longer needed since timeline tween composition is now handled separately // Keeping this here for reference // prevParent.completed = true; // prevParent.pause(); } } } // let nextSibling = tween._nextRep; // // All the next siblings are automatically overridden // if (nextSibling && nextSibling._absoluteStartTime >= tweenAbsStartTime) { // while (nextSibling) { // overrideTween(nextSibling); // nextSibling = nextSibling._nextRep; // } // } // if (nextSibling && nextSibling._absoluteStartTime < tweenAbsStartTime) { // while (nextSibling) { // overrideTween(nextSibling); // console.log(tween.id, nextSibling.id); // nextSibling = nextSibling._nextRep; // } // } // Handle additive tweens composition } else if (tweenCompositionType === compositionTypes.blend) { const additiveTweenSiblings = getTweenSiblings(tween.target, tween.property, '_add'); const additiveAnimation = addAdditiveAnimation(lookups._add); let lookupTween = additiveTweenSiblings._head; if (!lookupTween) { lookupTween = { ...tween }; lookupTween._composition = compositionTypes.replace; lookupTween._updateDuration = minValue; lookupTween._startTime = 0; lookupTween._numbers = cloneArray(tween._fromNumbers); lookupTween._number = 0; lookupTween._next = null; lookupTween._prev = null; addChild(additiveTweenSiblings, lookupTween); addChild(additiveAnimation, lookupTween); } // Convert the values of TO to FROM and set TO to 0 const toNumber = tween._toNumber; tween._fromNumber = lookupTween._fromNumber - toNumber; tween._toNumber = 0; tween._numbers = cloneArray(tween._fromNumbers); tween._number = 0; lookupTween._fromNumber = toNumber; if (tween._toNumbers) { const toNumbers = cloneArray(tween._toNumbers); if (toNumbers) { toNumbers.forEach((value, i) => { tween._fromNumbers[i] = lookupTween._fromNumbers[i] - value; tween._toNumbers[i] = 0; }); } lookupTween._fromNumbers = toNumbers; } addChild(additiveTweenSiblings, tween, null, '_prevAdd', '_nextAdd'); } return tween; } /** * @param {Tween} tween * @return {Tween} */ export const removeTweenSliblings = tween => { const tweenComposition = tween._composition; if (tweenComposition !== compositionTypes.none) { const tweenTarget = tween.target; const tweenProperty = tween.property; const replaceTweensLookup = lookups._rep; const replaceTargetProps = replaceTweensLookup.get(tweenTarget); const tweenReplaceSiblings = replaceTargetProps[tweenProperty]; removeChild(tweenReplaceSiblings, tween, '_prevRep', '_nextRep'); if (tweenComposition === compositionTypes.blend) { const addTweensLookup = lookups._add; const addTargetProps = addTweensLookup.get(tweenTarget); if (!addTargetProps) return; const additiveTweenSiblings = addTargetProps[tweenProperty]; const additiveAnimation = additive.animation; removeChild(additiveTweenSiblings, tween, '_prevAdd', '_nextAdd'); // If only one tween is left in the additive lookup, it's the tween lookup const lookupTween = additiveTweenSiblings._head; if (lookupTween && lookupTween === additiveTweenSiblings._tail) { removeChild(additiveTweenSiblings, lookupTween, '_prevAdd', '_nextAdd'); removeChild(additiveAnimation, lookupTween); let shouldClean = true; for (let prop in addTargetProps) { if (addTargetProps[prop]._head) { shouldClean = false; break; } } if (shouldClean) { addTweensLookup.delete(tweenTarget); } } } } return tween; } /** * @param {TargetsArray} targetsArray * @param {JSAnimation} animation * @param {String} [propertyName] * @return {Boolean} */ const removeTargetsFromJSAnimation = (targetsArray, animation, propertyName) => { let tweensMatchesTargets = false; forEachChildren(animation, (/**@type {Tween} */tween) => { const tweenTarget = tween.target; if (targetsArray.includes(tweenTarget)) { const tweenName = tween.property; const tweenType = tween._tweenType; const normalizePropName = sanitizePropertyName(propertyName, tweenTarget, tweenType); if (!normalizePropName || normalizePropName && normalizePropName === tweenName) { // Make sure to flag the previous CSS transform tween to renderTransform if (tween.parent._tail === tween && tween._tweenType === tweenTypes.TRANSFORM && tween._prev && tween._prev._tweenType === tweenTypes.TRANSFORM ) { tween._prev._renderTransforms = 1; } // Removes the tween from the selected animation removeChild(animation, tween); // Detach the tween from its siblings to make sure blended tweens are correctlly removed removeTweenSliblings(tween); tweensMatchesTargets = true; } } }, true); return tweensMatchesTargets; } /** * @param {TargetsArray} targetsArray * @param {Renderable} [renderable] * @param {String} [propertyName] */ export const removeTargetsFromRenderable = (targetsArray, renderable, propertyName) => { const parent = /** @type {Renderable|typeof engine} **/(renderable ? renderable : engine); let removeMatches; if (parent._hasChildren) { let iterationDuration = 0; forEachChildren(parent, (/** @type {Renderable} */child) => { if (!child._hasChildren) { removeMatches = removeTargetsFromJSAnimation(targetsArray, /** @type {JSAnimation} */(child), propertyName); // Remove the child from its parent if no tweens and no children left after the removal if (removeMatches && !child._head) { child.cancel(); removeChild(parent, child); } else { // Calculate the new iterationDuration value to handle onComplete with last child in render() const childTLOffset = child._offset + child._delay; const childDur = childTLOffset + child.duration; if (childDur > iterationDuration) { iterationDuration = childDur; } } } // Make sure to also remove engine's children targets // NOTE: Avoid recursion? if (child._head) { removeTargetsFromRenderable(targetsArray, child, propertyName); } else { child._hasChildren = false; } }, true); // Update iterationDuration value to handle onComplete with last child in render() if (!isUnd(/** @type {Renderable} */(parent).iterationDuration)) { /** @type {Renderable} */(parent).iterationDuration = iterationDuration; } } else { removeMatches = removeTargetsFromJSAnimation( targetsArray, /** @type {JSAnimation} */(parent), propertyName ); } if (removeMatches && !parent._head) { parent._hasChildren = false; // Cancel the parent if there are no tweens and no children left after the removal // We have to check if the .cancel() method exist to handle cases where the parent is the engine itself if (/** @type {Renderable} */(parent).cancel) /** @type {Renderable} */(parent).cancel(); } }
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false
juliangarnier/anime
https://github.com/juliangarnier/anime/blob/b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d/src/animation/index.js
src/animation/index.js
export * from './animation.js';
javascript
MIT
b82b2c7fb54b7fda1d487e3aee885f70d4c1d46d
2026-01-04T14:56:49.711869Z
false