uikit-v1.2.5-chakra-default-loading
All checks were successful
Build and Deploy Next.js + Nginx Docker Image / build-and-deploy (push) Successful in 52s
Build and Deploy Next.js + Nginx Docker Image / deploy (push) Successful in 7s

This commit is contained in:
Mohamadzadeh 2026-10-26 14:49:25 +03:30
parent cedfc4d688
commit 4730057b3f
21 changed files with 205 additions and 152 deletions

7
LOADING_DEFAULT_1.2.5.md Normal file
View File

@ -0,0 +1,7 @@
# UI Kit v1.2.5: Default loading UI
- With `<Chakra />` in the same `<BiProvider>`, `<Keycloak />` and `<Permission />` use a Chakra `<Spinner />` when `loading` is omitted.
- Explicit `loading` overrides the default, including `loading={null}`.
- Without `<Chakra />` there is no Chakra dependency: Keycloak keeps its previous `null` loader and Permission its previous `Loading permissions...` text.
- React-only `ChakraLoadingContext` shares the optional default across all modules; no behavior changes to API, Query, or authentication.
- Changes to `src/dev/AppHeaderPreview.jsx` are documentation source only; remote demo bundle was not rebuilt without npm dependencies.

View File

@ -53,3 +53,7 @@ yarn build
خروجی‌های قدیمی `core` را دست‌نخورده نگه می‌دارد.
مسیرهای `uikit/provider/<feature>` هنوز به‌عنوان alias همان خروجی‌های جدید کار می‌کنند. برای راهنمای کامل جدول `MIGRATION_1.2.0.md` را ببینید.
### Loading پیش‌فرض Keycloak و Permission (v1.2.5)
با تعریف `<Chakra />` در `<BiProvider>`، دو کامپوننت `<Keycloak />` و `<Permission />` هنگام انتظار خودکار `<Spinner />` نشان می‌دهند. پراپ `loading` سفارشی، حتی `loading={null}`، اولویت دارد. بدون `<Chakra />`، مقدار پیش‌فرض قدیمی حفظ می‌شود؛ نیاز به افزودن دستی Spinner در مقصد نیست.

View File

