@edenapp/solid-kit 0.15.2 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,40 @@
1
+ import { setupI18n } from "@edenapp/babel/solid";
2
+ import { afterEach, describe, expect, it, vi } from "vitest";
3
+ import { fillString, solidKitStrings } from "./locale.js";
4
+
5
+ const app = setupI18n({
6
+ resources: {
7
+ en: { translation: { solidKit: { dialogs: { cancel: "Back" } } } },
8
+ de: {
9
+ translation: {
10
+ solidKit: {
11
+ dialogs: { cancel: "Abbrechen" },
12
+ sidebar: { expand: "Ausklappen" },
13
+ },
14
+ },
15
+ },
16
+ },
17
+ });
18
+
19
+ describe("solid-kit strings", () => {
20
+ afterEach(() => app.setLocale("en"));
21
+
22
+ it("prefers the app's translation, then solid-kit's, then English", async () => {
23
+ app.setLocale("de-AT");
24
+ await vi.waitFor(() =>
25
+ expect(solidKitStrings("dialogs").cancel).toBe("Abbrechen"),
26
+ );
27
+ expect(solidKitStrings("sidebar").expand).toBe("Ausklappen");
28
+ expect(solidKitStrings("sidebar").collapse).toBe("Collapse sidebar");
29
+
30
+ // The app's English override is not used for Polish, which solid-kit has.
31
+ app.setLocale("pl-PL");
32
+ expect(solidKitStrings("dialogs").cancel).toBe("Anuluj");
33
+ });
34
+
35
+ it("fills named values and leaves unknown ones", () => {
36
+ expect(fillString("{count} more of {name}", { count: 2 })).toBe(
37
+ "2 more of {name}",
38
+ );
39
+ });
40
+ });
package/src/locale.ts ADDED
@@ -0,0 +1,79 @@
1
+ import { appI18n } from "@edenapp/babel/solid";
2
+ import { en, type SolidKitStrings } from "./locales/en.js";
3
+ import { pl } from "./locales/pl.js";
4
+
5
+ export type { SolidKitStrings };
6
+
7
+ export type DeepPartial<T> = {
8
+ [K in keyof T]?: T[K] extends string ? T[K] : DeepPartial<T[K]>;
9
+ };
10
+
11
+ /**
12
+ * The keys an app can put in its own locale files to replace solid-kit's
13
+ * strings, such as `solidKit.dialogs.cancel`.
14
+ */
15
+ export interface SolidKitTranslations {
16
+ solidKit?: DeepPartial<SolidKitStrings>;
17
+ }
18
+
19
+ const builtIn: Record<string, SolidKitStrings> = { en, pl };
20
+
21
+ /** The app's locale from `@edenapp/babel/solid`, or English without one. */
22
+ export function solidKitLocale(): string {
23
+ return appI18n()?.locale() ?? "en";
24
+ }
25
+
26
+ /**
27
+ * One component's strings for the app's locale. Each is the app's translation
28
+ * under `solidKit.`, else solid-kit's for that locale or its language, else
29
+ * English. Read it in a reactive scope to follow locale changes.
30
+ */
31
+ export function solidKitStrings<G extends keyof SolidKitStrings>(
32
+ group: G,
33
+ ): SolidKitStrings[G] {
34
+ const app = appI18n();
35
+ const value = solidKitLocale();
36
+ const own = builtIn[value] ?? builtIn[value.split("-")[0]] ?? en;
37
+ const resolve = (
38
+ english: object,
39
+ local: object | undefined,
40
+ path: string,
41
+ ): object =>
42
+ Object.fromEntries(
43
+ Object.entries(english).map(([key, fallback]) => {
44
+ const at = (from: object | undefined) =>
45
+ (from as Record<string, unknown> | undefined)?.[key];
46
+ if (typeof fallback === "object") {
47
+ return [
48
+ key,
49
+ resolve(
50
+ fallback,
51
+ at(local) as object | undefined,
52
+ `${path}.${key}`,
53
+ ),
54
+ ];
55
+ }
56
+ return [
57
+ key,
58
+ app?.find(`${path}.${key}`) ??
59
+ (at(local) as string | undefined) ??
60
+ fallback,
61
+ ];
62
+ }),
63
+ );
64
+ return resolve(
65
+ en[group],
66
+ own[group],
67
+ `solidKit.${group}`,
68
+ ) as SolidKitStrings[G];
69
+ }
70
+
71
+ /** `template` with each `{name}` replaced by its value. */
72
+ export function fillString(
73
+ template: string,
74
+ values: Record<string, string | number>,
75
+ ): string {
76
+ return template.replace(/\{(\w+)\}/g, (match, name: string) =>
77
+ name in values ? String(values[name]) : match,
78
+ );
79
+ }
@@ -0,0 +1,36 @@
1
+ import type { DateTimeUnit } from "../datetime/DateTimeField.js";
2
+
3
+ /** Every string solid-kit components show, grouped by component. */
4
+ export interface SolidKitStrings {
5
+ datetime: {
6
+ unit: Record<DateTimeUnit, string>;
7
+ earlier: Record<DateTimeUnit, string>;
8
+ later: Record<DateTimeUnit, string>;
9
+ done: string;
10
+ };
11
+ dialogs: { ok: string; cancel: string };
12
+ keyboard: { toggle: string };
13
+ notices: { dismiss: string; showMore: string; showLess: string };
14
+ sidebar: { collapse: string; expand: string };
15
+ }
16
+
17
+ export const en: SolidKitStrings = {
18
+ datetime: {
19
+ unit: { day: "Day", hour: "Hour", minute: "Minute" },
20
+ earlier: {
21
+ day: "Earlier day",
22
+ hour: "Earlier hour",
23
+ minute: "Earlier minute",
24
+ },
25
+ later: { day: "Later day", hour: "Later hour", minute: "Later minute" },
26
+ done: "Done",
27
+ },
28
+ dialogs: { ok: "OK", cancel: "Cancel" },
29
+ keyboard: { toggle: "Toggle keyboard" },
30
+ notices: {
31
+ dismiss: "Dismiss",
32
+ showMore: "{count} more",
33
+ showLess: "Show less",
34
+ },
35
+ sidebar: { collapse: "Collapse sidebar", expand: "Expand sidebar" },
36
+ };
@@ -0,0 +1,26 @@
1
+ import type { SolidKitStrings } from "./en.js";
2
+
3
+ export const pl: SolidKitStrings = {
4
+ datetime: {
5
+ unit: { day: "Dzień", hour: "Godzina", minute: "Minuta" },
6
+ earlier: {
7
+ day: "Wcześniejszy dzień",
8
+ hour: "Wcześniejsza godzina",
9
+ minute: "Wcześniejsza minuta",
10
+ },
11
+ later: {
12
+ day: "Późniejszy dzień",
13
+ hour: "Późniejsza godzina",
14
+ minute: "Późniejsza minuta",
15
+ },
16
+ done: "Gotowe",
17
+ },
18
+ dialogs: { ok: "OK", cancel: "Anuluj" },
19
+ keyboard: { toggle: "Przełącz klawiaturę" },
20
+ notices: {
21
+ dismiss: "Zamknij",
22
+ showMore: "Więcej: {count}",
23
+ showLess: "Pokaż mniej",
24
+ },
25
+ sidebar: { collapse: "Zwiń pasek boczny", expand: "Rozwiń pasek boczny" },
26
+ };
@@ -0,0 +1,120 @@
1
+ import { setupI18n } from "@edenapp/babel/solid";
2
+ import {
3
+ cleanup,
4
+ fireEvent,
5
+ render,
6
+ screen,
7
+ within,
8
+ } from "@solidjs/testing-library";
9
+ import { createSignal, onMount } from "solid-js";
10
+ import { afterEach, describe, expect, it } from "vitest";
11
+ import type { Notices } from "./createNotices.js";
12
+ import { NoticeProvider, useNotices } from "./NoticeProvider.js";
13
+
14
+ const app = setupI18n({ resources: {} });
15
+
16
+ describe("NoticeProvider", () => {
17
+ afterEach(() => {
18
+ cleanup();
19
+ app.setLocale("en");
20
+ });
21
+
22
+ it("announces danger as an alert and others politely, lets the user dismiss them, and hides extra notices", () => {
23
+ function Reporter() {
24
+ const notices = useNotices();
25
+ onMount(() => {
26
+ for (const title of ["a", "b", "c", "d"]) {
27
+ notices.report({ severity: "warning", title });
28
+ }
29
+ notices.report({ severity: "danger", title: "write failed" });
30
+ });
31
+ return null;
32
+ }
33
+
34
+ render(() => (
35
+ <NoticeProvider>
36
+ <Reporter />
37
+ </NoticeProvider>
38
+ ));
39
+
40
+ expect(screen.getByRole("alert").textContent).toContain("write failed");
41
+ const announced = within(screen.getByRole("status"));
42
+ expect(announced.getByText("d")).toBeTruthy();
43
+ expect(announced.getByText("c")).toBeTruthy();
44
+ expect(announced.queryByText("b")).toBeNull();
45
+
46
+ fireEvent.click(screen.getByRole("button", { name: "2 more" }));
47
+ expect(announced.getByText("b")).toBeTruthy();
48
+ expect(announced.getByText("a")).toBeTruthy();
49
+
50
+ const dismissButtons = screen.getAllByRole("button", { name: "Dismiss" });
51
+ fireEvent.click(dismissButtons[0]);
52
+ expect(screen.queryByRole("alert")).toBeNull();
53
+ });
54
+
55
+ it("keeps focus on the dismiss button when a keyed notice is replaced", () => {
56
+ let notices!: Notices;
57
+ function Reporter() {
58
+ notices = useNotices();
59
+ return null;
60
+ }
61
+
62
+ render(() => (
63
+ <NoticeProvider>
64
+ <Reporter />
65
+ </NoticeProvider>
66
+ ));
67
+
68
+ notices.report({ severity: "warning", title: "limit", key: "feed" });
69
+ notices.report({ severity: "warning", title: "speed" });
70
+ const [, dismiss] = screen.getAllByRole("button", { name: "Dismiss" });
71
+ dismiss.focus();
72
+ notices.report({ severity: "warning", title: "limit again", key: "feed" });
73
+
74
+ expect(screen.getByText("limit again")).toBeTruthy();
75
+ expect(document.activeElement).toBe(dismiss);
76
+ expect(screen.getAllByRole("button", { name: "Dismiss" })[1]).toBe(dismiss);
77
+ });
78
+
79
+ it("gives condition notices no dismiss button", () => {
80
+ function Condition() {
81
+ const [offline] = createSignal(true);
82
+ useNotices().condition(offline, {
83
+ severity: "warning",
84
+ title: "offline",
85
+ });
86
+ return null;
87
+ }
88
+
89
+ render(() => (
90
+ <NoticeProvider>
91
+ <Condition />
92
+ </NoticeProvider>
93
+ ));
94
+
95
+ expect(screen.getByRole("status").textContent).toContain("offline");
96
+ expect(screen.queryByRole("button", { name: "Dismiss" })).toBeNull();
97
+ });
98
+
99
+ it("labels its controls in the app's language", () => {
100
+ app.setLocale("pl");
101
+ function Reporter() {
102
+ const notices = useNotices();
103
+ onMount(() => {
104
+ for (const title of ["a", "b", "c", "d"]) {
105
+ notices.report({ severity: "warning", title });
106
+ }
107
+ });
108
+ return null;
109
+ }
110
+
111
+ render(() => (
112
+ <NoticeProvider>
113
+ <Reporter />
114
+ </NoticeProvider>
115
+ ));
116
+
117
+ expect(screen.getByRole("button", { name: "Więcej: 1" })).toBeTruthy();
118
+ expect(screen.getAllByRole("button", { name: "Zamknij" })).toHaveLength(3);
119
+ });
120
+ });
@@ -0,0 +1,29 @@
1
+ import { createContext, type JSX, useContext } from "solid-js";
2
+ import { createNotices, type Notices } from "./createNotices.js";
3
+ import { NoticeRegion } from "./NoticeRegion.js";
4
+
5
+ const NoticesContext = createContext<Notices>();
6
+
7
+ export interface NoticeProviderProps {
8
+ autoHideMs?: number;
9
+ children: JSX.Element;
10
+ }
11
+
12
+ /** Provides notice state to the app and shows its notices at the top centre. */
13
+ export function NoticeProvider(props: NoticeProviderProps) {
14
+ const notices = createNotices({ autoHideMs: props.autoHideMs });
15
+ return (
16
+ <NoticesContext.Provider value={notices}>
17
+ {props.children}
18
+ <NoticeRegion notices={notices} />
19
+ </NoticesContext.Provider>
20
+ );
21
+ }
22
+
23
+ export function useNotices(): Notices {
24
+ const notices = useContext(NoticesContext);
25
+ if (!notices) {
26
+ throw new Error("useNotices must be used inside NoticeProvider");
27
+ }
28
+ return notices;
29
+ }
@@ -0,0 +1,118 @@
1
+ import type { IconTypes } from "solid-icons";
2
+ import {
3
+ FiAlertOctagon,
4
+ FiAlertTriangle,
5
+ FiCheckCircle,
6
+ FiInfo,
7
+ FiX,
8
+ } from "solid-icons/fi";
9
+ import { createEffect, createMemo, createSignal, For, Show } from "solid-js";
10
+ import { Dynamic } from "solid-js/web";
11
+ import { fillString, solidKitStrings } from "../locale.js";
12
+ import type { Notice, NoticeSeverity, Notices } from "./createNotices.js";
13
+
14
+ export const NOTICE_MAX_VISIBLE = 3;
15
+
16
+ const severityIcons: Record<NoticeSeverity, IconTypes> = {
17
+ danger: FiAlertOctagon,
18
+ warning: FiAlertTriangle,
19
+ info: FiInfo,
20
+ success: FiCheckCircle,
21
+ };
22
+
23
+ function NoticeItem(props: {
24
+ notice: Notice;
25
+ dismiss: string;
26
+ onDismiss: (id: string) => void;
27
+ }) {
28
+ // Most screen readers announce an alert inserted into the page. Other
29
+ // notices are announced by the polite live region that contains them.
30
+ return (
31
+ <div
32
+ class={`eden-notice eden-notice-${props.notice.severity}`}
33
+ role={props.notice.severity === "danger" ? "alert" : undefined}
34
+ >
35
+ <span class="eden-notice-icon" aria-hidden="true">
36
+ <Dynamic component={severityIcons[props.notice.severity]} size={18} />
37
+ </span>
38
+ <div class="eden-notice-content">
39
+ <div class="eden-notice-title">
40
+ <span>{props.notice.title}</span>
41
+ <Show when={props.notice.count > 1}>
42
+ <span class="eden-badge eden-notice-count">
43
+ ×{props.notice.count}
44
+ </span>
45
+ </Show>
46
+ </div>
47
+ <Show when={props.notice.detail}>
48
+ <div class="eden-notice-detail">{props.notice.detail}</div>
49
+ </Show>
50
+ </div>
51
+ <Show when={props.notice.kind === "event"}>
52
+ <button
53
+ type="button"
54
+ class="eden-btn eden-btn-ghost eden-btn-sm eden-btn-square eden-notice-dismiss"
55
+ aria-label={props.dismiss}
56
+ title={props.dismiss}
57
+ onClick={() => props.onDismiss(props.notice.id)}
58
+ >
59
+ <FiX size={16} aria-hidden="true" />
60
+ </button>
61
+ </Show>
62
+ </div>
63
+ );
64
+ }
65
+
66
+ export function NoticeRegion(props: { notices: Notices }) {
67
+ const [expanded, setExpanded] = createSignal(false);
68
+ const text = () => solidKitStrings("notices");
69
+ const dismiss = () => text().dismiss;
70
+ const showMore = (hidden: number) =>
71
+ fillString(text().showMore, { count: hidden });
72
+ const list = () => props.notices.list();
73
+ const visible = () =>
74
+ expanded() ? list() : list().slice(0, NOTICE_MAX_VISIBLE);
75
+ const hidden = () => list().length - visible().length;
76
+ const byId = createMemo(
77
+ () => new Map(list().map((notice) => [notice.id, notice])),
78
+ );
79
+ // Keyed by id, so a keyed replacement updates the shown element in place and
80
+ // keeps focus on its dismiss button.
81
+ const visibleIds = () => visible().map((notice) => notice.id);
82
+
83
+ createEffect(() => {
84
+ if (list().length <= NOTICE_MAX_VISIBLE) setExpanded(false);
85
+ });
86
+
87
+ return (
88
+ <div class="eden-notice-region">
89
+ {/* The live region stays in the page, so screen readers announce the
90
+ notices added to it. aria-atomic="false" announces only the change. */}
91
+ <div class="eden-notice-list" role="status" aria-atomic="false">
92
+ <For each={visibleIds()}>
93
+ {(id) => (
94
+ <Show when={byId().get(id)}>
95
+ {(notice) => (
96
+ <NoticeItem
97
+ notice={notice()}
98
+ dismiss={dismiss()}
99
+ onDismiss={props.notices.dismiss}
100
+ />
101
+ )}
102
+ </Show>
103
+ )}
104
+ </For>
105
+ </div>
106
+ <Show when={hidden() > 0 || expanded()}>
107
+ <button
108
+ type="button"
109
+ class="eden-btn eden-btn-ghost eden-btn-sm eden-notice-more"
110
+ aria-expanded={expanded()}
111
+ onClick={() => setExpanded(!expanded())}
112
+ >
113
+ {expanded() ? text().showLess : showMore(hidden())}
114
+ </button>
115
+ </Show>
116
+ </div>
117
+ );
118
+ }
@@ -0,0 +1,167 @@
1
+ import { createEffect, createRoot, createSignal } from "solid-js";
2
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
3
+ import { createNotices, type Notices } from "./createNotices.js";
4
+
5
+ const titles = (notices: Notices) => notices.list().map((n) => n.title);
6
+
7
+ describe("createNotices", () => {
8
+ let dispose: (() => void) | undefined;
9
+ const create = () =>
10
+ createRoot((disposeRoot) => {
11
+ dispose = disposeRoot;
12
+ return createNotices({ autoHideMs: 1_000 });
13
+ });
14
+
15
+ beforeEach(() => vi.useFakeTimers());
16
+ afterEach(() => {
17
+ dispose?.();
18
+ vi.useRealTimers();
19
+ });
20
+
21
+ it("keeps danger and warning notices until dismissed and hides info and success", () => {
22
+ const notices = create();
23
+ const dangerId = notices.report({ severity: "danger", title: "write" });
24
+ notices.report({ severity: "warning", title: "limit" });
25
+ notices.report({ severity: "info", title: "saved draft" });
26
+ notices.report({ severity: "success", title: "saved" });
27
+
28
+ vi.advanceTimersByTime(1_000);
29
+ expect(titles(notices)).toEqual(["write", "limit"]);
30
+
31
+ notices.dismiss(dangerId);
32
+ expect(titles(notices)).toEqual(["limit"]);
33
+ });
34
+
35
+ it("replaces a notice with the same key in place and counts the repeats", () => {
36
+ const notices = create();
37
+ notices.report({ severity: "danger", title: "first", key: "offset" });
38
+ notices.report({ severity: "danger", title: "other" });
39
+ notices.report({ severity: "danger", title: "second", key: "offset" });
40
+
41
+ expect(notices.list()).toMatchObject([
42
+ { title: "other", count: 1 },
43
+ { title: "second", count: 2 },
44
+ ]);
45
+ });
46
+
47
+ it("reports a keyed notice from an effect once per change of its source", () => {
48
+ const notices = create();
49
+ const [failure, setFailure] = createSignal("timeout");
50
+ let runs = 0;
51
+ createRoot(() =>
52
+ createEffect(() => {
53
+ runs++;
54
+ notices.report({
55
+ severity: "danger",
56
+ title: failure(),
57
+ key: "link",
58
+ });
59
+ }),
60
+ );
61
+ setFailure("refused");
62
+
63
+ expect(runs).toBe(2);
64
+ expect(notices.list()).toMatchObject([{ title: "refused", count: 2 }]);
65
+ });
66
+
67
+ it("restarts the hide timer when a keyed info notice repeats", () => {
68
+ const notices = create();
69
+ notices.report({ severity: "info", title: "synced", key: "sync" });
70
+ vi.advanceTimersByTime(800);
71
+ notices.report({ severity: "info", title: "synced", key: "sync" });
72
+ vi.advanceTimersByTime(800);
73
+ expect(titles(notices)).toEqual(["synced"]);
74
+ vi.advanceTimersByTime(200);
75
+ expect(titles(notices)).toEqual([]);
76
+ });
77
+
78
+ it("shows a condition while it is true, before events of its severity, and removes it with its owner", () => {
79
+ const notices = create();
80
+ const [offline, setOffline] = createSignal(false);
81
+ const disposeOwner = createRoot((disposeCondition) => {
82
+ notices.condition(offline, { severity: "warning", title: "offline" });
83
+ return disposeCondition;
84
+ });
85
+ notices.report({ severity: "warning", title: "write" });
86
+
87
+ expect(titles(notices)).toEqual(["write"]);
88
+ setOffline(true);
89
+ expect(notices.list()).toMatchObject([
90
+ { title: "offline", kind: "condition" },
91
+ { title: "write", kind: "event" },
92
+ ]);
93
+ setOffline(false);
94
+ expect(titles(notices)).toEqual(["write"]);
95
+
96
+ setOffline(true);
97
+ disposeOwner();
98
+ expect(titles(notices)).toEqual(["write"]);
99
+ });
100
+
101
+ it("refuses a condition without a reactive owner, which could never remove it", () => {
102
+ const notices = create();
103
+ expect(() =>
104
+ notices.condition(() => true, { severity: "warning", title: "offline" }),
105
+ ).toThrow(/reactive owner/);
106
+ expect(notices.list()).toEqual([]);
107
+ });
108
+
109
+ it("leaves no hide timer pending for a report after the notices are disposed", () => {
110
+ const notices = create();
111
+ dispose?.();
112
+ notices.report({ severity: "info", title: "saved" });
113
+ expect(vi.getTimerCount()).toBe(0);
114
+ });
115
+
116
+ it("shows more severe notices first, so a failure is not hidden behind warnings", () => {
117
+ const notices = create();
118
+ createRoot(() => {
119
+ notices.condition(() => true, { severity: "warning", title: "offline" });
120
+ notices.condition(() => true, { severity: "info", title: "syncing" });
121
+ });
122
+ notices.report({ severity: "danger", title: "stop failed" });
123
+ notices.report({ severity: "warning", title: "invalid value" });
124
+
125
+ expect(titles(notices)).toEqual([
126
+ "stop failed",
127
+ "offline",
128
+ "invalid value",
129
+ "syncing",
130
+ ]);
131
+ });
132
+
133
+ it("follows reactive condition content", () => {
134
+ const notices = create();
135
+ const [title, setTitle] = createSignal("offline");
136
+ createRoot(() =>
137
+ notices.condition(
138
+ () => true,
139
+ () => ({ severity: "warning", title: title() }),
140
+ ),
141
+ );
142
+ setTitle("rozłączono");
143
+ expect(titles(notices)).toEqual(["rozłączono"]);
144
+ });
145
+
146
+ it("reports and logs a thrown action failure and resolves to undefined", async () => {
147
+ const notices = create();
148
+ const log = vi.spyOn(console, "error").mockImplementation(() => {});
149
+ const failure = new Error("controller rejected the write");
150
+
151
+ await expect(
152
+ notices.attempt(() => Promise.reject(failure), { title: "write" }),
153
+ ).resolves.toBeUndefined();
154
+ await expect(
155
+ notices.attempt(() => Promise.resolve(7), { title: "read" }),
156
+ ).resolves.toBe(7);
157
+
158
+ expect(notices.list()).toMatchObject([
159
+ {
160
+ severity: "danger",
161
+ title: "write",
162
+ detail: "controller rejected the write",
163
+ },
164
+ ]);
165
+ expect(log).toHaveBeenCalledWith("write", failure);
166
+ });
167
+ });