Skip to content

feat: support locale prop #60

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -13,7 +13,8 @@
"test": "vitest",
"package": "bun --run dlz",
"format": "bun --bun prettier --write . --cache",
"upgrade-examples": "bun scripts/upgrade-examples.ts"
"upgrade-examples": "bun scripts/upgrade-examples.ts",
"generate-locales": "bun scripts/generate-locales.ts"
},
"dependencies": {
"dayjs": "^1.11.13"
20 changes: 20 additions & 0 deletions scripts/generate-locales.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import localeDayjs from "dayjs/locale.json" with { type: "json" };
import { format } from "prettier";

const locales: string[] = [];

for (const { key, name } of localeDayjs) {
if (key === "en") {
locales.unshift(`'${key}'`);
} else {
locales.push(`'${key}'`);
}
}

const localesType = await format(
`/** @default "en" */\nexport type Locales = ${locales.join(" | ")};`,
{ parser: "typescript" },
);
Bun.write("src/locales.d.ts", localesType);

export {};
14 changes: 11 additions & 3 deletions src/Time.svelte
Original file line number Diff line number Diff line change
@@ -27,6 +27,12 @@
* @type {boolean | number}
*/
live = false,
/**
* The locale to use for formatting
* @type {import("./locales").Locales}
*/
locale = "en",
...rest
} = $props();
@@ -40,7 +46,7 @@
if (relative && live !== false) {
interval = setInterval(
() => {
formatted = dayjs(timestamp).from();
formatted = dayjs(timestamp).locale(locale).from(dayjs());
},
Math.abs(typeof live === "number" ? live : DEFAULT_INTERVAL),
);
@@ -54,11 +60,13 @@
* @type {string}
*/
let formatted = $state(
relative ? dayjs(timestamp).from() : dayjs(timestamp).format(format),
relative
? dayjs(timestamp).locale(locale).from(dayjs())
: dayjs(timestamp).locale(locale).format(format),
);
const title = $derived(
relative ? dayjs(timestamp).format(format) : undefined,
relative ? dayjs(timestamp).locale(locale).format(format) : undefined,
);
</script>

7 changes: 7 additions & 0 deletions src/Time.svelte.d.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { ConfigType, OptionType } from "dayjs";
import type { Component } from "svelte";
import type { SvelteHTMLElements } from "svelte/elements";
import type { Locales } from "./locales";

type RestProps = SvelteHTMLElements["time"];

@@ -33,6 +34,12 @@ export interface TimeProps extends RestProps {
*/
live?: boolean | number;

/**
* The locale to use for formatting
* @default "en"
*/
locale?: Locales;

/**
* Formatted timestamp.
* Result of invoking `dayjs().format()`
145 changes: 145 additions & 0 deletions src/locales.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
/** @default "en" */
export type Locales =
| "en"
| "af"
| "am"
| "ar-dz"
| "ar-iq"
| "ar-kw"
| "ar-ly"
| "ar-ma"
| "ar-sa"
| "ar-tn"
| "ar"
| "az"
| "be"
| "bg"
| "bi"
| "bm"
| "bn-bd"
| "bn"
| "bo"
| "br"
| "bs"
| "ca"
| "cs"
| "cv"
| "cy"
| "de-at"
| "da"
| "de-ch"
| "de"
| "dv"
| "el"
| "en-au"
| "en-ca"
| "en-gb"
| "en-ie"
| "en-il"
| "en-in"
| "en-nz"
| "en-sg"
| "en-tt"
| "eo"
| "es-do"
| "es-mx"
| "es-pr"
| "es-us"
| "et"
| "es"
| "eu"
| "fa"
| "fo"
| "fi"
| "fr-ca"
| "fr-ch"
| "fr"
| "fy"
| "ga"
| "gd"
| "gom-latn"
| "gl"
| "gu"
| "he"
| "hi"
| "hr"
| "hu"
| "ht"
| "hy-am"
| "id"
| "is"
| "it-ch"
| "it"
| "ja"
| "jv"
| "ka"
| "kk"
| "km"
| "kn"
| "ko"
| "ku"
| "ky"
| "lb"
| "lo"
| "lt"
| "lv"
| "me"
| "mi"
| "mk"
| "ml"
| "mn"
| "mr"
| "ms-my"
| "ms"
| "mt"
| "my"
| "nb"
| "ne"
| "nl-be"
| "nl"
| "pl"
| "pt-br"
| "pt"
| "rn"
| "ro"
| "ru"
| "rw"
| "sd"
| "se"
| "si"
| "sk"
| "sl"
| "sq"
| "sr-cyrl"
| "ss"
| "sv-fi"
| "sr"
| "sv"
| "sw"
| "ta"
| "te"
| "tet"
| "tg"
| "th"
| "tk"
| "tl-ph"
| "tlh"
| "tr"
| "tzl"
| "tzm-latn"
| "tzm"
| "ug-cn"
| "uk"
| "ur"
| "uz-latn"
| "uz"
| "vi"
| "x-pseudo"
| "yo"
| "zh-cn"
| "zh-hk"
| "zh-tw"
| "zh"
| "oc-lnc"
| "nn"
| "pa-in";
2 changes: 1 addition & 1 deletion src/svelte-time.svelte.d.ts
Original file line number Diff line number Diff line change
@@ -4,7 +4,7 @@ import type { TimeProps } from "./Time.svelte";
export interface SvelteTimeOptions
extends Pick<
TimeProps,
"timestamp" | "format" | "relative" | "live" | "title"
"timestamp" | "format" | "relative" | "live" | "title" | "locale"
> {}

export const svelteTime: Action<
7 changes: 4 additions & 3 deletions src/svelte-time.svelte.js
Original file line number Diff line number Diff line change
@@ -17,9 +17,10 @@ export const svelteTime = (node, options = {}) => {
const format = options.format || "MMM DD, YYYY";
const relative = options.relative === true;
const live = options.live ?? false;
const locale = options.locale ?? "en";

let formatted_from = dayjs(timestamp).from();
let formatted = dayjs(timestamp).format(format);
let formatted_from = dayjs(timestamp).locale(locale).from();
let formatted = dayjs(timestamp).locale(locale).format(format);

if (relative) {
if ("title" in options) {
@@ -33,7 +34,7 @@ export const svelteTime = (node, options = {}) => {
if (live !== false) {
interval = setInterval(
() => {
node.innerText = dayjs(timestamp).from();
node.innerText = dayjs(timestamp).locale(locale).from();
},
Math.abs(typeof live === "number" ? live : DEFAULT_INTERVAL),
);
117 changes: 117 additions & 0 deletions tests/SvelteTimeLocale.test.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
<script lang="ts">
import Time, { svelteTime } from "svelte-time";
import dayjs from "dayjs";
import "dayjs/locale/de"; // German
import "dayjs/locale/es"; // Spanish
import "dayjs/locale/fr"; // French
import "dayjs/locale/ja"; // Japanese
const fixedDate = "2024-01-01T12:00:00.000Z";
// Pre-format dates with locales
const germanDate = dayjs(fixedDate).locale("de").format("dddd, D. MMMM YYYY");
const spanishDate = dayjs(fixedDate)
.locale("es")
.format("dddd, D [de] MMMM [de] YYYY");
const frenchDate = dayjs(fixedDate).locale("fr").format("dddd D MMMM YYYY");
const japaneseDate = dayjs(fixedDate)
.locale("ja")
.format("YYYY年M月D日(dddd)");
</script>

<!-- German Locale -->
<Time
data-test="german-full"
timestamp={fixedDate}
format="dddd, D. MMMM YYYY"
locale="de"
/>

<span data-test="german-formatted">{germanDate}</span>

<Time
data-test="german-short"
timestamp={fixedDate}
format="dd., D. MMM YYYY"
locale="de"
/>

<Time
data-test="german-month-year"
timestamp={fixedDate}
format="MMMM YYYY"
locale="de"
/>

<!-- Spanish Locale -->
<Time
data-test="spanish-full"
timestamp={fixedDate}
format="dddd, D [de] MMMM [de] YYYY"
locale="es"
/>

<span data-test="spanish-formatted">{spanishDate}</span>

<Time
data-test="spanish-short"
timestamp={fixedDate}
format="dd., D MMM YYYY"
locale="es"
/>

<!-- French Locale -->
<Time
data-test="french-full"
timestamp={fixedDate}
format="dddd D MMMM YYYY"
locale="fr"
/>

<span data-test="french-formatted">{frenchDate}</span>

<Time
data-test="french-short"
timestamp={fixedDate}
format="dd. D MMM YYYY"
locale="fr"
/>

<!-- Japanese Locale -->
<Time
data-test="japanese-full"
timestamp={fixedDate}
format="YYYY年M月D日(dddd)"
locale="ja"
/>

<span data-test="japanese-formatted">{japaneseDate}</span>

<Time
data-test="japanese-short"
timestamp={fixedDate}
format="YYYY年M月D日"
locale="ja"
/>

<!-- Relative Time in Different Locales -->
<Time data-test="german-relative" timestamp={fixedDate} relative locale="de" />

<Time data-test="spanish-relative" timestamp={fixedDate} relative locale="es" />

<Time data-test="french-relative" timestamp={fixedDate} relative locale="fr" />

<Time
data-test="japanese-relative"
timestamp={fixedDate}
relative
locale="ja"
/>

<time data-test="action-locale-es" use:svelteTime={{ locale: "es" }}></time>

<time data-test="action-locale-fr" use:svelteTime={{ locale: "fr" }}></time>

<time data-test="action-locale-ja" use:svelteTime={{ locale: "ja" }}></time>

<time data-test="action-locale-de" use:svelteTime={{ locale: "de" }}></time>
160 changes: 160 additions & 0 deletions tests/SvelteTimeLocale.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
import dayjs from "dayjs";
import "dayjs/locale/de"; // German
import "dayjs/locale/es"; // Spanish
import "dayjs/locale/fr"; // French
import "dayjs/locale/ja"; // Japanese
import relativeTime from "dayjs/plugin/relativeTime";
import { mount, tick, unmount } from "svelte";
import SvelteTimeLocale from "./SvelteTimeLocale.test.svelte";

// Extend dayjs with required plugins
dayjs.extend(relativeTime);

describe("svelte-time-locale", () => {
let instance: null | Record<string, any> = null;
const FIXED_DATE = new Date("2024-01-01T12:00:00.000Z");

beforeEach(() => {
vi.useFakeTimers();
vi.setSystemTime(FIXED_DATE);
});

afterEach(() => {
vi.restoreAllMocks();
if (instance) {
unmount(instance);
}
instance = null;
document.body.innerHTML = "";
});

const getElement = (selector: string) => {
return document.querySelector(selector) as HTMLElement;
};

test("handles German locale formatting", async () => {
const target = document.body;
instance = mount(SvelteTimeLocale, { target });

// Full format
const germanFull = getElement('[data-test="german-full"]');
const germanFormatted = getElement('[data-test="german-formatted"]');
expect(germanFull.innerHTML).toEqual(germanFormatted.innerHTML);

// Short format
const germanShort = getElement('[data-test="german-short"]');
expect(germanShort.innerHTML).toEqual(
dayjs(FIXED_DATE).locale("de").format("dd., D. MMM YYYY"),
);

// Month year format
const germanMonthYear = getElement('[data-test="german-month-year"]');
expect(germanMonthYear.innerHTML).toEqual(
dayjs(FIXED_DATE).locale("de").format("MMMM YYYY"),
);
});

test("handles Spanish locale formatting", async () => {
const target = document.body;
instance = mount(SvelteTimeLocale, { target });

// Full format
const spanishFull = getElement('[data-test="spanish-full"]');
const spanishFormatted = getElement('[data-test="spanish-formatted"]');
expect(spanishFull.innerHTML).toEqual(spanishFormatted.innerHTML);

// Short format
const spanishShort = getElement('[data-test="spanish-short"]');
expect(spanishShort.innerHTML).toEqual(
dayjs(FIXED_DATE).locale("es").format("dd., D MMM YYYY"),
);
});

test("handles French locale formatting", async () => {
const target = document.body;
instance = mount(SvelteTimeLocale, { target });

// Full format
const frenchFull = getElement('[data-test="french-full"]');
const frenchFormatted = getElement('[data-test="french-formatted"]');
expect(frenchFull.innerHTML).toEqual(frenchFormatted.innerHTML);

// Short format
const frenchShort = getElement('[data-test="french-short"]');
expect(frenchShort.innerHTML).toEqual(
dayjs(FIXED_DATE).locale("fr").format("dd. D MMM YYYY"),
);
});

test("handles Japanese locale formatting", async () => {
const target = document.body;
instance = mount(SvelteTimeLocale, { target });

// Full format
const japaneseFull = getElement('[data-test="japanese-full"]');
const japaneseFormatted = getElement('[data-test="japanese-formatted"]');
expect(japaneseFull.innerHTML).toEqual(japaneseFormatted.innerHTML);

// Short format
const japaneseShort = getElement('[data-test="japanese-short"]');
expect(japaneseShort.innerHTML).toEqual(
dayjs(FIXED_DATE).locale("ja").format("YYYY年M月D日"),
);
});

test("handles relative time in different locales", async () => {
const target = document.body;
instance = mount(SvelteTimeLocale, { target });

// German relative time
const germanRelative = getElement('[data-test="german-relative"]');
expect(germanRelative.innerHTML).toEqual(
dayjs(FIXED_DATE).locale("de").fromNow(),
);

// Spanish relative time
const spanishRelative = getElement('[data-test="spanish-relative"]');
expect(spanishRelative.innerHTML).toEqual(
dayjs(FIXED_DATE).locale("es").fromNow(),
);

// French relative time
const frenchRelative = getElement('[data-test="french-relative"]');
expect(frenchRelative.innerHTML).toEqual(
dayjs(FIXED_DATE).locale("fr").fromNow(),
);

// Japanese relative time
const japaneseRelative = getElement('[data-test="japanese-relative"]');
expect(japaneseRelative.innerHTML).toEqual(
dayjs(FIXED_DATE).locale("ja").fromNow(),
);
});

test("handles action locale formatting", async () => {
const target = document.body;
instance = mount(SvelteTimeLocale, { target });

await tick();

const actionLocaleEs = getElement('[data-test="action-locale-es"]');
expect(actionLocaleEs.innerText).toEqual(
dayjs().locale("es").format("MMM DD, YYYY"),
);

const actionLocaleFr = getElement('[data-test="action-locale-fr"]');
expect(actionLocaleFr.innerText).toEqual(
dayjs().locale("fr").format("MMM DD, YYYY"),
);

const actionLocaleJa = getElement('[data-test="action-locale-ja"]');
expect(actionLocaleJa.innerText).toEqual(
dayjs().locale("ja").format("MMM DD, YYYY"),
);

const actionLocaleDe = getElement('[data-test="action-locale-de"]');
expect(actionLocaleDe.innerText).toEqual(
dayjs().locale("de").format("MMM DD, YYYY"),
);
});
});