@ -495,6 +495,20 @@ export function SearchFilter() {
### uikit/keycloak
**پیش‌فرض Loading در نسخه 1.2.5:** اگر `<Chakra />` در `BiProvider` وجود داشته باشد، `Keycloak` و `Permission` بدون نیاز به تنظیم `loading` یک `<Spinner />` از Chakra نمایش می‌دهند. اگر مقدار `loading` صریحاً ارسال شود (حتی `null`)، همان مقدار اولویت دارد. بدون `<Chakra />`، رفتار قبلی حفظ می‌شود: `Keycloak` مقدار `null` و `Permission` متن `Loading permissions...` را نمایش می‌دهد. این دو ماژول همچنان مستقل از Chakra هستند.
```jsx
<BiProvider>
<Chakra />
<Keycloak clientId={KEYCLOAK_CLIENT_ID} />
<Permission clientId={PERMISSION_CLIENT_ID} />
<App />
</BiProvider>
// نمونه سفارشی: <Keycloak clientId="..." loading={<CustomLoader />} />
// غیرفعال‌کردن نمایش: <Permission clientId="..." loading={null} />
```
**`Keycloak`**: `clientId` الزامی و `url`، `realm`، `initOptions`، `loading`، `errorFallback`، `allowUnauthenticated` و `onError` اختیاری هستند. **`useKeycloak()`** مقدارهای `instance`، `initialized`، `authenticated`، `token`، `error` و متدهای `login(options?)`، `logout(options?)`، `updateToken(minValidity?)` را برمی‌گرداند. پیش‌فرض `onLoad: "login-required"` و `flow: "implicit"` است؛ `updateToken()` نتیجه boolean برمی‌گرداند.
```jsx

4
dist/api.js vendored
View File

@ -3,8 +3,8 @@ import { jsx as b } from "react/jsx-runtime";
import { useRef as f, useMemo as j } from "react";
import z from "axios";
import { d as B } from "./chunks/feature-registry-B2iuEiEx.js";
import { u as L, A as P } from "./chunks/provider-runtime-B6XIrDzf.js";
import { a as U } from "./chunks/provider-runtime-B6XIrDzf.js";
import { u as L, A as P } from "./chunks/provider-runtime-CxEpkUq5.js";
import { a as U } from "./chunks/provider-runtime-CxEpkUq5.js";
function _({
children: u,
baseUrl: i = "",

61
dist/chakra.js vendored
View File

@ -1,12 +1,13 @@
"use client";
import { jsxs as c, jsx as f } from "react/jsx-runtime";
import s, { useEffect as u } from "react";
import { extendTheme as l, withDefaultColorScheme as m, Text as p, Input as h, IconButton as B, HStack as E, Button as k, Badge as _, ChakraProvider as a } from "@chakra-ui/react";
import { Global as w } from "@emotion/react";
import { createRoot as x } from "react-dom/client";
import { jsx as e, jsxs as f } from "react/jsx-runtime";
import s, { useEffect as l } from "react";
import { extendTheme as u, withDefaultColorScheme as m, Text as p, Input as h, IconButton as B, HStack as E, Button as k, Badge as _, ChakraProvider as n, Spinner as w } from "@chakra-ui/react";
import { Global as x } from "@emotion/react";
import { createRoot as C } from "react-dom/client";
import { e as I } from "./chunks/estedad-B1AoGIKy.js";
import { d as b } from "./chunks/feature-registry-B2iuEiEx.js";
const y = l({
import { d as S } from "./chunks/feature-registry-B2iuEiEx.js";
import { C as b } from "./chunks/provider-runtime-CxEpkUq5.js";
const g = u({
direction: "rtl",
styles: {
global: {
@ -31,31 +32,31 @@ const y = l({
}
}
}, m({ colorScheme: "facebook" }));
function S({ children: n, theme: o = y, fonts: i = !0, remoteUiEnabled: e = !0, remoteUiChakraProviderProps: r, ...d }) {
return u(() => {
if (!e || typeof window > "u") return;
const t = window.__UIKIT_REMOTE_DEPS__ || {};
function y({ children: i, theme: t = g, fonts: d = !0, remoteUiEnabled: r = !0, remoteUiChakraProviderProps: a, ...c }) {
return l(() => {
if (!r || typeof window > "u") return;
const o = window.__UIKIT_REMOTE_DEPS__ || {};
window.__UIKIT_REMOTE_DEPS__ = {
...t,
React: t.React || s,
createRoot: t.createRoot || x,
ChakraProvider: t.ChakraProvider || a,
Badge: t.Badge || _,
Button: t.Button || k,
HStack: t.HStack || E,
IconButton: t.IconButton || B,
Input: t.Input || h,
Text: t.Text || p,
theme: o,
chakraProviderProps: { ...t.chakraProviderProps, ...r }
...o,
React: o.React || s,
createRoot: o.createRoot || C,
ChakraProvider: o.ChakraProvider || n,
Badge: o.Badge || _,
Button: o.Button || k,
HStack: o.HStack || E,
IconButton: o.IconButton || B,
Input: o.Input || h,
Text: o.Text || p,
theme: t,
chakraProviderProps: { ...o.chakraProviderProps, ...a }
};
}, [e, o, r]), /* @__PURE__ */ c(a, { theme: o, ...d, children: [
i && /* @__PURE__ */ f(w, { styles: `@font-face { font-family: Estedad; src: url("${I}") format("woff2"); font-weight: 400; font-style: normal; font-display: swap; }` }),
n
] });
}, [r, t, a]), /* @__PURE__ */ e(n, { theme: t, ...c, children: /* @__PURE__ */ f(b.Provider, { value: /* @__PURE__ */ e(w, {}), children: [
d && /* @__PURE__ */ e(x, { styles: `@font-face { font-family: Estedad; src: url("${I}") format("woff2"); font-weight: 400; font-style: normal; font-display: swap; }` }),
i
] }) });
}
const F = b("Chakra", 10, S);
const z = S("Chakra", 10, y);
export {
F as Chakra,
y as defaultBiTheme
z as Chakra,
g as defaultBiTheme
};

View File

@ -1,22 +1,23 @@
import { createContext as o, useContext as r } from "react";
const n = o(null), t = o(null);
import { createContext as o, useContext as n } from "react";
const r = o(null), t = o(null), a = o(void 0);
function i() {
return r(n);
return n(r);
}
function u() {
const e = i();
if (!e) throw new Error("useKeycloak requires <Keycloak /> inside <BiProvider>.");
return e;
}
function a() {
const e = r(t);
function c() {
const e = n(t);
if (!e) throw new Error("useApi requires <Api /> inside <BiProvider>.");
return e;
}
export {
t as A,
n as K,
a,
a as C,
r as K,
c as a,
u as b,
i as u
};

1
dist/keycloak.d.ts vendored
View File

@ -5,6 +5,7 @@ export interface KeycloakProps {
url?: string;
realm?: string;
initOptions?: Record<string, unknown>;
/** Defaults to Chakra Spinner when <Chakra /> is present; otherwise null. Explicit null disables it. */
loading?: ReactNode;
errorFallback?: ReactNode;
allowUnauthenticated?: boolean;

62
dist/keycloak.js vendored
View File

@ -1,65 +1,65 @@
"use client";
import { jsx as L } from "react/jsx-runtime";
import { useMemo as K, useRef as b, useState as x, useCallback as s, useEffect as R } from "react";
import q from "keycloak-js";
import { d as C } from "./chunks/feature-registry-B2iuEiEx.js";
import { K as M } from "./chunks/provider-runtime-B6XIrDzf.js";
import { b as I } from "./chunks/provider-runtime-B6XIrDzf.js";
import { setKeycloakLogoutHandler as v } from "./core-runtime.js";
function P({
children: S,
import { jsx as A } from "react/jsx-runtime";
import { useContext as b, useMemo as v, useRef as R, useState as q, useCallback as s, useEffect as M } from "react";
import P from "keycloak-js";
import { d as T } from "./chunks/feature-registry-B2iuEiEx.js";
import { C as j, K as B } from "./chunks/provider-runtime-CxEpkUq5.js";
import { b as U } from "./chunks/provider-runtime-CxEpkUq5.js";
import { setKeycloakLogoutHandler as L } from "./core-runtime.js";
function F({
children: C,
clientId: c,
url: f = "https://auth.ibagher.ir",
realm: d = "bi",
initOptions: h,
loading: w = null,
errorFallback: z = null,
allowUnauthenticated: A = !1,
loading: k,
errorFallback: S = null,
allowUnauthenticated: w = !1,
onError: i
}) {
if (!c) throw new Error("<Keycloak /> requires clientId.");
const e = K(
() => new q({ url: f, realm: d, clientId: c }),
const x = b(j), z = k !== void 0 ? k : x ?? null, e = v(
() => new P({ url: f, realm: d, clientId: c }),
[f, d, c]
), k = b(/* @__PURE__ */ new WeakMap()), [t, m] = x({ client: e, initialized: !1, authenticated: !1, token: null, error: null }), a = s(() => {
m({ client: e, initialized: !0, authenticated: !!e.authenticated, token: e.token ?? null, error: null });
), m = R(/* @__PURE__ */ new WeakMap()), [t, g] = q({ client: e, initialized: !1, authenticated: !1, token: null, error: null }), a = s(() => {
g({ client: e, initialized: !0, authenticated: !!e.authenticated, token: e.token ?? null, error: null });
}, [e]);
R(() => {
M(() => {
let n = !0;
const o = () => {
n && a();
};
e.onAuthSuccess = o, e.onAuthRefreshSuccess = o, e.onAuthLogout = o, v((r) => e.logout(r));
let u = k.current.get(e);
e.onAuthSuccess = o, e.onAuthRefreshSuccess = o, e.onAuthLogout = o, L((r) => e.logout(r));
let u = m.current.get(e);
return u || (u = Promise.resolve().then(() => e.init({
onLoad: "login-required",
checkLoginIframe: !1,
flow: "implicit",
// Matches the existing core/BiProvider behavior.
...h
})), k.current.set(e, u)), u.then(o, (r) => {
n && (m({ client: e, initialized: !0, authenticated: !1, token: null, error: r }), i == null || i(r));
})), m.current.set(e, u)), u.then(o, (r) => {
n && (g({ client: e, initialized: !0, authenticated: !1, token: null, error: r }), i == null || i(r));
}), () => {
n = !1, e.onAuthSuccess = void 0, e.onAuthRefreshSuccess = void 0, e.onAuthLogout = void 0, v(null);
n = !1, e.onAuthSuccess = void 0, e.onAuthRefreshSuccess = void 0, e.onAuthLogout = void 0, L(null);
};
}, [e, h, i, a]);
const p = s((n) => e.login(n), [e]), g = s((n) => e.logout(n), [e]), y = s(async (n = 30) => {
const p = s((n) => e.login(n), [e]), y = s((n) => e.logout(n), [e]), K = s(async (n = 30) => {
const o = await e.updateToken(n);
return a(), o;
}, [e, a]), l = K(() => ({
}, [e, a]), l = v(() => ({
instance: e,
initialized: t.client === e && t.initialized,
authenticated: t.client === e && t.authenticated,
token: t.client === e ? t.token : null,
error: t.client === e ? t.error : null,
login: p,
logout: g,
updateToken: y
}), [e, t, p, g, y]);
return l.initialized ? l.error ? z : !l.authenticated && !A ? null : /* @__PURE__ */ L(M.Provider, { value: l, children: S }) : w;
logout: y,
updateToken: K
}), [e, t, p, y, K]);
return l.initialized ? l.error ? S : !l.authenticated && !w ? null : /* @__PURE__ */ A(B.Provider, { value: l, children: C }) : z;
}
const $ = C("Keycloak", 40, P);
const J = T("Keycloak", 40, F);
export {
$ as Keycloak,
I as useKeycloak
J as Keycloak,
U as useKeycloak
};

View File

@ -7,6 +7,7 @@ export interface PermissionProps {
/** Used only when Keycloak has no token. Otherwise the permission request is unauthenticated. */
getToken?: () => string | null | Promise<string | null>;
storageKey?: string;
/** Defaults to Chakra Spinner when <Chakra /> is present; otherwise legacy text. Explicit null disables it. */
loading?: ReactNode;
errorFallback?: ReactNode;
enabled?: boolean;

132
dist/permission.js vendored
View File

@ -1,13 +1,13 @@
"use client";
import { jsx as L } from "react/jsx-runtime";
import { useState as U, useRef as B, useEffect as F, useCallback as y, useMemo as z } from "react";
import { d as K } from "./chunks/feature-registry-B2iuEiEx.js";
import { u as H } from "./chunks/provider-runtime-B6XIrDzf.js";
import { PermissionContext as N, usePermission as $ } from "./core-runtime.js";
function Q(r) {
import { jsx as y } from "react/jsx-runtime";
import { useContext as Q, useState as U, useRef as B, useEffect as F, useCallback as L, useMemo as z } from "react";
import { d as V } from "./chunks/feature-registry-B2iuEiEx.js";
import { C as X, u as H } from "./chunks/provider-runtime-CxEpkUq5.js";
import { PermissionContext as Z, usePermission as E } from "./core-runtime.js";
function k(r) {
return new Set((Array.isArray(r) ? r : []).map((n) => n.name));
}
function V(r, n = "") {
function nn(r, n = "") {
if (!n) return !1;
if (r.has(n) || [...r].some((s) => s.startsWith(n))) return !0;
let e = n;
@ -15,7 +15,7 @@ function V(r, n = "") {
if (e = e.slice(0, e.lastIndexOf(":")), r.has(`${e}:*`)) return !0;
return !1;
}
function X(r = "permissions") {
function rn(r = "permissions") {
if (!(typeof window > "u"))
try {
const n = window.localStorage.getItem(r), e = n ? JSON.parse(n) : void 0;
@ -24,113 +24,113 @@ function X(r = "permissions") {
return;
}
}
function Z(r = "permissions", n) {
function en(r = "permissions", n) {
if (!(typeof window > "u"))
try {
window.localStorage.setItem(r, JSON.stringify(n));
} catch {
}
}
function k(r = "permissions") {
function tn(r = "permissions") {
if (!(typeof window > "u"))
try {
window.localStorage.removeItem(r);
} catch {
}
}
function nn({
function sn({
children: r,
clientId: n,
url: e = "https://api.d.aiengines.ir/user_api/v1/permissions/list",
user: s = null,
getToken: u,
storageKey: d,
loading: l = /* @__PURE__ */ L("div", { children: "Loading permissions..." }),
errorFallback: f = /* @__PURE__ */ L("div", { children: "Error loading permissions" }),
enabled: x = !0
getToken: d,
storageKey: l,
loading: c,
errorFallback: f = /* @__PURE__ */ y("div", { children: "Error loading permissions" }),
enabled: $ = !0
}) {
var I, J;
if (!n) throw new Error("<Permission /> requires clientId.");
const t = H(), M = ((J = (I = t == null ? void 0 : t.instance) == null ? void 0 : I.tokenParsed) == null ? void 0 : J.sub) ?? (s == null ? void 0 : s.id) ?? "anonymous", i = d ?? `permissions:${n}:${M}`, [W, Y] = U(0), [G, p] = U({ key: null, permissions: null, isLoading: !0, error: null }), v = B(u);
v.current = u;
const O = t == null ? void 0 : t.token, w = t == null ? void 0 : t.instance, R = t == null ? void 0 : t.authenticated, h = t == null ? void 0 : t.updateToken;
const M = Q(X), W = c !== void 0 ? c : M ?? /* @__PURE__ */ y("div", { children: "Loading permissions..." }), t = H(), Y = ((J = (I = t == null ? void 0 : t.instance) == null ? void 0 : I.tokenParsed) == null ? void 0 : J.sub) ?? (s == null ? void 0 : s.id) ?? "anonymous", i = l ?? `permissions:${n}:${Y}`, [D, K] = U(0), [G, h] = U({ key: null, permissions: null, isLoading: !0, error: null }), v = B(d);
v.current = d;
const O = t == null ? void 0 : t.token, p = t == null ? void 0 : t.instance, R = t == null ? void 0 : t.authenticated, w = t == null ? void 0 : t.updateToken;
F(() => {
const o = X(i) ?? null;
if (!x) {
p({ key: i, permissions: [], isLoading: !1, error: null });
const o = rn(i) ?? null;
if (!$) {
h({ key: i, permissions: [], isLoading: !1, error: null });
return;
}
let A = !0;
const b = new AbortController();
return p({ key: i, permissions: o, isLoading: !o, error: null }), (async () => {
let C = !0;
const A = new AbortController();
return h({ key: i, permissions: o, isLoading: !o, error: null }), (async () => {
try {
const S = typeof window > "u" ? "http://localhost" : window.location.origin, T = new URL(e, S);
const b = typeof window > "u" ? "http://localhost" : window.location.origin, T = new URL(e, b);
T.searchParams.set("client_id", n);
let m = null;
if (R) {
try {
await (h == null ? void 0 : h(5));
await (w == null ? void 0 : w(5));
} catch {
}
m = (w == null ? void 0 : w.token) || O || null;
m = (p == null ? void 0 : p.token) || O || null;
}
!m && v.current && (m = await v.current() || null);
const C = await fetch(T, {
signal: b.signal,
const S = await fetch(T, {
signal: A.signal,
headers: m ? { Authorization: `Bearer ${m}` } : {}
});
if (!C.ok) throw new Error(`Permission HTTP ${C.status}`);
const E = await C.json();
if (!Array.isArray(E)) throw new Error("Permission response must be an array.");
if (!A) return;
Z(i, E), p({ key: i, permissions: E, isLoading: !1, error: null });
} catch (S) {
A && !b.signal.aborted && p({ key: i, permissions: o, isLoading: !1, error: S });
if (!S.ok) throw new Error(`Permission HTTP ${S.status}`);
const x = await S.json();
if (!Array.isArray(x)) throw new Error("Permission response must be an array.");
if (!C) return;
en(i, x), h({ key: i, permissions: x, isLoading: !1, error: null });
} catch (b) {
C && !A.signal.aborted && h({ key: i, permissions: o, isLoading: !1, error: b });
}
})(), () => {
A = !1, b.abort();
C = !1, A.abort();
};
}, [e, n, i, O, w, x, R, h, W]);
const g = y(() => Y((o) => o + 1), []), _ = y(() => {
k(i), g();
}, [i, g]), a = G.key === i ? G : { permissions: null, isLoading: !0, error: null }, c = a.permissions, j = z(() => Q(c), [c]), P = y((o) => V(j, o), [j]), q = y((o) => !P(o), [P]), D = z(() => ({
}, [e, n, i, O, p, $, R, w, D]);
const g = L(() => K((o) => o + 1), []), _ = L(() => {
tn(i), g();
}, [i, g]), a = G.key === i ? G : { permissions: null, isLoading: !0, error: null }, u = a.permissions, j = z(() => k(u), [u]), P = L((o) => nn(j, o), [j]), q = L((o) => !P(o), [P]), N = z(() => ({
user: s,
permissions: c,
permissions: u,
can: P,
cannot: q,
isLoading: a.isLoading,
error: a.error,
refresh: g,
clear: _
}), [s, c, P, q, a.isLoading, a.error, g, _]);
return a.isLoading && !c ? l : a.error && !c ? f : /* @__PURE__ */ L(N.Provider, { value: D, children: r });
}), [s, u, P, q, a.isLoading, a.error, g, _]);
return a.isLoading && !u ? W : a.error && !u ? f : /* @__PURE__ */ y(Z.Provider, { value: N, children: r });
}
const an = K("Permission", 60, nn);
function cn({ perm: r, children: n, fallback: e = /* @__PURE__ */ L("div", { children: "You are not allowed to do this" }) }) {
const { can: s } = $();
const ln = V("Permission", 60, sn);
function fn({ perm: r, children: n, fallback: e = /* @__PURE__ */ y("div", { children: "You are not allowed to do this" }) }) {
const { can: s } = E();
return s(r) ? n : e;
}
function un({ children: r }) {
const { permissions: n, can: e } = $();
function mn({ children: r }) {
const { permissions: n, can: e } = E();
return n && e("admin") ? r : null;
}
function dn({ children: r, forceNoAccess: n = !1, onNoAccess: e }) {
const { can: s, isLoading: u } = $(), d = H(), l = B(e);
l.current = e;
const f = d == null ? void 0 : d.logout;
function hn({ children: r, forceNoAccess: n = !1, onNoAccess: e }) {
const { can: s, isLoading: d } = E(), l = H(), c = B(e);
c.current = e;
const f = l == null ? void 0 : l.logout;
return F(() => {
u || !n && s("panel_access") || (l.current ? l.current() : f && f());
}, [u, n, s, f]), r;
d || !n && s("panel_access") || (c.current ? c.current() : f && f());
}, [d, n, s, f]), r;
}
export {
un as AdminGuard,
cn as Can,
dn as PanelAccessGuard,
an as Permission,
V as checkPermission,
k as clearCachedPermissions,
Q as createPermissionSet,
X as getCachedPermissions,
Z as setCachedPermissions,
$ as usePermission
mn as AdminGuard,
fn as Can,
hn as PanelAccessGuard,
ln as Permission,
nn as checkPermission,
tn as clearCachedPermissions,
k as createPermissionSet,
rn as getCachedPermissions,
en as setCachedPermissions,
E as usePermission
};

File diff suppressed because one or more lines are too long

View File

@ -5,7 +5,7 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="color-scheme" content="light" />
<title>UI Kit Remote Demo</title>
<script type="module" crossorigin src="./demo-assets/index-DNhZDl2y.js"></script>
<script type="module" crossorigin src="./demo-assets/index-GAwfVE8_.js"></script>
</head>
<body>
<div id="root"></div>

View File

@ -1,6 +1,6 @@
{
"name": "uikit",
"version": "1.2.4",
"version": "1.2.5",
"type": "module",
"main": "./dist/index.js",
"module": "./dist/index.js",

View File

@ -1,11 +1,12 @@
"use client";
import React, { useEffect } from "react";
import { extendTheme, withDefaultColorScheme, ChakraProvider, Badge, Button, HStack, IconButton, Input, Text } from "@chakra-ui/react";
import { extendTheme, withDefaultColorScheme, ChakraProvider, Spinner, Badge, Button, HStack, IconButton, Input, Text } from "@chakra-ui/react";
import { Global } from "@emotion/react";
import { createRoot } from "react-dom/client";
import fontUrl from "../assets/fonts/estedad.woff2?url";
import { defineFeature } from "../internal/feature-registry.jsx";
import { ChakraLoadingContext } from "../internal/provider-runtime.jsx";
export const defaultBiTheme = extendTheme({
direction: "rtl",
@ -54,8 +55,10 @@ function ChakraLayer({ children, theme = defaultBiTheme, fonts = true, remoteUiE
}, [remoteUiEnabled, theme, remoteUiChakraProviderProps]);
return <ChakraProvider theme={theme} {...providerProps}>
{fonts && <Global styles={`@font-face { font-family: Estedad; src: url("${fontUrl}") format("woff2"); font-weight: 400; font-style: normal; font-display: swap; }`} />}
{children}
<ChakraLoadingContext.Provider value={<Spinner />}>
{fonts && <Global styles={`@font-face { font-family: Estedad; src: url("${fontUrl}") format("woff2"); font-weight: 400; font-style: normal; font-display: swap; }`} />}
{children}
</ChakraLoadingContext.Provider>
</ChakraProvider>;
}

View File

@ -283,6 +283,8 @@ export function Providers({ children }) {
// url="https://auth.example.com"
// realm="my-realm"
// initOptions={{ onLoad: "login-required" }}
// اگر Chakra در همین BiProvider باشد، loading پیش‌فرض Spinner است.
// نمونه سفارشی با اولویت بالاتر:
loading={<span>Loading auth...</span>}
errorFallback={<span>Auth failed</span>}
onError={(error) => console.error(error)}
@ -366,6 +368,8 @@ export function Providers({ children }) {
getToken={() => localStorage.getItem("access_token")}
// url="https://api.example.com/permissions/list"
// storageKey="permissions:permission-client:my-user"
// اگر Chakra در همین BiProvider باشد، loading پیش‌فرض Spinner است.
// نمونه سفارشی با اولویت بالاتر:
loading={<span>Loading permissions...</span>}
errorFallback={<span>Permission error</span>}
/>
@ -935,6 +939,7 @@ function ProviderDocs() {
<Text mt={2} fontSize="xs" color="gray.600">
<Code>clientId</Code> برای Keycloak و Permission اجباری است. آدرس API و شناسه‌ها را با مقادیر سامانه جایگزین کنید.
ترتیب نوشتن markerها مهم نیست؛ ترتیب اجرای واقعی: Chakra ← Query ← Router ← Keycloak ← Api ← Permission ← App.
با حضور Chakra، لودینگ Keycloak و Permission به‌صورت پیش‌فرض Spinner است؛ نیازی به ارسال loading نیست و loading سفارشی (حتی null) اولویت دارد.
</Text>
</Box>
@ -985,6 +990,7 @@ function ProviderDocs() {
<Text>• <Code>uikit/api</Code> → <Code>Api</Code>: <Code>baseUrl</Code>، <Code>auth</Code>، <Code>getToken</Code>، <Code>axiosConfig</Code>، <Code>onUnauthorized</Code>، <Code>logoutOnUnauthorized</Code> (پیش‌فرض false)؛ نیازمند Axios، قابل مصرف با <Code>useApi</Code>.</Text>
<Text>• <Code>uikit/permission</Code> → <Code>Permission</Code>: <Code>clientId</Code> اجباری، <Code>url</Code>، <Code>user</Code>، <Code>getToken</Code>، <Code>storageKey</Code>، <Code>loading</Code>، <Code>errorFallback</Code> و <Code>enabled</Code>؛ بدون کتابخانه اضافه، قابل مصرف با <Code>usePermission</Code> و <Code>Can</Code>.</Text>
<Text>• اولویت احراز هویت هر دو ماژول: توکن <Code>Keycloak</Code>، سپس خروجی <Code>getToken()</Code> و در نبود هر دو درخواست بدون Bearer. در <Code>Api</Code> با <Code>auth={false}</Code> تزریق توکن غیرفعال می‌شود.</Text>
<Text>• Loading پیش‌فرض با حضور <Code>Chakra</Code>: هر دو ماژول <Code>Keycloak</Code> و <Code>Permission</Code> خودکار Chakra <Code>Spinner</Code> نشان می‌دهند؛ <Code>loading</Code> ارسالی (حتی null) اولویت دارد. بدون Chakra، رفتار قبلی حفظ می‌شود.</Text>
<Text>• <Code>uikit/next-pages-router</Code> و <Code>uikit/next-app-router</Code>: فقط یکی را انتخاب کنید؛ نیازمند <Code>next-query-params</Code> و <Code>use-query-params</Code>.</Text>
<Text>• <Code>uikit/vite</Code> → <Code>Vite</Code>: اختیاری و بدون تنظیم اضافه.</Text>
<Text>• <Code>uikit/update-checker</Code> → <Code>Updates</Code>: <Code>endpoint</Code> (پیش‌فرض /version.json)، <Code>interval</Code> (پیش‌فرض 30000ms) و <Code>message</Code>.</Text>

View File

@ -4,6 +4,9 @@ import { createContext, useContext } from "react";
export const KeycloakContext = createContext(null);
export const ApiContext = createContext(null);
// Optional loading UI from <Chakra />. React-only so Keycloak and Permission
// remain usable without installing or enabling Chakra.
export const ChakraLoadingContext = createContext(undefined);
export function useKeycloakOptional() {
return useContext(KeycloakContext);

View File

@ -5,6 +5,7 @@ export interface KeycloakProps {
url?: string;
realm?: string;
initOptions?: Record<string, unknown>;
/** Defaults to Chakra Spinner when <Chakra /> is present; otherwise null. Explicit null disables it. */
loading?: ReactNode;
errorFallback?: ReactNode;
allowUnauthenticated?: boolean;

View File

@ -1,9 +1,9 @@
"use client";
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
import React, { useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
import KeycloakClient from "keycloak-js";
import { defineFeature } from "../internal/feature-registry.jsx";
import { KeycloakContext, useKeycloak } from "../internal/provider-runtime.jsx";
import { ChakraLoadingContext, KeycloakContext, useKeycloak } from "../internal/provider-runtime.jsx";
import { setKeycloakLogoutHandler } from "../core/runtime.jsx";
function KeycloakLayer({
@ -12,12 +12,14 @@ function KeycloakLayer({
url = "https://auth.ibagher.ir",
realm = "bi",
initOptions,
loading = null,
loading,
errorFallback = null,
allowUnauthenticated = false,
onError,
}) {
if (!clientId) throw new Error("<Keycloak /> requires clientId.");
const chakraLoading = useContext(ChakraLoadingContext);
const loadingContent = loading !== undefined ? loading : (chakraLoading ?? null);
const client = useMemo(
() => new KeycloakClient({ url, realm, clientId }),
@ -79,7 +81,7 @@ function KeycloakLayer({
login, logout, updateToken,
}), [client, state, login, logout, updateToken]);
if (!value.initialized) return loading;
if (!value.initialized) return loadingContent;
if (value.error) return errorFallback;
if (!value.authenticated && !allowUnauthenticated) return null;
return <KeycloakContext.Provider value={value}>{children}</KeycloakContext.Provider>;

View File

@ -7,6 +7,7 @@ export interface PermissionProps {
/** Used only when Keycloak has no token. Otherwise the permission request is unauthenticated. */
getToken?: () => string | null | Promise<string | null>;
storageKey?: string;
/** Defaults to Chakra Spinner when <Chakra /> is present; otherwise legacy text. Explicit null disables it. */
loading?: ReactNode;
errorFallback?: ReactNode;
enabled?: boolean;

View File

@ -1,8 +1,8 @@
"use client";
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
import React, { useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
import { defineFeature } from "../internal/feature-registry.jsx";
import { useKeycloakOptional } from "../internal/provider-runtime.jsx";
import { ChakraLoadingContext, useKeycloakOptional } from "../internal/provider-runtime.jsx";
// The shared context is React-only and is also consumed by existing uikit/layout.
import { PermissionContext, usePermission } from "../core/runtime.jsx";
@ -47,11 +47,15 @@ function PermissionLayer({
user = null,
getToken,
storageKey,
loading = <div>Loading permissions...</div>,
loading,
errorFallback = <div>Error loading permissions</div>,
enabled = true,
}) {
if (!clientId) throw new Error("<Permission /> requires clientId.");
const chakraLoading = useContext(ChakraLoadingContext);
const loadingContent = loading !== undefined
? loading
: (chakraLoading ?? <div>Loading permissions...</div>);
const keycloak = useKeycloakOptional();
// Never reuse one user's cached permissions for another authenticated user.
const identity = keycloak?.instance?.tokenParsed?.sub ?? user?.id ?? "anonymous";
@ -121,7 +125,7 @@ function PermissionLayer({
refresh, clear,
}), [user, permissions, can, cannot, current.isLoading, current.error, refresh, clear]);
if (current.isLoading && !permissions) return loading;
if (current.isLoading && !permissions) return loadingContent;
if (current.error && !permissions) return errorFallback;
return <PermissionContext.Provider value={value}>{children}</PermissionContext.Provider>;
}