@intlayer/design-system 8.11.0 → 8.11.2

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.
Files changed (50) hide show
  1. package/dist/esm/api/useAuth/useOAuth2.mjs +3 -3
  2. package/dist/esm/api/useAuth/useOAuth2.mjs.map +1 -1
  3. package/dist/esm/api/useAuth/useSession.mjs +3 -3
  4. package/dist/esm/api/useAuth/useSession.mjs.map +1 -1
  5. package/dist/esm/components/Browser/Browser.mjs +1 -1
  6. package/dist/esm/components/Browser/Browser.mjs.map +1 -1
  7. package/dist/esm/components/Form/FormBase.mjs +2 -1
  8. package/dist/esm/components/Form/FormBase.mjs.map +1 -1
  9. package/dist/esm/components/IDE/Code.mjs +1 -1
  10. package/dist/esm/components/IDE/Code.mjs.map +1 -1
  11. package/dist/esm/components/MarkDownRender/MarkDownIframe.mjs +1 -1
  12. package/dist/esm/components/MarkDownRender/MarkDownIframe.mjs.map +1 -1
  13. package/dist/esm/components/MarkDownRender/MarkDownRender.mjs +1 -1
  14. package/dist/esm/components/MarkDownRender/MarkDownRender.mjs.map +1 -1
  15. package/dist/esm/components/TextArea/AutoSizeTextArea.mjs +1 -2
  16. package/dist/esm/components/TextArea/AutoSizeTextArea.mjs.map +1 -1
  17. package/dist/esm/libs/auth.mjs +2 -6
  18. package/dist/esm/libs/auth.mjs.map +1 -1
  19. package/dist/esm/routes.mjs +3 -1
  20. package/dist/esm/routes.mjs.map +1 -1
  21. package/dist/types/api/useAuth/useOAuth2.d.ts +1 -1
  22. package/dist/types/api/useAuth/useOAuth2.d.ts.map +1 -1
  23. package/dist/types/api/useIntlayerAPI.d.ts.map +1 -1
  24. package/dist/types/components/Badge/index.d.ts +1 -1
  25. package/dist/types/components/Button/Button.d.ts +3 -3
  26. package/dist/types/components/CollapsibleTable/CollapsibleTable.d.ts +3 -3
  27. package/dist/types/components/Command/index.d.ts +11 -11
  28. package/dist/types/components/Container/index.d.ts +6 -6
  29. package/dist/types/components/DictionaryFieldEditor/DictionaryDetails/useDictionaryDetailsSchema.d.ts +1 -1
  30. package/dist/types/components/Form/FormBase.d.ts +4 -1
  31. package/dist/types/components/Form/FormBase.d.ts.map +1 -1
  32. package/dist/types/components/Input/Checkbox.d.ts +3 -3
  33. package/dist/types/components/Input/Input.d.ts +2 -2
  34. package/dist/types/components/Input/OTPInput.d.ts +1 -1
  35. package/dist/types/components/Link/Link.d.ts +2 -2
  36. package/dist/types/components/MarkDownRender/MarkDownRender.d.ts +3 -3
  37. package/dist/types/components/MarkDownRender/MarkDownRender.d.ts.map +1 -1
  38. package/dist/types/components/MarkDownRender/index.d.ts +2 -2
  39. package/dist/types/components/Pagination/Pagination.d.ts +1 -1
  40. package/dist/types/components/SwitchSelector/SwitchSelector.d.ts +1 -1
  41. package/dist/types/components/SwitchSelector/VerticalSwitchSelector.d.ts +1 -1
  42. package/dist/types/components/Tag/index.d.ts +2 -2
  43. package/dist/types/components/Toaster/Toast.d.ts +1 -1
  44. package/dist/types/components/index.d.ts +2 -2
  45. package/dist/types/libs/auth.d.ts +1 -1
  46. package/dist/types/libs/auth.d.ts.map +1 -1
  47. package/dist/types/routes.d.ts +3 -1
  48. package/dist/types/routes.d.ts.map +1 -1
  49. package/package.json +24 -24
  50. package/tailwind.css +4 -6
@@ -1,17 +1,17 @@
1
1
  'use client';
2
2
 
3
+ import { editor } from "@intlayer/config/built";
3
4
  import { useQuery } from "@tanstack/react-query";
4
- import configuration from "@intlayer/config/built";
5
5
  import { getOAuthAPI } from "@intlayer/api";
6
6
  import { useConfiguration } from "@intlayer/editor-react";
7
7
  import { defu } from "defu";
8
8
 
9
9
  //#region src/api/useAuth/useOAuth2.ts
10
10
  const useOAuth2 = (intlayerConfiguration) => {
11
- const config = defu(intlayerConfiguration, useConfiguration(), configuration);
11
+ const config = defu(intlayerConfiguration, useConfiguration(), { editor });
12
12
  const { data } = useQuery({
13
13
  queryKey: ["oAuth2AccessToken"],
14
- queryFn: getOAuthAPI(config).getOAuth2AccessToken,
14
+ queryFn: getOAuthAPI(void 0, config).getOAuth2AccessToken,
15
15
  enabled: !!(config.editor.clientId && config.editor.clientSecret),
16
16
  staleTime: 0,
17
17
  gcTime: 0,
@@ -1 +1 @@
1
- {"version":3,"file":"useOAuth2.mjs","names":["defaultConfiguration"],"sources":["../../../../src/api/useAuth/useOAuth2.ts"],"sourcesContent":["'use client';\n\nimport { getOAuthAPI } from '@intlayer/api';\nimport { default as defaultConfiguration } from '@intlayer/config/built';\nimport { useConfiguration } from '@intlayer/editor-react';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport { useQuery } from '@tanstack/react-query';\nimport { defu } from 'defu';\n\nexport const useOAuth2 = (intlayerConfiguration?: IntlayerConfig) => {\n const configuration = useConfiguration();\n const config = defu(\n intlayerConfiguration,\n configuration,\n defaultConfiguration\n );\n\n const intlayerAPI = getOAuthAPI(config);\n\n const { data } = useQuery({\n queryKey: ['oAuth2AccessToken'],\n queryFn: intlayerAPI.getOAuth2AccessToken,\n enabled: !!(config.editor.clientId && config.editor.clientSecret),\n staleTime: 0,\n gcTime: 0,\n refetchOnWindowFocus: false,\n refetchOnMount: false,\n refetchOnReconnect: false,\n refetchInterval: false,\n refetchIntervalInBackground: false,\n });\n\n const oAuth2AccessToken = data?.data;\n\n return {\n oAuth2AccessToken,\n };\n};\n"],"mappings":";;;;;;;;;AASA,MAAa,aAAa,0BAA2C;CAEnE,MAAM,SAAS,KACb,uBAFoB,iBAGR,GACZA,aACF;CAIA,MAAM,EAAE,SAAS,SAAS;EACxB,UAAU,CAAC,mBAAmB;EAC9B,SAJkB,YAAY,MAIX,EAAE;EACrB,SAAS,CAAC,EAAE,OAAO,OAAO,YAAY,OAAO,OAAO;EACpD,WAAW;EACX,QAAQ;EACR,sBAAsB;EACtB,gBAAgB;EAChB,oBAAoB;EACpB,iBAAiB;EACjB,6BAA6B;CAC/B,CAAC;CAID,OAAO,EACL,mBAHwB,MAAM,KAIhC;AACF"}
1
+ {"version":3,"file":"useOAuth2.mjs","names":[],"sources":["../../../../src/api/useAuth/useOAuth2.ts"],"sourcesContent":["'use client';\n\nimport { getOAuthAPI } from '@intlayer/api';\nimport { editor } from '@intlayer/config/built';\nimport { useConfiguration } from '@intlayer/editor-react';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport { useQuery } from '@tanstack/react-query';\nimport { defu } from 'defu';\n\nexport const useOAuth2 = (\n intlayerConfiguration?: Pick<IntlayerConfig, 'editor'>\n) => {\n const configuration = useConfiguration();\n const config = defu(intlayerConfiguration, configuration, {\n editor,\n }) as IntlayerConfig;\n\n const intlayerAPI = getOAuthAPI(undefined, config);\n\n const { data } = useQuery({\n queryKey: ['oAuth2AccessToken'],\n queryFn: intlayerAPI.getOAuth2AccessToken,\n enabled: !!(config.editor.clientId && config.editor.clientSecret),\n staleTime: 0,\n gcTime: 0,\n refetchOnWindowFocus: false,\n refetchOnMount: false,\n refetchOnReconnect: false,\n refetchInterval: false,\n refetchIntervalInBackground: false,\n });\n\n const oAuth2AccessToken = data?.data;\n\n return {\n oAuth2AccessToken,\n };\n};\n"],"mappings":";;;;;;;;;AASA,MAAa,aACX,0BACG;CAEH,MAAM,SAAS,KAAK,uBADE,iBACiC,GAAG,EACxD,OACF,CAAC;CAID,MAAM,EAAE,SAAS,SAAS;EACxB,UAAU,CAAC,mBAAmB;EAC9B,SAJkB,YAAY,QAAW,MAItB,EAAE;EACrB,SAAS,CAAC,EAAE,OAAO,OAAO,YAAY,OAAO,OAAO;EACpD,WAAW;EACX,QAAQ;EACR,sBAAsB;EACtB,gBAAgB;EAChB,oBAAoB;EACpB,iBAAiB;EACjB,6BAA6B;CAC/B,CAAC;CAID,OAAO,EACL,mBAHwB,MAAM,KAIhC;AACF"}
@@ -1,14 +1,14 @@
1
1
  'use client';
2
2
 
3
3
  import { getAuthAPI } from "../../libs/auth.mjs";
4
+ import { editor } from "@intlayer/config/built";
4
5
  import { useQuery, useQueryClient } from "@tanstack/react-query";
5
- import configuration from "@intlayer/config/built";
6
6
  import { useConfiguration } from "@intlayer/editor-react";
7
7
 
8
8
  //#region src/api/useAuth/useSession.ts
9
9
  const useSession = (sessionProp, intlayerConfiguration) => {
10
- const configuration$1 = useConfiguration();
11
- const config = intlayerConfiguration ?? configuration$1 ?? configuration;
10
+ const configuration = useConfiguration();
11
+ const config = intlayerConfiguration ?? configuration ?? { editor };
12
12
  const queryClient = useQueryClient();
13
13
  const { data, isFetched, refetch } = useQuery({
14
14
  queryKey: ["session"],
@@ -1 +1 @@
1
- {"version":3,"file":"useSession.mjs","names":["configuration","defaultConfiguration"],"sources":["../../../../src/api/useAuth/useSession.ts"],"sourcesContent":["'use client';\n\nimport type { SessionAPI } from '@intlayer/backend';\nimport { default as defaultConfiguration } from '@intlayer/config/built';\nimport { useConfiguration } from '@intlayer/editor-react';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport { useQuery, useQueryClient } from '@tanstack/react-query';\nimport { getAuthAPI } from '../../libs/auth';\n\nexport type UseSessionResult = {\n /** The current session: `undefined` while loading, `null` if fetched and no session, otherwise the session. */\n session: SessionAPI | null | undefined;\n /** Refetches the session and returns it (undefined while loading). */\n fetchSession: () => Promise<SessionAPI | null | undefined>;\n /** Alias of `fetchSession` for ergonomics. */\n revalidateSession: () => Promise<SessionAPI | null | undefined>;\n /** Manually set the session cache. */\n setSession: (nextSession: SessionAPI | null) => void;\n};\n\nexport const useSession = (\n sessionProp?: SessionAPI | null,\n intlayerConfiguration?: IntlayerConfig\n): UseSessionResult => {\n const configuration = useConfiguration();\n const config = (intlayerConfiguration ??\n configuration ??\n defaultConfiguration) as IntlayerConfig;\n\n const queryClient = useQueryClient();\n\n // Keep TanStack generics internal so they don't leak into the d.ts\n const { data, isFetched, refetch } = useQuery({\n queryKey: ['session'],\n queryFn: async () => {\n const intlayerAPI = getAuthAPI(config);\n const result = await intlayerAPI.getSession();\n // Narrow to the public shape we want to expose\n return result.data as unknown as SessionAPI;\n },\n // Session data rarely changes during navigation, so keep it fresh for 5 minutes\n // This prevents unnecessary refetches when navigating between pages\n staleTime: 5 * 60 * 1000,\n gcTime: 30 * 60 * 1000,\n // Periodically revalidate so the backend's sliding session-refresh\n // (better-auth `updateAge`) keeps the cookie alive for active users.\n refetchInterval: 10 * 60 * 1000,\n refetchIntervalInBackground: false,\n refetchOnMount: true,\n // Refetching on focus/reconnect lets a returning user get a fresh,\n // extended session without a manual reload.\n refetchOnWindowFocus: true,\n refetchOnReconnect: true,\n enabled: !sessionProp,\n });\n\n const session = data ?? (isFetched ? null : undefined);\n\n const setSession = (nextSession: SessionAPI | null) => {\n queryClient.setQueryData(['session'], nextSession);\n };\n\n const fetchSession = async (): Promise<SessionAPI | null | undefined> => {\n const res = await refetch();\n return res.data as SessionAPI | null | undefined;\n };\n\n const revalidateSession = fetchSession;\n\n return {\n session,\n fetchSession,\n revalidateSession,\n setSession,\n };\n};\n"],"mappings":";;;;;;;;AAoBA,MAAa,cACX,aACA,0BACqB;CACrB,MAAMA,kBAAgB,iBAAiB;CACvC,MAAM,SAAU,yBACdA,mBACAC;CAEF,MAAM,cAAc,eAAe;CAGnC,MAAM,EAAE,MAAM,WAAW,YAAY,SAAS;EAC5C,UAAU,CAAC,SAAS;EACpB,SAAS,YAAY;GAInB,QAAO,MAHa,WAAW,MACA,EAAE,WAAW,GAE9B;EAChB;EAGA,WAAW,MAAS;EACpB,QAAQ,OAAU;EAGlB,iBAAiB,MAAU;EAC3B,6BAA6B;EAC7B,gBAAgB;EAGhB,sBAAsB;EACtB,oBAAoB;EACpB,SAAS,CAAC;CACZ,CAAC;CAED,MAAM,UAAU,SAAS,YAAY,OAAO;CAE5C,MAAM,cAAc,gBAAmC;EACrD,YAAY,aAAa,CAAC,SAAS,GAAG,WAAW;CACnD;CAEA,MAAM,eAAe,YAAoD;EAEvE,QAAO,MADW,QAAQ,GACf;CACb;CAIA,OAAO;EACL;EACA;EACA;EACA;CACF;AACF"}
1
+ {"version":3,"file":"useSession.mjs","names":[],"sources":["../../../../src/api/useAuth/useSession.ts"],"sourcesContent":["'use client';\n\nimport type { SessionAPI } from '@intlayer/backend';\nimport { editor } from '@intlayer/config/built';\nimport { useConfiguration } from '@intlayer/editor-react';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport { useQuery, useQueryClient } from '@tanstack/react-query';\nimport { getAuthAPI } from '../../libs/auth';\n\nexport type UseSessionResult = {\n /** The current session: `undefined` while loading, `null` if fetched and no session, otherwise the session. */\n session: SessionAPI | null | undefined;\n /** Refetches the session and returns it (undefined while loading). */\n fetchSession: () => Promise<SessionAPI | null | undefined>;\n /** Alias of `fetchSession` for ergonomics. */\n revalidateSession: () => Promise<SessionAPI | null | undefined>;\n /** Manually set the session cache. */\n setSession: (nextSession: SessionAPI | null) => void;\n};\n\nexport const useSession = (\n sessionProp?: SessionAPI | null,\n intlayerConfiguration?: IntlayerConfig\n): UseSessionResult => {\n const configuration = useConfiguration();\n const config = (intlayerConfiguration ??\n configuration ?? { editor }) as IntlayerConfig;\n\n const queryClient = useQueryClient();\n\n // Keep TanStack generics internal so they don't leak into the d.ts\n const { data, isFetched, refetch } = useQuery({\n queryKey: ['session'],\n queryFn: async () => {\n const intlayerAPI = getAuthAPI(config);\n const result = await intlayerAPI.getSession();\n // Narrow to the public shape we want to expose\n return result.data as unknown as SessionAPI;\n },\n // Session data rarely changes during navigation, so keep it fresh for 5 minutes\n // This prevents unnecessary refetches when navigating between pages\n staleTime: 5 * 60 * 1000,\n gcTime: 30 * 60 * 1000,\n // Periodically revalidate so the backend's sliding session-refresh\n // (better-auth `updateAge`) keeps the cookie alive for active users.\n refetchInterval: 10 * 60 * 1000,\n refetchIntervalInBackground: false,\n refetchOnMount: true,\n // Refetching on focus/reconnect lets a returning user get a fresh,\n // extended session without a manual reload.\n refetchOnWindowFocus: true,\n refetchOnReconnect: true,\n enabled: !sessionProp,\n });\n\n const session = data ?? (isFetched ? null : undefined);\n\n const setSession = (nextSession: SessionAPI | null) => {\n queryClient.setQueryData(['session'], nextSession);\n };\n\n const fetchSession = async (): Promise<SessionAPI | null | undefined> => {\n const res = await refetch();\n return res.data as SessionAPI | null | undefined;\n };\n\n const revalidateSession = fetchSession;\n\n return {\n session,\n fetchSession,\n revalidateSession,\n setSession,\n };\n};\n"],"mappings":";;;;;;;;AAoBA,MAAa,cACX,aACA,0BACqB;CACrB,MAAM,gBAAgB,iBAAiB;CACvC,MAAM,SAAU,yBACd,iBAAiB,EAAE,OAAO;CAE5B,MAAM,cAAc,eAAe;CAGnC,MAAM,EAAE,MAAM,WAAW,YAAY,SAAS;EAC5C,UAAU,CAAC,SAAS;EACpB,SAAS,YAAY;GAInB,QAAO,MAHa,WAAW,MACA,EAAE,WAAW,GAE9B;EAChB;EAGA,WAAW,MAAS;EACpB,QAAQ,OAAU;EAGlB,iBAAiB,MAAU;EAC3B,6BAA6B;EAC7B,gBAAgB;EAGhB,sBAAsB;EACtB,oBAAoB;EACpB,SAAS,CAAC;CACZ,CAAC;CAED,MAAM,UAAU,SAAS,YAAY,OAAO;CAE5C,MAAM,cAAc,gBAAmC;EACrD,YAAY,aAAa,CAAC,SAAS,GAAG,WAAW;CACnD;CAEA,MAAM,eAAe,YAAoD;EAEvE,QAAO,MADW,QAAQ,GACf;CACb;CAIA,OAAO;EACL;EACA;EACA;EACA;CACF;AACF"}
@@ -301,7 +301,7 @@ const Browser = ({ initialUrl = "https://example.com", path, className, style, s
301
301
  isOverable: true,
302
302
  children: /* @__PURE__ */ jsxs(Container, {
303
303
  className: "min-w-28 rounded-md!",
304
- roundedSize: "sm",
304
+ roundedSize: "xl",
305
305
  border: true,
306
306
  borderColor: "neutral",
307
307
  children: [/* @__PURE__ */ jsx("div", {
@@ -1 +1 @@
1
- {"version":3,"file":"Browser.mjs","names":[],"sources":["../../../../src/components/Browser/Browser.tsx"],"sourcesContent":["'use client';\n\nimport { Container } from '@components/Container';\nimport { cn } from '@utils/cn';\nimport { ArrowLeft, ArrowRight, RotateCw, ScanSearch } from 'lucide-react';\nimport {\n type CSSProperties,\n type HTMLAttributes,\n type RefObject,\n type SubmitEvent,\n useEffect,\n useImperativeHandle,\n useMemo,\n useRef,\n useState,\n} from 'react';\nimport { useIntlayer } from 'react-intlayer';\nimport { Button } from '../Button';\nimport { ClickOutsideDiv } from '../ClickOutsideDiv';\nimport { DropDown } from '../DropDown';\nimport { Input, inputVariants } from '../Input';\n\nexport type BrowserProps = {\n initialUrl?: string;\n path?: string;\n className?: string;\n style?: CSSProperties;\n size?: 'xs' | 'sm' | 'md' | 'lg' | 'xl';\n 'aria-label'?: string;\n sandbox?: string;\n ref?: RefObject<HTMLIFrameElement | null>;\n domainRestriction?: string;\n} & HTMLAttributes<HTMLIFrameElement>;\n\nconst UrlPath = ({ url }: { url: string }) => {\n const parts = getUrlPath(url).split('/').filter(Boolean);\n\n if (parts.length === 0) return <span>/</span>;\n\n return parts.flatMap((part, index, array) => [\n <span key={`part-${index}`}>{part}</span>,\n index < array.length - 1 && (\n <span key={`sep-${index}`} className=\"mx-2 text-neutral\">\n /\n </span>\n ),\n ]);\n};\n\nconst getUrlPath = (url: string) => {\n try {\n const { pathname, search, hash } = new URL(url);\n\n return `${pathname}${search}${hash}` || '/';\n } catch {\n return url;\n }\n};\n\nexport const Browser = ({\n initialUrl = 'https://example.com',\n path,\n className,\n style,\n size = 'md',\n 'aria-label': ariaLabel,\n sandbox = 'allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox allow-downloads',\n ref,\n domainRestriction,\n ...props\n}: BrowserProps) => {\n // --- State -----------------------------------------------------------------\n const [inputUrl, setInputUrl] = useState(initialUrl);\n const [currentUrl, setCurrentUrl] = useState(initialUrl);\n\n // History Management\n const [history, setHistory] = useState<string[]>([initialUrl]);\n const [currentIndex, setCurrentIndex] = useState(0);\n\n const [error, setError] = useState<string | null>(null);\n const [submitted, setSubmitted] = useState(false);\n const internalIframeRef = useRef<HTMLIFrameElement>(null);\n\n // Sitemap explorer state\n const [sitemapOpen, setSitemapOpen] = useState(false);\n const [sitemapUrls, setSitemapUrls] = useState<string[]>([]);\n const [sitemapSearch, setSitemapSearch] = useState('');\n const [sitemapLoading, setSitemapLoading] = useState(false);\n const [sitemapFetched, setSitemapFetched] = useState(false);\n const [sitemapError, setSitemapError] = useState(false);\n const sitemapInputRef = useRef<HTMLInputElement>(null);\n\n useImperativeHandle(ref, () => internalIframeRef.current!, []);\n const content = useIntlayer('browser');\n\n // --- Effects ---------------------------------------------------------------\n\n // Reset everything if initialUrl changes completely\n useEffect(() => {\n setInputUrl(initialUrl);\n setCurrentUrl(initialUrl);\n setHistory([initialUrl]);\n setCurrentIndex(0);\n setError(null);\n setSubmitted(false);\n setSitemapOpen(false);\n setSitemapUrls([]);\n setSitemapSearch('');\n setSitemapFetched(false);\n setSitemapError(false);\n }, [initialUrl]);\n\n // Sync external path changes with the URL bar and History\n useEffect(() => {\n if (!path) return;\n\n try {\n const baseOrigin = domainRestriction ?? initialUrl;\n const origin = new URL(baseOrigin).origin;\n const fullUrl = `${origin}${path}`;\n\n // Update Input (Always update the visual bar)\n setInputUrl(fullUrl);\n\n // Check internal iframe state to avoid reload if already there\n let isAlreadyAtUrl = false;\n if (internalIframeRef.current?.contentWindow) {\n try {\n const currentIframeHref =\n internalIframeRef.current.contentWindow.location.href;\n if (new URL(currentIframeHref).href === new URL(fullUrl).href) {\n isAlreadyAtUrl = true;\n }\n } catch {\n // Cross-origin access ignored\n }\n }\n\n // Update History Stack regardless of isAlreadyAtUrl so arrow navigation is always correct\n if (history[currentIndex] !== fullUrl) {\n setHistory((prev) => {\n const newHistory = prev.slice(0, currentIndex + 1);\n newHistory.push(fullUrl);\n return newHistory;\n });\n setCurrentIndex((prev) => prev + 1);\n }\n\n // Navigate only if NOT already there to avoid refreshing on internal iframe navigation\n if (!isAlreadyAtUrl) {\n setCurrentUrl(fullUrl);\n }\n\n setError(null);\n } catch {\n // Ignore invalid paths\n }\n }, [path, domainRestriction, initialUrl]); // Removed currentIndex dependency to prevent loops\n\n // Imperatively keep the iframe src in sync with currentUrl.\n // React's attribute reconciliation can be unreliable for cross-origin iframes after\n // internal navigation, so this effect is the source of truth for navigation.\n useEffect(() => {\n const iframe = internalIframeRef.current;\n if (!iframe) return;\n if (iframe.src !== currentUrl) {\n iframe.src = currentUrl;\n }\n }, [currentUrl]);\n\n // --- Navigation Logic ------------------------------------------------------\n\n const handleNavigateTo = (url: string) => {\n try {\n const validated = normalizeUrl(url);\n\n // If we are navigating to the exact same URL, just reload\n if (validated === currentUrl) {\n handleReload();\n return;\n }\n\n setCurrentUrl(validated);\n setInputUrl(validated);\n setError(null);\n\n // Update History: Slice future if we went back, then push new\n const newHistory = history.slice(0, currentIndex + 1);\n newHistory.push(validated);\n setHistory(newHistory);\n setCurrentIndex(newHistory.length - 1);\n } catch (e) {\n if (\n e instanceof Error &&\n e.message === 'URL does not match allowed domain' &&\n domainRestriction\n ) {\n setError(\n content.domainRestrictionError?.value ??\n `Only URLs from ${domainRestriction} are allowed.`\n );\n } else {\n setError(content.errorMessage.value);\n }\n }\n };\n\n const handleBack = () => {\n if (currentIndex > 0) {\n const newIndex = currentIndex - 1;\n const prevUrl = history[newIndex];\n setCurrentIndex(newIndex);\n setCurrentUrl(prevUrl);\n setInputUrl(prevUrl);\n setError(null);\n }\n };\n\n const handleForward = () => {\n if (currentIndex < history.length - 1) {\n const newIndex = currentIndex + 1;\n const nextUrl = history[newIndex];\n setCurrentIndex(newIndex);\n setCurrentUrl(nextUrl);\n setInputUrl(nextUrl);\n setError(null);\n }\n };\n\n const handleSubmit = (e: SubmitEvent<HTMLFormElement>) => {\n e.preventDefault();\n setSubmitted(true);\n handleNavigateTo(inputUrl);\n };\n\n const handleReload = () => {\n const iframe = internalIframeRef.current;\n if (!iframe) return;\n const src = iframe.src;\n iframe.src = '';\n setTimeout(() => {\n if (internalIframeRef.current) internalIframeRef.current.src = src;\n }, 50);\n };\n\n // --- Validation Helpers ----------------------------------------------------\n const isValidHostname = (host: string) => {\n if (host === 'localhost') return true;\n if (/^(\\d{1,3}\\.){3}\\d{1,3}$/.test(host)) return true;\n if (/^[a-f0-9:]+$/i.test(host)) return true;\n if (!/^[a-z0-9.-]+$/i.test(host)) return false;\n if (/^[-.]/.test(host) || /[-.]$/.test(host)) return false;\n if (host.includes('..')) return false;\n if (!host.includes('.')) return false;\n return true;\n };\n\n const getRestrictionOrigin = (): URL | null => {\n if (!domainRestriction) return null;\n try {\n return new URL(domainRestriction);\n } catch {\n return null;\n }\n };\n\n const normalizeUrl = (raw: string) => {\n const trimmed = raw.trim();\n if (!trimmed || /\\s/.test(trimmed)) throw new Error('Invalid');\n\n const restrictionOrigin = getRestrictionOrigin();\n const isRelativePath = trimmed.startsWith('/') && !trimmed.startsWith('//');\n\n if (isRelativePath) {\n if (restrictionOrigin) {\n return new URL(`${restrictionOrigin.origin}${trimmed}`).toString();\n }\n return new URL(`${new URL(currentUrl).origin}${trimmed}`).toString();\n }\n\n const hasProtocol = /^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(trimmed);\n const candidate = hasProtocol ? trimmed : `https://${trimmed}`;\n const url = new URL(candidate);\n\n if (url.protocol !== 'http:' && url.protocol !== 'https:') {\n throw new Error('Only http(s) is allowed');\n }\n\n if (!isValidHostname(url.hostname)) throw new Error('Invalid host');\n\n if (restrictionOrigin) {\n const urlMatches =\n url.hostname === restrictionOrigin.hostname &&\n url.protocol === restrictionOrigin.protocol &&\n (restrictionOrigin.port === '' ||\n url.port === restrictionOrigin.port ||\n url.host === restrictionOrigin.host);\n\n if (!urlMatches) throw new Error('URL does not match allowed domain');\n }\n\n return url.toString();\n };\n\n const handleSitemapToggle = async () => {\n const nextOpen = !sitemapOpen;\n setSitemapOpen(nextOpen);\n\n if (nextOpen && !sitemapFetched) {\n setSitemapLoading(true);\n setSitemapError(false);\n setSitemapFetched(true);\n try {\n const { extractUrlFromSitemap } = await import(\n './extractUrlFromSitemap'\n );\n const urls = await extractUrlFromSitemap(currentUrl);\n setSitemapUrls(urls);\n if (urls.length === 0) setSitemapError(false);\n } catch {\n setSitemapError(true);\n } finally {\n setSitemapLoading(false);\n }\n setTimeout(() => sitemapInputRef.current?.focus(), 50);\n }\n };\n\n const filteredSitemapUrls = useMemo(() => {\n const query = sitemapSearch.trim().toLowerCase();\n if (!query) return sitemapUrls;\n return sitemapUrls.filter((url) => url.toLowerCase().includes(query));\n }, [sitemapUrls, sitemapSearch]);\n\n const showError = submitted && !!error;\n const canGoBack = currentIndex > 0;\n const canGoForward = currentIndex < history.length - 1;\n\n return (\n <section\n className={cn(\n 'flex w-full flex-col overflow-hidden rounded-xl bg-background shadow-[0_4px_12px_rgba(0,0,0,0.4),0_0_1px_rgba(0,0,0,0.2)]',\n className\n )}\n style={style}\n aria-label={ariaLabel ?? content.ariaLabel.value}\n >\n {/* Top bar */}\n <div className=\"relative z-10 flex shrink-0 items-center gap-3 rounded-t-xl bg-text/15 px-4 py-2\">\n {/* Navigation Controls */}\n <div className=\"flex items-center gap-1\">\n <Button\n type=\"button\"\n onClick={handleBack}\n disabled={!canGoBack}\n variant=\"hoverable\"\n size=\"icon-md\"\n label={content.backButtonLabel.value}\n Icon={ArrowLeft}\n />\n <Button\n type=\"button\"\n onClick={handleForward}\n disabled={!canGoForward}\n variant=\"hoverable\"\n size=\"icon-md\"\n label={content.forwardButtonLabel.value}\n Icon={ArrowRight}\n />\n </div>\n\n {/* URL Bar */}\n <form\n onSubmit={handleSubmit}\n noValidate\n className={cn(\n inputVariants(),\n 'flex w-full gap-2 rounded-xl p-0.5! supports-[corner-shape:squircle]:rounded-2xl',\n 'bg-neutral/10 text-text/50 placeholder:text-neutral/80'\n )}\n >\n <label htmlFor=\"browser-url\" className=\"sr-only\">\n {content.urlLabel}\n </label>\n <Input\n id=\"browser-url\"\n type=\"text\"\n inputMode=\"url\"\n spellCheck={false}\n autoCapitalize=\"off\"\n variant=\"invisible\"\n className=\"ml-3 p-0!\"\n size=\"sm\"\n autoCorrect=\"off\"\n value={inputUrl}\n onChange={(e) => {\n setInputUrl(e.target.value);\n if (showError) setError(null);\n }}\n placeholder={content.urlPlaceholder.value}\n aria-label={content.urlLabel.value}\n aria-invalid={showError}\n aria-describedby={showError ? 'browser-url-error' : undefined}\n />\n\n <Button\n type=\"button\"\n onClick={handleReload}\n variant=\"hoverable\"\n size=\"icon-md\"\n className=\"p-1!\"\n label={'content.reloadButtonTitle.value'}\n Icon={RotateCw}\n />\n\n {/* invisible submit */}\n <button type=\"submit\" className=\"sr-only absolute\" tabIndex={-1} />\n </form>\n\n {/* Sitemap Explorer */}\n <ClickOutsideDiv\n onClickOutSide={() => setSitemapOpen(false)}\n disabled={!sitemapOpen}\n role=\"none\"\n >\n <DropDown identifier=\"sitemap-explorer\">\n <DropDown.Trigger\n identifier=\"sitemap-explorer-trigger\"\n type=\"button\"\n color=\"text\"\n onClick={handleSitemapToggle}\n variant=\"hoverable\"\n size=\"icon-md\"\n label={content.sitemapButtonLabel.value}\n Icon={ScanSearch}\n />\n\n <DropDown.Panel\n identifier=\"sitemap-explorer\"\n isHidden={!sitemapOpen}\n align=\"end\"\n isFocusable\n isOverable\n >\n <Container\n className=\"min-w-28 rounded-md!\"\n roundedSize=\"sm\"\n border\n borderColor=\"neutral\"\n >\n <div className=\"p-2\">\n <Input\n type=\"search\"\n ref={sitemapInputRef}\n aria-label={content.sitemapSearchAriaLabel.value}\n placeholder={content.sitemapSearchPlaceholder.value}\n onChange={(e) => setSitemapSearch(e.target.value)}\n value={sitemapSearch}\n size=\"sm\"\n />\n </div>\n <ul\n className=\"max-h-64 divide-y divide-dotted divide-neutral/30 overflow-y-auto p-1 text-center\"\n aria-label={content.sitemapButtonLabel.value}\n >\n {sitemapLoading ? (\n <li className=\"px-3 py-4 text-center text-neutral text-xs\">\n {content.sitemapLoading}\n </li>\n ) : sitemapError ||\n (!sitemapLoading && filteredSitemapUrls.length === 0) ? (\n <li className=\"px-3 py-4 text-center text-neutral text-xs\">\n {sitemapError\n ? content.sitemapError\n : content.sitemapEmpty}\n </li>\n ) : (\n filteredSitemapUrls.map((url) => (\n <li key={url} className=\"py-0.5\">\n <Button\n variant=\"hoverable\"\n color=\"text\"\n size=\"sm\"\n className=\"w-full text-left\"\n label={url}\n onClick={() => {\n handleNavigateTo(url);\n setSitemapOpen(false);\n }}\n >\n <span className=\"max-w-64 truncate text-left text-base\">\n <UrlPath url={url} />\n </span>\n </Button>\n </li>\n ))\n )}\n </ul>\n </Container>\n </DropDown.Panel>\n </DropDown>\n </ClickOutsideDiv>\n\n {/* Error Message Tooltip */}\n {showError && (\n <div className=\"absolute top-full left-4 z-20 mt-1\">\n <p\n id=\"browser-url-error\"\n role=\"alert\"\n aria-live=\"assertive\"\n className=\"rounded-md bg-red-900/90 px-3 py-1.5 text-red-100 text-xs shadow-md backdrop-blur-sm\"\n >\n {error}\n </p>\n </div>\n )}\n </div>\n\n {/* Iframe */}\n <div className=\"relative z-0 flex min-h-0 w-full flex-1 flex-col overflow-hidden rounded-b-xl bg-background\">\n <iframe\n ref={internalIframeRef}\n src={currentUrl}\n title={content.iframeTitle.value}\n className=\"size-full flex-1\"\n sandbox={sandbox}\n loading=\"lazy\"\n aria-live=\"polite\"\n {...props}\n />\n </div>\n </section>\n );\n};\n"],"mappings":";;;;;;;;;;;;;;AAkCA,MAAM,WAAW,EAAE,UAA2B;CAC5C,MAAM,QAAQ,WAAW,GAAG,EAAE,MAAM,GAAG,EAAE,OAAO,OAAO;CAEvD,IAAI,MAAM,WAAW,GAAG,OAAO,oBAAC,QAAD,YAAM,IAAO;CAE5C,OAAO,MAAM,SAAS,MAAM,OAAO,UAAU,CAC3C,oBAAC,QAAD,YAA6B,KAAW,GAA7B,QAAQ,OAAqB,GACxC,QAAQ,MAAM,SAAS,KACrB,oBAAC,QAAD;EAA2B,WAAU;YAAoB;CAEnD,GAFK,OAAO,OAEZ,CAEV,CAAC;AACH;AAEA,MAAM,cAAc,QAAgB;CAClC,IAAI;EACF,MAAM,EAAE,UAAU,QAAQ,SAAS,IAAI,IAAI,GAAG;EAE9C,OAAO,GAAG,W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BAET;KACA;IACA;GAEJ;MAGL,oBAAC,OAAD;GAAK,WAAU;aACb,oBAAC,UAAD;IACE,KAAK;IACL,KAAK;IACL,OAAO,QAAQ,YAAY;IAC3B,WAAU;IACD;IACT,SAAQ;IACR,aAAU;IACV,GAAI;GACL;EACE,EACE;;AAEb"}
1
+ {"version":3,"file":"Browser.mjs","names":[],"sources":["../../../../src/components/Browser/Browser.tsx"],"sourcesContent":["'use client';\n\nimport { Container } from '@components/Container';\nimport { cn } from '@utils/cn';\nimport { ArrowLeft, ArrowRight, RotateCw, ScanSearch } from 'lucide-react';\nimport {\n type CSSProperties,\n type HTMLAttributes,\n type RefObject,\n type SubmitEvent,\n useEffect,\n useImperativeHandle,\n useMemo,\n useRef,\n useState,\n} from 'react';\nimport { useIntlayer } from 'react-intlayer';\nimport { Button } from '../Button';\nimport { ClickOutsideDiv } from '../ClickOutsideDiv';\nimport { DropDown } from '../DropDown';\nimport { Input, inputVariants } from '../Input';\n\nexport type BrowserProps = {\n initialUrl?: string;\n path?: string;\n className?: string;\n style?: CSSProperties;\n size?: 'xs' | 'sm' | 'md' | 'lg' | 'xl';\n 'aria-label'?: string;\n sandbox?: string;\n ref?: RefObject<HTMLIFrameElement | null>;\n domainRestriction?: string;\n} & HTMLAttributes<HTMLIFrameElement>;\n\nconst UrlPath = ({ url }: { url: string }) => {\n const parts = getUrlPath(url).split('/').filter(Boolean);\n\n if (parts.length === 0) return <span>/</span>;\n\n return parts.flatMap((part, index, array) => [\n <span key={`part-${index}`}>{part}</span>,\n index < array.length - 1 && (\n <span key={`sep-${index}`} className=\"mx-2 text-neutral\">\n /\n </span>\n ),\n ]);\n};\n\nconst getUrlPath = (url: string) => {\n try {\n const { pathname, search, hash } = new URL(url);\n\n return `${pathname}${search}${hash}` || '/';\n } catch {\n return url;\n }\n};\n\nexport const Browser = ({\n initialUrl = 'https://example.com',\n path,\n className,\n style,\n size = 'md',\n 'aria-label': ariaLabel,\n sandbox = 'allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox allow-downloads',\n ref,\n domainRestriction,\n ...props\n}: BrowserProps) => {\n // --- State -----------------------------------------------------------------\n const [inputUrl, setInputUrl] = useState(initialUrl);\n const [currentUrl, setCurrentUrl] = useState(initialUrl);\n\n // History Management\n const [history, setHistory] = useState<string[]>([initialUrl]);\n const [currentIndex, setCurrentIndex] = useState(0);\n\n const [error, setError] = useState<string | null>(null);\n const [submitted, setSubmitted] = useState(false);\n const internalIframeRef = useRef<HTMLIFrameElement>(null);\n\n // Sitemap explorer state\n const [sitemapOpen, setSitemapOpen] = useState(false);\n const [sitemapUrls, setSitemapUrls] = useState<string[]>([]);\n const [sitemapSearch, setSitemapSearch] = useState('');\n const [sitemapLoading, setSitemapLoading] = useState(false);\n const [sitemapFetched, setSitemapFetched] = useState(false);\n const [sitemapError, setSitemapError] = useState(false);\n const sitemapInputRef = useRef<HTMLInputElement>(null);\n\n useImperativeHandle(ref, () => internalIframeRef.current!, []);\n const content = useIntlayer('browser');\n\n // --- Effects ---------------------------------------------------------------\n\n // Reset everything if initialUrl changes completely\n useEffect(() => {\n setInputUrl(initialUrl);\n setCurrentUrl(initialUrl);\n setHistory([initialUrl]);\n setCurrentIndex(0);\n setError(null);\n setSubmitted(false);\n setSitemapOpen(false);\n setSitemapUrls([]);\n setSitemapSearch('');\n setSitemapFetched(false);\n setSitemapError(false);\n }, [initialUrl]);\n\n // Sync external path changes with the URL bar and History\n useEffect(() => {\n if (!path) return;\n\n try {\n const baseOrigin = domainRestriction ?? initialUrl;\n const origin = new URL(baseOrigin).origin;\n const fullUrl = `${origin}${path}`;\n\n // Update Input (Always update the visual bar)\n setInputUrl(fullUrl);\n\n // Check internal iframe state to avoid reload if already there\n let isAlreadyAtUrl = false;\n if (internalIframeRef.current?.contentWindow) {\n try {\n const currentIframeHref =\n internalIframeRef.current.contentWindow.location.href;\n if (new URL(currentIframeHref).href === new URL(fullUrl).href) {\n isAlreadyAtUrl = true;\n }\n } catch {\n // Cross-origin access ignored\n }\n }\n\n // Update History Stack regardless of isAlreadyAtUrl so arrow navigation is always correct\n if (history[currentIndex] !== fullUrl) {\n setHistory((prev) => {\n const newHistory = prev.slice(0, currentIndex + 1);\n newHistory.push(fullUrl);\n return newHistory;\n });\n setCurrentIndex((prev) => prev + 1);\n }\n\n // Navigate only if NOT already there to avoid refreshing on internal iframe navigation\n if (!isAlreadyAtUrl) {\n setCurrentUrl(fullUrl);\n }\n\n setError(null);\n } catch {\n // Ignore invalid paths\n }\n }, [path, domainRestriction, initialUrl]); // Removed currentIndex dependency to prevent loops\n\n // Imperatively keep the iframe src in sync with currentUrl.\n // React's attribute reconciliation can be unreliable for cross-origin iframes after\n // internal navigation, so this effect is the source of truth for navigation.\n useEffect(() => {\n const iframe = internalIframeRef.current;\n if (!iframe) return;\n if (iframe.src !== currentUrl) {\n iframe.src = currentUrl;\n }\n }, [currentUrl]);\n\n // --- Navigation Logic ------------------------------------------------------\n\n const handleNavigateTo = (url: string) => {\n try {\n const validated = normalizeUrl(url);\n\n // If we are navigating to the exact same URL, just reload\n if (validated === currentUrl) {\n handleReload();\n return;\n }\n\n setCurrentUrl(validated);\n setInputUrl(validated);\n setError(null);\n\n // Update History: Slice future if we went back, then push new\n const newHistory = history.slice(0, currentIndex + 1);\n newHistory.push(validated);\n setHistory(newHistory);\n setCurrentIndex(newHistory.length - 1);\n } catch (e) {\n if (\n e instanceof Error &&\n e.message === 'URL does not match allowed domain' &&\n domainRestriction\n ) {\n setError(\n content.domainRestrictionError?.value ??\n `Only URLs from ${domainRestriction} are allowed.`\n );\n } else {\n setError(content.errorMessage.value);\n }\n }\n };\n\n const handleBack = () => {\n if (currentIndex > 0) {\n const newIndex = currentIndex - 1;\n const prevUrl = history[newIndex];\n setCurrentIndex(newIndex);\n setCurrentUrl(prevUrl);\n setInputUrl(prevUrl);\n setError(null);\n }\n };\n\n const handleForward = () => {\n if (currentIndex < history.length - 1) {\n const newIndex = currentIndex + 1;\n const nextUrl = history[newIndex];\n setCurrentIndex(newIndex);\n setCurrentUrl(nextUrl);\n setInputUrl(nextUrl);\n setError(null);\n }\n };\n\n const handleSubmit = (e: SubmitEvent<HTMLFormElement>) => {\n e.preventDefault();\n setSubmitted(true);\n handleNavigateTo(inputUrl);\n };\n\n const handleReload = () => {\n const iframe = internalIframeRef.current;\n if (!iframe) return;\n const src = iframe.src;\n iframe.src = '';\n setTimeout(() => {\n if (internalIframeRef.current) internalIframeRef.current.src = src;\n }, 50);\n };\n\n // --- Validation Helpers ----------------------------------------------------\n const isValidHostname = (host: string) => {\n if (host === 'localhost') return true;\n if (/^(\\d{1,3}\\.){3}\\d{1,3}$/.test(host)) return true;\n if (/^[a-f0-9:]+$/i.test(host)) return true;\n if (!/^[a-z0-9.-]+$/i.test(host)) return false;\n if (/^[-.]/.test(host) || /[-.]$/.test(host)) return false;\n if (host.includes('..')) return false;\n if (!host.includes('.')) return false;\n return true;\n };\n\n const getRestrictionOrigin = (): URL | null => {\n if (!domainRestriction) return null;\n try {\n return new URL(domainRestriction);\n } catch {\n return null;\n }\n };\n\n const normalizeUrl = (raw: string) => {\n const trimmed = raw.trim();\n if (!trimmed || /\\s/.test(trimmed)) throw new Error('Invalid');\n\n const restrictionOrigin = getRestrictionOrigin();\n const isRelativePath = trimmed.startsWith('/') && !trimmed.startsWith('//');\n\n if (isRelativePath) {\n if (restrictionOrigin) {\n return new URL(`${restrictionOrigin.origin}${trimmed}`).toString();\n }\n return new URL(`${new URL(currentUrl).origin}${trimmed}`).toString();\n }\n\n const hasProtocol = /^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(trimmed);\n const candidate = hasProtocol ? trimmed : `https://${trimmed}`;\n const url = new URL(candidate);\n\n if (url.protocol !== 'http:' && url.protocol !== 'https:') {\n throw new Error('Only http(s) is allowed');\n }\n\n if (!isValidHostname(url.hostname)) throw new Error('Invalid host');\n\n if (restrictionOrigin) {\n const urlMatches =\n url.hostname === restrictionOrigin.hostname &&\n url.protocol === restrictionOrigin.protocol &&\n (restrictionOrigin.port === '' ||\n url.port === restrictionOrigin.port ||\n url.host === restrictionOrigin.host);\n\n if (!urlMatches) throw new Error('URL does not match allowed domain');\n }\n\n return url.toString();\n };\n\n const handleSitemapToggle = async () => {\n const nextOpen = !sitemapOpen;\n setSitemapOpen(nextOpen);\n\n if (nextOpen && !sitemapFetched) {\n setSitemapLoading(true);\n setSitemapError(false);\n setSitemapFetched(true);\n try {\n const { extractUrlFromSitemap } = await import(\n './extractUrlFromSitemap'\n );\n const urls = await extractUrlFromSitemap(currentUrl);\n setSitemapUrls(urls);\n if (urls.length === 0) setSitemapError(false);\n } catch {\n setSitemapError(true);\n } finally {\n setSitemapLoading(false);\n }\n setTimeout(() => sitemapInputRef.current?.focus(), 50);\n }\n };\n\n const filteredSitemapUrls = useMemo(() => {\n const query = sitemapSearch.trim().toLowerCase();\n if (!query) return sitemapUrls;\n return sitemapUrls.filter((url) => url.toLowerCase().includes(query));\n }, [sitemapUrls, sitemapSearch]);\n\n const showError = submitted && !!error;\n const canGoBack = currentIndex > 0;\n const canGoForward = currentIndex < history.length - 1;\n\n return (\n <section\n className={cn(\n 'flex w-full flex-col overflow-hidden rounded-xl bg-background shadow-[0_4px_12px_rgba(0,0,0,0.4),0_0_1px_rgba(0,0,0,0.2)]',\n className\n )}\n style={style}\n aria-label={ariaLabel ?? content.ariaLabel.value}\n >\n {/* Top bar */}\n <div className=\"relative z-10 flex shrink-0 items-center gap-3 rounded-t-xl bg-text/15 px-4 py-2\">\n {/* Navigation Controls */}\n <div className=\"flex items-center gap-1\">\n <Button\n type=\"button\"\n onClick={handleBack}\n disabled={!canGoBack}\n variant=\"hoverable\"\n size=\"icon-md\"\n label={content.backButtonLabel.value}\n Icon={ArrowLeft}\n />\n <Button\n type=\"button\"\n onClick={handleForward}\n disabled={!canGoForward}\n variant=\"hoverable\"\n size=\"icon-md\"\n label={content.forwardButtonLabel.value}\n Icon={ArrowRight}\n />\n </div>\n\n {/* URL Bar */}\n <form\n onSubmit={handleSubmit}\n noValidate\n className={cn(\n inputVariants(),\n 'flex w-full gap-2 rounded-xl p-0.5! supports-[corner-shape:squircle]:rounded-2xl',\n 'bg-neutral/10 text-text/50 placeholder:text-neutral/80'\n )}\n >\n <label htmlFor=\"browser-url\" className=\"sr-only\">\n {content.urlLabel}\n </label>\n <Input\n id=\"browser-url\"\n type=\"text\"\n inputMode=\"url\"\n spellCheck={false}\n autoCapitalize=\"off\"\n variant=\"invisible\"\n className=\"ml-3 p-0!\"\n size=\"sm\"\n autoCorrect=\"off\"\n value={inputUrl}\n onChange={(e) => {\n setInputUrl(e.target.value);\n if (showError) setError(null);\n }}\n placeholder={content.urlPlaceholder.value}\n aria-label={content.urlLabel.value}\n aria-invalid={showError}\n aria-describedby={showError ? 'browser-url-error' : undefined}\n />\n\n <Button\n type=\"button\"\n onClick={handleReload}\n variant=\"hoverable\"\n size=\"icon-md\"\n className=\"p-1!\"\n label={'content.reloadButtonTitle.value'}\n Icon={RotateCw}\n />\n\n {/* invisible submit */}\n <button type=\"submit\" className=\"sr-only absolute\" tabIndex={-1} />\n </form>\n\n {/* Sitemap Explorer */}\n <ClickOutsideDiv\n onClickOutSide={() => setSitemapOpen(false)}\n disabled={!sitemapOpen}\n role=\"none\"\n >\n <DropDown identifier=\"sitemap-explorer\">\n <DropDown.Trigger\n identifier=\"sitemap-explorer-trigger\"\n type=\"button\"\n color=\"text\"\n onClick={handleSitemapToggle}\n variant=\"hoverable\"\n size=\"icon-md\"\n label={content.sitemapButtonLabel.value}\n Icon={ScanSearch}\n />\n\n <DropDown.Panel\n identifier=\"sitemap-explorer\"\n isHidden={!sitemapOpen}\n align=\"end\"\n isFocusable\n isOverable\n >\n <Container\n className=\"min-w-28 rounded-md!\"\n roundedSize=\"xl\"\n border\n borderColor=\"neutral\"\n >\n <div className=\"p-2\">\n <Input\n type=\"search\"\n ref={sitemapInputRef}\n aria-label={content.sitemapSearchAriaLabel.value}\n placeholder={content.sitemapSearchPlaceholder.value}\n onChange={(e) => setSitemapSearch(e.target.value)}\n value={sitemapSearch}\n size=\"sm\"\n />\n </div>\n <ul\n className=\"max-h-64 divide-y divide-dotted divide-neutral/30 overflow-y-auto p-1 text-center\"\n aria-label={content.sitemapButtonLabel.value}\n >\n {sitemapLoading ? (\n <li className=\"px-3 py-4 text-center text-neutral text-xs\">\n {content.sitemapLoading}\n </li>\n ) : sitemapError ||\n (!sitemapLoading && filteredSitemapUrls.length === 0) ? (\n <li className=\"px-3 py-4 text-center text-neutral text-xs\">\n {sitemapError\n ? content.sitemapError\n : content.sitemapEmpty}\n </li>\n ) : (\n filteredSitemapUrls.map((url) => (\n <li key={url} className=\"py-0.5\">\n <Button\n variant=\"hoverable\"\n color=\"text\"\n size=\"sm\"\n className=\"w-full text-left\"\n label={url}\n onClick={() => {\n handleNavigateTo(url);\n setSitemapOpen(false);\n }}\n >\n <span className=\"max-w-64 truncate text-left text-base\">\n <UrlPath url={url} />\n </span>\n </Button>\n </li>\n ))\n )}\n </ul>\n </Container>\n </DropDown.Panel>\n </DropDown>\n </ClickOutsideDiv>\n\n {/* Error Message Tooltip */}\n {showError && (\n <div className=\"absolute top-full left-4 z-20 mt-1\">\n <p\n id=\"browser-url-error\"\n role=\"alert\"\n aria-live=\"assertive\"\n className=\"rounded-md bg-red-900/90 px-3 py-1.5 text-red-100 text-xs shadow-md backdrop-blur-sm\"\n >\n {error}\n </p>\n </div>\n )}\n </div>\n\n {/* Iframe */}\n <div className=\"relative z-0 flex min-h-0 w-full flex-1 flex-col overflow-hidden rounded-b-xl bg-background\">\n <iframe\n ref={internalIframeRef}\n src={currentUrl}\n title={content.iframeTitle.value}\n className=\"size-full flex-1\"\n sandbox={sandbox}\n loading=\"lazy\"\n aria-live=\"polite\"\n {...props}\n />\n </div>\n </section>\n );\n};\n"],"mappings":";;;;;;;;;;;;;;AAkCA,MAAM,WAAW,EAAE,UAA2B;CAC5C,MAAM,QAAQ,WAAW,GAAG,EAAE,MAAM,GAAG,EAAE,OAAO,OAAO;CA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BAAC,MAAD;UAAc,WAAU;oBACtB,oBAAC,QAAD;WACE,SAAQ;WACR,OAAM;WACN,MAAK;WACL,WAAU;WACV,OAAO;WACP,eAAe;YACb,iBAAiB,GAAG;YACpB,eAAe,KAAK;WACtB;qBAEA,oBAAC,QAAD;YAAM,WAAU;sBACd,oBAAC,SAAD,EAAc,IAAM;WAChB;UACA;SACN,GAhBK,GAgBL,CACL;QAED,EACK;;MACG,EACR;;IACK;IAGhB,aACC,oBAAC,OAAD;KAAK,WAAU;eACb,oBAAC,KAAD;MACE,IAAG;MACH,MAAK;MACL,aAAU;MACV,WAAU;gBAET;KACA;IACA;GAEJ;MAGL,oBAAC,OAAD;GAAK,WAAU;aACb,oBAAC,UAAD;IACE,KAAK;IACL,KAAK;IACL,OAAO,QAAQ,YAAY;IAC3B,WAAU;IACD;IACT,SAAQ;IACR,aAAU;IACV,GAAI;GACL;EACE,EACE;;AAEb"}
@@ -10,7 +10,7 @@ const awaitFunction = async (fn) => {
10
10
  if (fn && typeof fn.then === "function") return await fn;
11
11
  return fn;
12
12
  };
13
- const Form = ({ schema, onSubmit: onSubmitProp, onSubmitSuccess: onSubmitSuccessProp, onSubmitError: onSubmitErrorProp, className, children, autoComplete, ...props }) => {
13
+ const Form = ({ schema, onSubmit: onSubmitProp, onSubmitSuccess: onSubmitSuccessProp, onSubmitError: onSubmitErrorProp, className, children, autoComplete, method, ...props }) => {
14
14
  const onSubmit = async (values) => {
15
15
  const parsedValues = schema?.safeParse(values) ?? {
16
16
  success: true,
@@ -27,6 +27,7 @@ const Form = ({ schema, onSubmit: onSubmitProp, onSubmitSuccess: onSubmitSuccess
27
27
  onSubmit: props.handleSubmit(onSubmit),
28
28
  autoComplete: autoComplete ? "on" : "off",
29
29
  noValidate: true,
30
+ method,
30
31
  children
31
32
  })
32
33
  });
@@ -1 +1 @@
1
- {"version":3,"file":"FormBase.mjs","names":["useFormReactHookForm"],"sources":["../../../../src/components/Form/FormBase.tsx"],"sourcesContent":["'use client';\n\nimport { zodResolver } from '@hookform/resolvers/zod';\nimport { cn } from '@utils/cn';\nimport type { HTMLAttributes } from 'react';\nimport {\n FormProvider,\n type FormProviderProps,\n type UseFormProps,\n useForm as useFormReactHookForm,\n useFormState,\n} from 'react-hook-form';\nimport type { ZodObject, z } from 'zod/v4';\n\ntype FormProps<T extends ZodObject> = HTMLAttributes<HTMLFormElement> &\n FormProviderProps<z.infer<T>> & {\n schema?: T;\n onSubmit?: (data: z.infer<T>) => void | Promise<void>;\n onSubmitSuccess?: (data: z.infer<T>) => void | Promise<void>;\n onSubmitError?: (error: Error) => void | Promise<void>;\n autoComplete?: boolean;\n };\n\nconst awaitFunction = async (fn: any) => {\n // Check if result is a Promise (Thenable)\n\n if (fn && typeof fn.then === 'function') {\n // It's a Promise, so wait for it to resolve\n return await fn;\n }\n // If not a Promise, it will just execute without awaiting\n return fn;\n};\n\nexport const Form = <T extends ZodObject>({\n schema,\n onSubmit: onSubmitProp,\n onSubmitSuccess: onSubmitSuccessProp,\n onSubmitError: onSubmitErrorProp,\n className,\n children,\n autoComplete,\n ...props\n}: FormProps<T>) => {\n const onSubmit = async (values: z.infer<T>) => {\n const parsedValues = schema?.safeParse(values) ?? {\n success: true,\n data: undefined,\n };\n\n // onSubmitProp?.(values);\n await awaitFunction(onSubmitProp?.(values));\n\n if (parsedValues.success) {\n await awaitFunction(onSubmitSuccessProp?.(parsedValues.data!));\n } else {\n await awaitFunction(\n onSubmitErrorProp?.(\n new Error(\n parsedValues.error.issues.map((error) => error.message).join(', ')\n )\n )\n );\n }\n };\n\n return (\n <FormProvider {...props}>\n <form\n className={cn('flex flex-col gap-y-6', className)}\n onSubmit={props.handleSubmit(onSubmit)}\n autoComplete={autoComplete ? 'on' : 'off'}\n noValidate\n >\n {children}\n </form>\n </FormProvider>\n );\n};\n\nexport const useForm = <T extends ZodObject>(\n schema: T,\n props?: UseFormProps<z.infer<T>>\n) => {\n const form = useFormReactHookForm<z.infer<T>>({\n resolver: zodResolver(schema as any),\n ...props,\n });\n\n const { isSubmitting, isSubmitted, isLoading, isValid } = useFormState({\n control: form.control,\n });\n\n return {\n form,\n isSubmitting,\n isSubmitted,\n isLoading,\n isValid,\n };\n};\n"],"mappings":";;;;;;;;AAuBA,MAAM,gBAAgB,OAAO,OAAY;CAGvC,IAAI,MAAM,OAAO,GAAG,SAAS,YAE3B,OAAO,MAAM;CAGf,OAAO;AACT;AAEA,MAAa,QAA6B,EACxC,QACA,UAAU,cACV,iBAAiB,qBACjB,eAAe,mBACf,WACA,UACA,cACA,GAAG,YACe;CAClB,MAAM,WAAW,OAAO,WAAuB;EAC7C,MAAM,eAAe,QAAQ,UAAU,MAAM,KAAK;GAChD,SAAS;GACT,MAAM;EACR;EAGA,MAAM,cAAc,eAAe,MAAM,CAAC;EAE1C,IAAI,aAAa,SACf,MAAM,cAAc,sBAAsB,aAAa,IAAK,CAAC;OAE7D,MAAM,cACJ,oBACE,IAAI,MACF,aAAa,MAAM,OAAO,KAAK,UAAU,MAAM,OAAO,EAAE,KAAK,IAAI,CACnE,CACF,CACF;CAEJ;CAEA,OACE,oBAAC,cAAD;EAAc,GAAI;YAChB,oBAAC,QAAD;GACE,WAAW,GAAG,yBAAyB,SAAS;GAChD,UAAU,MAAM,aAAa,QAAQ;GACrC,cAAc,eAAe,OAAO;GACpC;GAEC;EACG;CACM;AAElB;AAEA,MAAa,WACX,QACA,UACG;CACH,MAAM,OAAOA,UAAiC;EAC5C,UAAU,YAAY,MAAa;EACnC,GAAG;CACL,CAAC;CAED,MAAM,EAAE,cAAc,aAAa,WAAW,YAAY,aAAa,EACrE,SAAS,KAAK,QAChB,CAAC;CAED,OAAO;EACL;EACA;EACA;EACA;EACA;CACF;AACF"}
1
+ {"version":3,"file":"FormBase.mjs","names":["useFormReactHookForm"],"sources":["../../../../src/components/Form/FormBase.tsx"],"sourcesContent":["'use client';\n\nimport { zodResolver } from '@hookform/resolvers/zod';\nimport { cn } from '@utils/cn';\nimport type { HTMLAttributes } from 'react';\nimport {\n FormProvider,\n type FormProviderProps,\n type UseFormProps,\n useForm as useFormReactHookForm,\n useFormState,\n} from 'react-hook-form';\nimport type { ZodObject, z } from 'zod/v4';\n\ntype FormProps<T extends ZodObject> = HTMLAttributes<HTMLFormElement> &\n FormProviderProps<z.infer<T>> & {\n schema?: T;\n onSubmit?: (data: z.infer<T>) => void | Promise<void>;\n onSubmitSuccess?: (data: z.infer<T>) => void | Promise<void>;\n onSubmitError?: (error: Error) => void | Promise<void>;\n autoComplete?: boolean;\n };\n\nconst awaitFunction = async (fn: any) => {\n // Check if result is a Promise (Thenable)\n\n if (fn && typeof fn.then === 'function') {\n // It's a Promise, so wait for it to resolve\n return await fn;\n }\n // If not a Promise, it will just execute without awaiting\n return fn;\n};\n\nexport const Form = <T extends ZodObject>({\n schema,\n onSubmit: onSubmitProp,\n onSubmitSuccess: onSubmitSuccessProp,\n onSubmitError: onSubmitErrorProp,\n className,\n children,\n autoComplete,\n method,\n ...props\n}: FormProps<T> & { method?: string }) => {\n const onSubmit = async (values: z.infer<T>) => {\n const parsedValues = schema?.safeParse(values) ?? {\n success: true,\n data: undefined,\n };\n\n // onSubmitProp?.(values);\n await awaitFunction(onSubmitProp?.(values));\n\n if (parsedValues.success) {\n await awaitFunction(onSubmitSuccessProp?.(parsedValues.data!));\n } else {\n await awaitFunction(\n onSubmitErrorProp?.(\n new Error(\n parsedValues.error.issues.map((error) => error.message).join(', ')\n )\n )\n );\n }\n };\n\n return (\n <FormProvider {...props}>\n <form\n className={cn('flex flex-col gap-y-6', className)}\n onSubmit={props.handleSubmit(onSubmit)}\n autoComplete={autoComplete ? 'on' : 'off'}\n noValidate\n method={method}\n >\n {children}\n </form>\n </FormProvider>\n );\n};\n\nexport const useForm = <T extends ZodObject>(\n schema: T,\n props?: UseFormProps<z.infer<T>>\n) => {\n const form = useFormReactHookForm<z.infer<T>>({\n resolver: zodResolver(schema as any),\n ...props,\n });\n\n const { isSubmitting, isSubmitted, isLoading, isValid } = useFormState({\n control: form.control,\n });\n\n return {\n form,\n isSubmitting,\n isSubmitted,\n isLoading,\n isValid,\n };\n};\n"],"mappings":";;;;;;;;AAuBA,MAAM,gBAAgB,OAAO,OAAY;CAGvC,IAAI,MAAM,OAAO,GAAG,SAAS,YAE3B,OAAO,MAAM;CAGf,OAAO;AACT;AAEA,MAAa,QAA6B,EACxC,QACA,UAAU,cACV,iBAAiB,qBACjB,eAAe,mBACf,WACA,UACA,cACA,QACA,GAAG,YACqC;CACxC,MAAM,WAAW,OAAO,WAAuB;EAC7C,MAAM,eAAe,QAAQ,UAAU,MAAM,KAAK;GAChD,SAAS;GACT,MAAM;EACR;EAGA,MAAM,cAAc,eAAe,MAAM,CAAC;EAE1C,IAAI,aAAa,SACf,MAAM,cAAc,sBAAsB,aAAa,IAAK,CAAC;OAE7D,MAAM,cACJ,oBACE,IAAI,MACF,aAAa,MAAM,OAAO,KAAK,UAAU,MAAM,OAAO,EAAE,KAAK,IAAI,CACnE,CACF,CACF;CAEJ;CAEA,OACE,oBAAC,cAAD;EAAc,GAAI;YAChB,oBAAC,QAAD;GACE,WAAW,GAAG,yBAAyB,SAAS;GAChD,UAAU,MAAM,aAAa,QAAQ;GACrC,cAAc,eAAe,OAAO;GACpC;GACQ;GAEP;EACG;CACM;AAElB;AAEA,MAAa,WACX,QACA,UACG;CACH,MAAM,OAAOA,UAAiC;EAC5C,UAAU,YAAY,MAAa;EACnC,GAAG;CACL,CAAC;CAED,MAAM,EAAE,cAAc,aAAa,WAAW,YAAY,aAAa,EACrE,SAAS,KAAK,QAChB,CAAC;CAED,OAAO;EACL;EACA;EACA;EACA;EACA;CACF;AACF"}
@@ -28,7 +28,7 @@ const parseFormats = (raw) => {
28
28
  } catch {}
29
29
  return [raw];
30
30
  };
31
- const Code = ({ children, language, isDarkMode, showHeader = true, showLineNumbers = true, className, fileName, packageManager, codeFormat: rawCodeFormat, contentDeclarationFormat: rawContentDeclarationFormat, isRollable = true, ...props }) => {
31
+ const Code = ({ children, language, isDarkMode, showHeader = true, showLineNumbers = true, className, fileName, packageManager, codeFormat: rawCodeFormat, contentDeclarationFormat: rawContentDeclarationFormat, isRollable = true, lang, ...props }) => {
32
32
  const { codeFormat: selectedCodeFormat, contentDeclarationFormat: selectedContentDeclarationFormat } = useCodeContext();
33
33
  const codeFormats = useMemo(() => parseFormats(rawCodeFormat), [rawCodeFormat]);
34
34
  const contentFormats = useMemo(() => parseFormats(rawContentDeclarationFormat), [rawContentDeclarationFormat]);
@@ -1 +1 @@
1
- {"version":3,"file":"Code.mjs","names":[],"sources":["../../../../src/components/IDE/Code.tsx"],"sourcesContent":["'use client';\n\nimport { cn } from '@utils/cn';\nimport type { FC, HTMLAttributes, ReactNode } from 'react';\nimport { useEffect, useMemo, useState } from 'react';\nimport type { BundledLanguage } from 'shiki/bundle/web';\nimport { Container } from '../Container';\nimport { ExpandCollapse } from '../ExpandCollapse';\nimport { CodeBlock } from './CodeBlockClient';\nimport { CodeBlockHighlight } from './CodeBlockHighlight';\nimport { CodeConditionalRender } from './CodeConditionalRenderer';\nimport type {\n CodeFormat,\n ContentDeclarationFormat,\n PackageManager,\n} from './CodeContext';\nimport { useCodeContext } from './CodeContext';\nimport { CodeFormatSelector } from './CodeFormatSelector';\nimport { ContentDeclarationFormatSelector } from './ContentDeclarationFormatSelector';\nimport { CopyCode } from './CopyCode';\nimport { PackageManagerSelector } from './PackageManagerSelector';\n\nexport type CodeCompAttributes = {\n fileName?: string;\n packageManager?: PackageManager;\n /** Single format, a JSON-array string, or an array of formats. */\n codeFormat?: CodeFormat | string | string[];\n contentDeclarationFormat?: ContentDeclarationFormat | string | string[];\n};\n\ntype CodeCompProps = {\n children: ReactNode;\n fileName?: string;\n language: BundledLanguage;\n isDarkMode?: boolean;\n showHeader?: boolean;\n showLineNumbers?: boolean;\n isRollable?: boolean;\n} & CodeCompAttributes &\n HTMLAttributes<HTMLDivElement>;\n\nconst MIN_HEIGHT = 700;\n\n/** Languages that use JSX syntax — CommonJS doesn't make sense for these. */\nconst JSX_LANGUAGES = new Set(['tsx', 'jsx']);\n\n/** Parse a codeFormat prop that may be a single value, a JSON-array string, or already an array. */\nconst parseFormats = (\n raw: string | string[] | undefined\n): CodeFormat[] | undefined => {\n if (!raw) return undefined;\n if (Array.isArray(raw)) return raw as CodeFormat[];\n if (typeof raw === 'string' && raw.startsWith('[')) {\n try {\n const parsed = JSON.parse(raw);\n if (Array.isArray(parsed)) return parsed as CodeFormat[];\n } catch {\n /* ignore */\n }\n }\n return [raw as CodeFormat];\n};\n\nexport const Code: FC<CodeCompProps> = ({\n children,\n language,\n isDarkMode,\n showHeader = true,\n showLineNumbers = true,\n className,\n fileName,\n packageManager,\n codeFormat: rawCodeFormat,\n contentDeclarationFormat: rawContentDeclarationFormat,\n isRollable = true,\n ...props\n}) => {\n const {\n codeFormat: selectedCodeFormat,\n contentDeclarationFormat: selectedContentDeclarationFormat,\n } = useCodeContext();\n\n // Parse whichever attribute is present as an array of formats.\n const codeFormats = useMemo(\n () => parseFormats(rawCodeFormat as string | undefined),\n [rawCodeFormat]\n );\n const contentFormats = useMemo(\n () => parseFormats(rawContentDeclarationFormat as string | undefined),\n [rawContentDeclarationFormat]\n );\n\n // A block is \"multi-format\" when it has multiple formats including TypeScript\n // (the canonical source). Such blocks transform at runtime.\n const isMultiCodeFormat =\n codeFormats !== undefined &&\n codeFormats.length > 1 &&\n codeFormats.includes('typescript');\n\n const isMultiContentFormat =\n contentFormats !== undefined &&\n contentFormats.length > 1 &&\n contentFormats.includes('typescript');\n\n const isMultiFormat = isMultiCodeFormat || isMultiContentFormat;\n\n // Determine which context format drives this block's selection.\n // content declaration blocks use selectedContentDeclarationFormat;\n // regular code blocks use selectedCodeFormat.\n const selectedFormat: CodeFormat = isMultiContentFormat\n ? (selectedContentDeclarationFormat as CodeFormat)\n : selectedCodeFormat;\n\n // The formats actually relevant for transformation (no 'json', no 'commonjs' for JSX).\n const effectiveFormats = useMemo<CodeFormat[] | undefined>(() => {\n const base = isMultiContentFormat ? contentFormats : codeFormats;\n if (!base) return base;\n let filtered = base.filter((f) => f !== 'json') as CodeFormat[];\n if (JSX_LANGUAGES.has(language as string)) {\n filtered = filtered.filter((f) => f !== 'commonjs');\n }\n return filtered;\n }, [isMultiContentFormat, contentFormats, codeFormats, language]);\n\n // When the globally-selected format isn't valid for this block\n // (e.g. CJS selected but this is a JSX file), fall back to the last valid one.\n const resolvedFormat: Exclude<CodeFormat, 'json'> = useMemo(() => {\n if (!effectiveFormats || effectiveFormats.includes(selectedFormat)) {\n return selectedFormat as Exclude<CodeFormat, 'json'>;\n }\n return (effectiveFormats[effectiveFormats.length - 1] ??\n 'typescript') as Exclude<CodeFormat, 'json'>;\n }, [effectiveFormats, selectedFormat]);\n\n // ── Async filename derivation (dynamic import of transformer) ──────────────\n // We derive the displayed fileName so the header updates when format changes.\n // deriveFileName is tiny but it lives inside codeTransformer, which is only\n // imported when actually needed (non-TypeScript selection).\n const [displayedFileName, setDisplayedFileName] = useState<\n string | undefined\n >(fileName);\n\n useEffect(() => {\n if (!isMultiFormat || resolvedFormat === 'typescript') {\n setDisplayedFileName(fileName);\n return;\n }\n if (!fileName) return;\n\n let cancelled = false;\n (async () => {\n const { deriveFileName } = await import('./codeTransformer');\n if (!cancelled)\n setDisplayedFileName(deriveFileName(fileName, resolvedFormat));\n })();\n return () => {\n cancelled = true;\n };\n }, [fileName, isMultiFormat, resolvedFormat]);\n\n // ── Async copy text (transformed code for CopyCode) ───────────────────────\n const rawCode = useMemo(() => {\n const code = Array.isArray(children) ? children.join('') : String(children);\n return code.endsWith('\\n') ? code.slice(0, -1) : code;\n }, [children]);\n\n const [copyCode, setCopyCode] = useState<string>(rawCode);\n\n useEffect(() => {\n if (!isMultiFormat || resolvedFormat === 'typescript') {\n setCopyCode(rawCode);\n return;\n }\n let cancelled = false;\n (async () => {\n const { transformCode } = await import('./codeTransformer');\n if (!cancelled) setCopyCode(transformCode(rawCode, resolvedFormat));\n })();\n return () => {\n cancelled = true;\n };\n }, [rawCode, isMultiFormat, resolvedFormat]);\n\n const hadSelectInHeader =\n packageManager || rawCodeFormat || rawContentDeclarationFormat;\n\n return (\n <CodeConditionalRender\n packageManager={packageManager}\n codeFormat={rawCodeFormat as string | undefined}\n contentDeclarationFormat={\n rawContentDeclarationFormat as string | undefined\n }\n >\n <Container\n className={cn(\n 'relative min-w-0 max-w-full text-sm leading-6',\n showLineNumbers && 'with-line-number ml-0',\n className\n )}\n transparency=\"lg\"\n {...props}\n >\n {showHeader && (\n <>\n <div className=\"grid w-full grid-cols-[1fr_auto] items-center justify-between rounded-t-xl bg-card/50 py-1.5 pr-12 pl-4 text-neutral text-xs\">\n <span className=\"truncate\">{displayedFileName ?? language}</span>\n <div className=\"flex items-center gap-2\">\n {packageManager && <PackageManagerSelector />}\n {rawCodeFormat && (\n <CodeFormatSelector availableFormats={effectiveFormats} />\n )}\n {rawContentDeclarationFormat && (\n <ContentDeclarationFormatSelector />\n )}\n </div>\n </div>\n <div className=\"sticky top-46 z-20\">\n <div\n className={cn(\n 'absolute right-2 bottom-0 flex h-7 items-center',\n hadSelectInHeader && 'h-11'\n )}\n >\n <CopyCode code={copyCode} />\n </div>\n </div>\n </>\n )}\n <ExpandCollapse\n minHeight={MIN_HEIGHT}\n isRollable={isRollable}\n className=\"min-w-0 max-w-full overflow-x-auto p-2\"\n >\n {isMultiFormat ? (\n /*\n * Multi-format: CodeBlockHighlight manages both the transformation\n * (dynamic import of codeTransformer) and the Shiki highlighting in\n * a single useEffect. The previous highlighted output stays visible\n * while the new one loads — no white-text flash.\n */\n <CodeBlockHighlight\n originalLang={language}\n targetFormat={resolvedFormat}\n isDarkMode={isDarkMode}\n >\n {rawCode}\n </CodeBlockHighlight>\n ) : (\n /*\n * Single-format: use the original Suspense-based async Shiki renderer\n * (good for SSR / static content).\n */\n <CodeBlock lang={language} isDarkMode={isDarkMode}>\n {rawCode}\n </CodeBlock>\n )}\n </ExpandCollapse>\n </Container>\n </CodeConditionalRender>\n );\n};\n"],"mappings":";;;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CACE,qBAAC,OAAD;IAAK,WAAU;cAAf,CACE,oBAAC,QAAD;KAAM,WAAU;eAAY,qBAAqB;IAAe,IAChE,qBAAC,OAAD;KAAK,WAAU;eAAf;MACG,kBAAkB,oBAAC,wBAAD,CAAyB;MAC3C,iBACC,oBAAC,oBAAD,EAAoB,kBAAkB,iBAAmB;MAE1D,+BACC,oBAAC,kCAAD,CAAmC;KAElC;MACF;OACL,oBAAC,OAAD;IAAK,WAAU;cACb,oBAAC,OAAD;KACE,WAAW,GACT,mDACA,qBAAqB,MACvB;eAEA,oBAAC,UAAD,EAAU,MAAM,SAAW;IACxB;GACF,EACL,MAEJ,oBAAC,gBAAD;IACE,WAAW;IACC;IACZ,WAAU;cAET,gBAOC,oBAAC,oBAAD;KACE,cAAc;KACd,cAAc;KACF;eAEX;IACiB,KAMpB,oBAAC,WAAD;KAAW,MAAM;KAAsB;eACpC;IACQ;GAEC,EACP;;CACU;AAE3B"}
1
+ {"version":3,"file":"Code.mjs","names":[],"sources":["../../../../src/components/IDE/Code.tsx"],"sourcesContent":["'use client';\n\nimport { cn } from '@utils/cn';\nimport type { FC, HTMLAttributes, ReactNode } from 'react';\nimport { useEffect, useMemo, useState } from 'react';\nimport type { BundledLanguage } from 'shiki/bundle/web';\nimport { Container } from '../Container';\nimport { ExpandCollapse } from '../ExpandCollapse';\nimport { CodeBlock } from './CodeBlockClient';\nimport { CodeBlockHighlight } from './CodeBlockHighlight';\nimport { CodeConditionalRender } from './CodeConditionalRenderer';\nimport type {\n CodeFormat,\n ContentDeclarationFormat,\n PackageManager,\n} from './CodeContext';\nimport { useCodeContext } from './CodeContext';\nimport { CodeFormatSelector } from './CodeFormatSelector';\nimport { ContentDeclarationFormatSelector } from './ContentDeclarationFormatSelector';\nimport { CopyCode } from './CopyCode';\nimport { PackageManagerSelector } from './PackageManagerSelector';\n\nexport type CodeCompAttributes = {\n fileName?: string;\n packageManager?: PackageManager;\n /** Single format, a JSON-array string, or an array of formats. */\n codeFormat?: CodeFormat | string | string[];\n contentDeclarationFormat?: ContentDeclarationFormat | string | string[];\n};\n\ntype CodeCompProps = {\n children: ReactNode;\n fileName?: string;\n language: BundledLanguage;\n isDarkMode?: boolean;\n showHeader?: boolean;\n showLineNumbers?: boolean;\n isRollable?: boolean;\n} & CodeCompAttributes &\n HTMLAttributes<HTMLDivElement>;\n\nconst MIN_HEIGHT = 700;\n\n/** Languages that use JSX syntax — CommonJS doesn't make sense for these. */\nconst JSX_LANGUAGES = new Set(['tsx', 'jsx']);\n\n/** Parse a codeFormat prop that may be a single value, a JSON-array string, or already an array. */\nconst parseFormats = (\n raw: string | string[] | undefined\n): CodeFormat[] | undefined => {\n if (!raw) return undefined;\n if (Array.isArray(raw)) return raw as CodeFormat[];\n if (typeof raw === 'string' && raw.startsWith('[')) {\n try {\n const parsed = JSON.parse(raw);\n if (Array.isArray(parsed)) return parsed as CodeFormat[];\n } catch {\n /* ignore */\n }\n }\n return [raw as CodeFormat];\n};\n\nexport const Code: FC<CodeCompProps> = ({\n children,\n language,\n isDarkMode,\n showHeader = true,\n showLineNumbers = true,\n className,\n fileName,\n packageManager,\n codeFormat: rawCodeFormat,\n contentDeclarationFormat: rawContentDeclarationFormat,\n isRollable = true,\n lang, // Destructure html lang prop to prevent passing invalid BCP-47 language tag to Code component\n ...props\n}) => {\n const {\n codeFormat: selectedCodeFormat,\n contentDeclarationFormat: selectedContentDeclarationFormat,\n } = useCodeContext();\n\n // Parse whichever attribute is present as an array of formats.\n const codeFormats = useMemo(\n () => parseFormats(rawCodeFormat as string | undefined),\n [rawCodeFormat]\n );\n const contentFormats = useMemo(\n () => parseFormats(rawContentDeclarationFormat as string | undefined),\n [rawContentDeclarationFormat]\n );\n\n // A block is \"multi-format\" when it has multiple formats including TypeScript\n // (the canonical source). Such blocks transform at runtime.\n const isMultiCodeFormat =\n codeFormats !== undefined &&\n codeFormats.length > 1 &&\n codeFormats.includes('typescript');\n\n const isMultiContentFormat =\n contentFormats !== undefined &&\n contentFormats.length > 1 &&\n contentFormats.includes('typescript');\n\n const isMultiFormat = isMultiCodeFormat || isMultiContentFormat;\n\n // Determine which context format drives this block's selection.\n // content declaration blocks use selectedContentDeclarationFormat;\n // regular code blocks use selectedCodeFormat.\n const selectedFormat: CodeFormat = isMultiContentFormat\n ? (selectedContentDeclarationFormat as CodeFormat)\n : selectedCodeFormat;\n\n // The formats actually relevant for transformation (no 'json', no 'commonjs' for JSX).\n const effectiveFormats = useMemo<CodeFormat[] | undefined>(() => {\n const base = isMultiContentFormat ? contentFormats : codeFormats;\n if (!base) return base;\n let filtered = base.filter((f) => f !== 'json') as CodeFormat[];\n if (JSX_LANGUAGES.has(language as string)) {\n filtered = filtered.filter((f) => f !== 'commonjs');\n }\n return filtered;\n }, [isMultiContentFormat, contentFormats, codeFormats, language]);\n\n // When the globally-selected format isn't valid for this block\n // (e.g. CJS selected but this is a JSX file), fall back to the last valid one.\n const resolvedFormat: Exclude<CodeFormat, 'json'> = useMemo(() => {\n if (!effectiveFormats || effectiveFormats.includes(selectedFormat)) {\n return selectedFormat as Exclude<CodeFormat, 'json'>;\n }\n return (effectiveFormats[effectiveFormats.length - 1] ??\n 'typescript') as Exclude<CodeFormat, 'json'>;\n }, [effectiveFormats, selectedFormat]);\n\n // ── Async filename derivation (dynamic import of transformer) ──────────────\n // We derive the displayed fileName so the header updates when format changes.\n // deriveFileName is tiny but it lives inside codeTransformer, which is only\n // imported when actually needed (non-TypeScript selection).\n const [displayedFileName, setDisplayedFileName] = useState<\n string | undefined\n >(fileName);\n\n useEffect(() => {\n if (!isMultiFormat || resolvedFormat === 'typescript') {\n setDisplayedFileName(fileName);\n return;\n }\n if (!fileName) return;\n\n let cancelled = false;\n (async () => {\n const { deriveFileName } = await import('./codeTransformer');\n if (!cancelled)\n setDisplayedFileName(deriveFileName(fileName, resolvedFormat));\n })();\n return () => {\n cancelled = true;\n };\n }, [fileName, isMultiFormat, resolvedFormat]);\n\n // ── Async copy text (transformed code for CopyCode) ───────────────────────\n const rawCode = useMemo(() => {\n const code = Array.isArray(children) ? children.join('') : String(children);\n return code.endsWith('\\n') ? code.slice(0, -1) : code;\n }, [children]);\n\n const [copyCode, setCopyCode] = useState<string>(rawCode);\n\n useEffect(() => {\n if (!isMultiFormat || resolvedFormat === 'typescript') {\n setCopyCode(rawCode);\n return;\n }\n let cancelled = false;\n (async () => {\n const { transformCode } = await import('./codeTransformer');\n if (!cancelled) setCopyCode(transformCode(rawCode, resolvedFormat));\n })();\n return () => {\n cancelled = true;\n };\n }, [rawCode, isMultiFormat, resolvedFormat]);\n\n const hadSelectInHeader =\n packageManager || rawCodeFormat || rawContentDeclarationFormat;\n\n return (\n <CodeConditionalRender\n packageManager={packageManager}\n codeFormat={rawCodeFormat as string | undefined}\n contentDeclarationFormat={\n rawContentDeclarationFormat as string | undefined\n }\n >\n <Container\n className={cn(\n 'relative min-w-0 max-w-full text-sm leading-6',\n showLineNumbers && 'with-line-number ml-0',\n className\n )}\n transparency=\"lg\"\n {...props}\n >\n {showHeader && (\n <>\n <div className=\"grid w-full grid-cols-[1fr_auto] items-center justify-between rounded-t-xl bg-card/50 py-1.5 pr-12 pl-4 text-neutral text-xs\">\n <span className=\"truncate\">{displayedFileName ?? language}</span>\n <div className=\"flex items-center gap-2\">\n {packageManager && <PackageManagerSelector />}\n {rawCodeFormat && (\n <CodeFormatSelector availableFormats={effectiveFormats} />\n )}\n {rawContentDeclarationFormat && (\n <ContentDeclarationFormatSelector />\n )}\n </div>\n </div>\n <div className=\"sticky top-46 z-20\">\n <div\n className={cn(\n 'absolute right-2 bottom-0 flex h-7 items-center',\n hadSelectInHeader && 'h-11'\n )}\n >\n <CopyCode code={copyCode} />\n </div>\n </div>\n </>\n )}\n <ExpandCollapse\n minHeight={MIN_HEIGHT}\n isRollable={isRollable}\n className=\"min-w-0 max-w-full overflow-x-auto p-2\"\n >\n {isMultiFormat ? (\n /*\n * Multi-format: CodeBlockHighlight manages both the transformation\n * (dynamic import of codeTransformer) and the Shiki highlighting in\n * a single useEffect. The previous highlighted output stays visible\n * while the new one loads — no white-text flash.\n */\n <CodeBlockHighlight\n originalLang={language}\n targetFormat={resolvedFormat}\n isDarkMode={isDarkMode}\n >\n {rawCode}\n </CodeBlockHighlight>\n ) : (\n /*\n * Single-format: use the original Suspense-based async Shiki renderer\n * (good for SSR / static content).\n */\n <CodeBlock lang={language} isDarkMode={isDarkMode}>\n {rawCode}\n </CodeBlock>\n )}\n </ExpandCollapse>\n </Container>\n </CodeConditionalRender>\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;AAyCA,MAAM,aAAa;;AAGnB,MAAM,gBAAgB,IAAI,IAAI,CAAC,OAAO,KAAK,CAAC;;AAG5C,MAAM,gBACJ,QAC6B;CAC7B,IAAI,CAAC,KAAK,OAAO;CACjB,IAAI,MAAM,QAAQ,GAAG,GAAG,OAAO;CAC/B,IAAI,OAAO,QAAQ,YAAY,IAAI,WAAW,GAAG,GAC/C,IAAI;EACF,MAAM,SAAS,KAAK,MAAM,GAAG;EAC7B,IAAI,MAAM,QAAQ,MAAM,GAAG,OAAO;CACpC,QAAQ,CAER;CAEF,OAAO,CAAC,GAAiB;AAC3B;AAEA,MAAa,QAA2B,EACtC,UACA,UACA,YACA,aAAa,MACb,kBAAkB,MAClB,WACA,UACA,gBACA,YAAY,eACZ,0BAA0B,6BAC1B,aAAa,MACb,MACA,GAAG,YACC;CACJ,MAAM,EACJ,YAAY,oBACZ,0BAA0B,qCACxB,eAAe;CAGnB,MAAM,cAAc,cACZ,aAAa,aAAmC,GACtD,CAAC,aAAa,CAChB;CACA,MAAM,iBAAiB,cACf,aAAa,2BAAiD,GACpE,CAAC,2BAA2B,CAC9B;CAIA,MAAM,oBACJ,gBAAgB,UAChB,YAAY,SAAS,KACrB,YAAY,SAAS,YAAY;CAEnC,MAAM,uBACJ,mBAAmB,UACnB,eAAe,SAAS,KACxB,eAAe,SAAS,YAAY;CAEtC,MAAM,gBAAgB,qBAAqB;CAK3C,MAAM,iBAA6B,uBAC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AO;GACvC,IAAI,CAAC,WAAW,YAAY,cAAc,SAAS,cAAc,CAAC;EACpE,GAAG;EACH,aAAa;GACX,YAAY;EACd;CACF,GAAG;EAAC;EAAS;EAAe;CAAc,CAAC;CAE3C,MAAM,oBACJ,kBAAkB,iBAAiB;CAErC,OACE,oBAAC,uBAAD;EACkB;EAChB,YAAY;EACZ,0BACE;YAGF,qBAAC,WAAD;GACE,WAAW,GACT,iDACA,mBAAmB,yBACnB,SACF;GACA,cAAa;GACb,GAAI;aAPN,CASG,cACC,8CACE,qBAAC,OAAD;IAAK,WAAU;cAAf,CACE,oBAAC,QAAD;KAAM,WAAU;eAAY,qBAAqB;IAAe,IAChE,qBAAC,OAAD;KAAK,WAAU;eAAf;MACG,kBAAkB,oBAAC,wBAAD,CAAyB;MAC3C,iBACC,oBAAC,oBAAD,EAAoB,kBAAkB,iBAAmB;MAE1D,+BACC,oBAAC,kCAAD,CAAmC;KAElC;MACF;OACL,oBAAC,OAAD;IAAK,WAAU;cACb,oBAAC,OAAD;KACE,WAAW,GACT,mDACA,qBAAqB,MACvB;eAEA,oBAAC,UAAD,EAAU,MAAM,SAAW;IACxB;GACF,EACL,MAEJ,oBAAC,gBAAD;IACE,WAAW;IACC;IACZ,WAAU;cAET,gBAOC,oBAAC,oBAAD;KACE,cAAc;KACd,cAAc;KACF;eAEX;IACiB,KAMpB,oBAAC,WAAD;KAAW,MAAM;KAAsB;eACpC;IACQ;GAEC,EACP;;CACU;AAE3B"}
@@ -50,7 +50,7 @@ const MarkDownIframe = (props) => {
50
50
  className: cn("block max-h-[80vh] min-h-[12rem] w-full border-0", className)
51
51
  }),
52
52
  /* @__PURE__ */ jsxs("div", {
53
- className: "flex items-center justify-between gap-3 border-neutral/30 border-t bg-card/40 px-3 py-1",
53
+ className: "flex items-center justify-between gap-3 px-3 py-1",
54
54
  children: [href ? /* @__PURE__ */ jsx(Link, {
55
55
  href,
56
56
  target: "_blank",
@@ -1 +1 @@
1
- {"version":3,"file":"MarkDownIframe.mjs","names":[],"sources":["../../../../src/components/MarkDownRender/MarkDownIframe.tsx"],"sourcesContent":["'use client';\n\nimport { Button, ButtonSize, ButtonVariant } from '@components/Button';\nimport { Container } from '@components/Container';\nimport { Link } from '@components/Link';\nimport { Modal, ModalSize } from '@components/Modal';\nimport { cn } from '@utils/cn';\nimport { MoveDiagonal } from 'lucide-react';\nimport { type ComponentProps, type FC, useState } from 'react';\n\nfunction embedLinkMeta(src: string | undefined): {\n href: string;\n label: string;\n} {\n if (!src) return { href: '', label: '' };\n if (/^https?:\\/\\//i.test(src)) {\n try {\n const url = new URL(src);\n return { href: url.href, label: url.host };\n } catch {\n return { href: src, label: src };\n }\n }\n return { href: src, label: src };\n}\n\nexport const MarkDownIframe: FC<ComponentProps<'iframe'>> = (props) => {\n const { src, className, title, ...rest } = props;\n const [isModalOpen, setIsModalOpen] = useState(false);\n const { href, label } = embedLinkMeta(src);\n\n return (\n <Container\n roundedSize=\"2xl\"\n border\n borderColor=\"neutral\"\n className=\"overflow-hidden p-0\"\n gap=\"none\"\n >\n <iframe\n {...rest}\n src={src}\n title={title}\n className={cn(\n 'block max-h-[80vh] min-h-[12rem] w-full border-0',\n className\n )}\n />\n <div className=\"flex items-center justify-between gap-3 border-neutral/30 border-t bg-card/40 px-3 py-1\">\n {href ? (\n <Link\n href={href}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n label=\"\"\n color=\"neutral\"\n className=\"inline-flex min-w-0 max-w-[calc(100%-3rem)] items-center gap-2 text-neutral text-xs underline-offset-2 hover:text-text hover:underline\"\n >\n {label}\n </Link>\n ) : (\n <span className=\"text-neutral text-sm\">Embedded frame</span>\n )}\n <Button\n variant={ButtonVariant.HOVERABLE}\n size={ButtonSize.ICON_MD}\n onClick={() => setIsModalOpen(true)}\n label=\"Open embedded page in fullscreen\"\n Icon={MoveDiagonal}\n />\n </div>\n\n <Modal\n isOpen={isModalOpen}\n onClose={() => setIsModalOpen(false)}\n size={ModalSize.UNSET}\n hasCloseButton\n isScrollable\n padding=\"sm\"\n >\n {isModalOpen && src ? (\n <Container\n roundedSize=\"2xl\"\n border\n borderColor=\"neutral\"\n className=\"overflow-hidden p-0\"\n gap=\"none\"\n >\n <iframe\n {...rest}\n src={src}\n title={title ?? 'Embedded content'}\n allowFullScreen\n className=\"block min-h-[82vh] w-full border-0\"\n />\n </Container>\n ) : null}\n </Modal>\n </Container>\n );\n};\n"],"mappings":";;;;;;;;;;;;AAUA,SAAS,cAAc,KAGrB;CACA,IAAI,CAAC,KAAK,OAAO;EAAE,MAAM;EAAI,OAAO;CAAG;CACvC,IAAI,gBAAgB,KAAK,GAAG,GAC1B,IAAI;EACF,MAAM,MAAM,IAAI,IAAI,GAAG;EACvB,OAAO;GAAE,MAAM,IAAI;GAAM,OAAO,IAAI;EAAK;CAC3C,QAAQ;EACN,OAAO;GAAE,MAAM;GAAK,OAAO;EAAI;CACjC;CAEF,OAAO;EAAE,MAAM;EAAK,OAAO;CAAI;AACjC;AAEA,MAAa,kBAAgD,UAAU;CACrE,MAAM,EAAE,KAAK,WAAW,OAAO,GAAG,SAAS;CAC3C,MAAM,CAAC,aAAa,kBAAkB,SAAS,KAAK;CACpD,MAAM,EAAE,MAAM,UAAU,cAAc,GAAG;CAEzC,OACE,qBAAC,WAAD;EACE,aAAY;EACZ;EACA,aAAY;EACZ,WAAU;EACV,KAAI;YALN;GAOE,oBAAC,UAAD;IACE,GAAI;IACC;IACE;IACP,WAAW,GACT,oDACA,SACF;GACD;GACD,qBAAC,OAAD;IAAK,WAAU;cAAf,CACG,OACC,oBAAC,MAAD;KACQ;KACN,QAAO;KACP,KAAI;KACJ,OAAM;KACN,OAAM;KACN,WAAU;eAET;IACG,KAEN,oBAAC,QAAD;KAAM,WAAU;eAAuB;IAAoB,IAE7D,oBAAC,QAAD;KACE;KACA;KACA,eAAe,eAAe,IAAI;KAClC,OAAM;KACN,MAAM;IACP,EACE;;GAEL,oBAAC,OAAD;IACE,QAAQ;IACR,eAAe,eAAe,KAAK;IACnC;IACA;IACA;IACA,SAAQ;cAEP,eAAe,MACd,oBAAC,WAAD;KACE,aAAY;KACZ;KACA,aAAY;KACZ,WAAU;KACV,KAAI;eAEJ,oBAAC,UAAD;MACE,GAAI;MACC;MACL,OAAO,SAAS;MAChB;MACA,WAAU;KACX;IACQ,KACT;GACC;EACE;;AAEf"}
1
+ {"version":3,"file":"MarkDownIframe.mjs","names":[],"sources":["../../../../src/components/MarkDownRender/MarkDownIframe.tsx"],"sourcesContent":["'use client';\n\nimport { Button, ButtonSize, ButtonVariant } from '@components/Button';\nimport { Container } from '@components/Container';\nimport { Link } from '@components/Link';\nimport { Modal, ModalSize } from '@components/Modal';\nimport { cn } from '@utils/cn';\nimport { MoveDiagonal } from 'lucide-react';\nimport { type ComponentProps, type FC, useState } from 'react';\n\nfunction embedLinkMeta(src: string | undefined): {\n href: string;\n label: string;\n} {\n if (!src) return { href: '', label: '' };\n if (/^https?:\\/\\//i.test(src)) {\n try {\n const url = new URL(src);\n return { href: url.href, label: url.host };\n } catch {\n return { href: src, label: src };\n }\n }\n return { href: src, label: src };\n}\n\nexport const MarkDownIframe: FC<ComponentProps<'iframe'>> = (props) => {\n const { src, className, title, ...rest } = props;\n const [isModalOpen, setIsModalOpen] = useState(false);\n const { href, label } = embedLinkMeta(src);\n\n return (\n <Container\n roundedSize=\"2xl\"\n border\n borderColor=\"neutral\"\n className=\"overflow-hidden p-0\"\n gap=\"none\"\n >\n <iframe\n {...rest}\n src={src}\n title={title}\n className={cn(\n 'block max-h-[80vh] min-h-[12rem] w-full border-0',\n className\n )}\n />\n <div className=\"flex items-center justify-between gap-3 px-3 py-1\">\n {href ? (\n <Link\n href={href}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n label=\"\"\n color=\"neutral\"\n className=\"inline-flex min-w-0 max-w-[calc(100%-3rem)] items-center gap-2 text-neutral text-xs underline-offset-2 hover:text-text hover:underline\"\n >\n {label}\n </Link>\n ) : (\n <span className=\"text-neutral text-sm\">Embedded frame</span>\n )}\n <Button\n variant={ButtonVariant.HOVERABLE}\n size={ButtonSize.ICON_MD}\n onClick={() => setIsModalOpen(true)}\n label=\"Open embedded page in fullscreen\"\n Icon={MoveDiagonal}\n />\n </div>\n\n <Modal\n isOpen={isModalOpen}\n onClose={() => setIsModalOpen(false)}\n size={ModalSize.UNSET}\n hasCloseButton\n isScrollable\n padding=\"sm\"\n >\n {isModalOpen && src ? (\n <Container\n roundedSize=\"2xl\"\n border\n borderColor=\"neutral\"\n className=\"overflow-hidden p-0\"\n gap=\"none\"\n >\n <iframe\n {...rest}\n src={src}\n title={title ?? 'Embedded content'}\n allowFullScreen\n className=\"block min-h-[82vh] w-full border-0\"\n />\n </Container>\n ) : null}\n </Modal>\n </Container>\n );\n};\n"],"mappings":";;;;;;;;;;;;AAUA,SAAS,cAAc,KAGrB;CACA,IAAI,CAAC,KAAK,OAAO;EAAE,MAAM;EAAI,OAAO;CAAG;CACvC,IAAI,gBAAgB,KAAK,GAAG,GAC1B,IAAI;EACF,MAAM,MAAM,IAAI,IAAI,GAAG;EACvB,OAAO;GAAE,MAAM,IAAI;GAAM,OAAO,IAAI;EAAK;CAC3C,QAAQ;EACN,OAAO;GAAE,MAAM;GAAK,OAAO;EAAI;CACjC;CAEF,OAAO;EAAE,MAAM;EAAK,OAAO;CAAI;AACjC;AAEA,MAAa,kBAAgD,UAAU;CACrE,MAAM,EAAE,KAAK,WAAW,OAAO,GAAG,SAAS;CAC3C,MAAM,CAAC,aAAa,kBAAkB,SAAS,KAAK;CACpD,MAAM,EAAE,MAAM,UAAU,cAAc,GAAG;CAEzC,OACE,qBAAC,WAAD;EACE,aAAY;EACZ;EACA,aAAY;EACZ,WAAU;EACV,KAAI;YALN;GAOE,oBAAC,UAAD;IACE,GAAI;IACC;IACE;IACP,WAAW,GACT,oDACA,SACF;GACD;GACD,qBAAC,OAAD;IAAK,WAAU;cAAf,CACG,OACC,oBAAC,MAAD;KACQ;KACN,QAAO;KACP,KAAI;KACJ,OAAM;KACN,OAAM;KACN,WAAU;eAET;IACG,KAEN,oBAAC,QAAD;KAAM,WAAU;eAAuB;IAAoB,IAE7D,oBAAC,QAAD;KACE;KACA;KACA,eAAe,eAAe,IAAI;KAClC,OAAM;KACN,MAAM;IACP,EACE;;GAEL,oBAAC,OAAD;IACE,QAAQ;IACR,eAAe,eAAe,KAAK;IACnC;IACA;IACA;IACA,SAAQ;cAEP,eAAe,MACd,oBAAC,WAAD;KACE,aAAY;KACZ;KACA,aAAY;KACZ,WAAU;KACV,KAAI;eAEJ,oBAAC,UAAD;MACE,GAAI;MACC;MACL,OAAO,SAAS;MAChB;MACA,WAAU;KACX;IACQ,KACT;GACC;EACE;;AAEf"}
@@ -47,7 +47,7 @@ const StrongRenderer = (props) => /* @__PURE__ */ jsx("strong", {
47
47
  className: "text-text",
48
48
  ...props
49
49
  });
50
- const MemoizedCodeBlock = memo(({ className, children, isDarkMode, ...rest }) => {
50
+ const MemoizedCodeBlock = memo(({ className, children, isDarkMode, lang, ...rest }) => {
51
51
  const content = String(children ?? "").replace(/\n$/, "");
52
52
  if (!!!className) return /* @__PURE__ */ jsx("code", {
53
53
  className: "rounded-md border border-neutral/30 bg-card/60 box-decoration-clone px-1.5 py-0.5 font-mono text-sm",
@@ -1 +1 @@
1
- {"version":3,"file":"MarkDownRender.mjs","names":[],"sources":["../../../../src/components/MarkDownRender/MarkDownRender.tsx"],"sourcesContent":["import type { LocalesValues } from '@intlayer/types/module_augmentation';\nimport { cn } from '@utils/cn';\nimport type { ComponentProps, ComponentPropsWithoutRef, FC } from 'react';\nimport { memo } from 'react';\nimport {\n type MarkdownRenderer as MarkdownRendererIntlayer,\n renderMarkdown,\n} from 'react-intlayer/markdown';\nimport type { BundledLanguage } from 'shiki/bundle/web';\nimport { H1, H2, H3, H4, H5, H6 } from '../Headers';\nimport { Code } from '../IDE/Code';\nimport { CodeProvider } from '../IDE/CodeContext';\nimport { Link } from '../Link';\nimport { Tab } from '../Tab';\nimport { TabProvider } from '../Tab/TabContext';\nimport { Hr, SmartTable, Td, Th, Tr } from '../Table';\nimport { MarkDownIframe } from './MarkDownIframe';\n\n// Extracted, stable component renderers\nconst H1Renderer = (props: ComponentProps<'h1'>) => (\n <H1 isClickable className=\"text-text\" {...props} />\n);\nconst H2Renderer = (props: ComponentProps<'h2'>) => (\n <H2 isClickable className=\"mt-16 text-text\" {...props} />\n);\nconst H3Renderer = (props: ComponentProps<'h3'>) => (\n <H3 isClickable className=\"mt-5 text-text\" {...props} />\n);\nconst H4Renderer = (props: ComponentProps<'h4'>) => (\n <H4 isClickable className=\"mt-3 text-text\" {...props} />\n);\nconst H5Renderer = (props: ComponentProps<'h5'>) => (\n <H5 isClickable className=\"mt-3 text-text\" {...props} />\n);\nconst H6Renderer = (props: ComponentProps<'h6'>) => (\n <H6 isClickable className=\"mt-3 text-text\" {...props} />\n);\nconst StrongRenderer = (props: ComponentProps<'strong'>) => (\n <strong className=\"text-text\" {...props} />\n);\n\nconst MemoizedCodeBlock = memo(\n ({\n className,\n children,\n isDarkMode,\n ...rest\n }: ComponentProps<'code'> & { isDarkMode?: boolean }) => {\n const content = String(children ?? '').replace(/\\n$/, '');\n const isBlock = !!className;\n\n if (!isBlock) {\n const decodedContent = content.replace(\n /&(?:amp;)?#(\\d+);/g,\n (_, code: string) => String.fromCharCode(parseInt(code, 10))\n );\n return (\n <code className=\"rounded-md border border-neutral/30 bg-card/60 box-decoration-clone px-1.5 py-0.5 font-mono text-sm\">\n {decodedContent}\n </code>\n );\n }\n\n const language = (className?.replace(/lang(?:uage)?-/, '') ||\n 'plaintext') as BundledLanguage;\n\n return (\n <Code {...rest} language={language} showHeader isDarkMode={isDarkMode}>\n {content}\n </Code>\n );\n },\n (prevProps, nextProps) =>\n prevProps.children === nextProps.children &&\n prevProps.className === nextProps.className &&\n prevProps.isDarkMode === nextProps.isDarkMode\n);\n\nconst createCodeRenderer = (isDarkMode?: boolean) => {\n return function CodeWrapper(props: ComponentProps<'code'>) {\n return <MemoizedCodeBlock {...props} isDarkMode={isDarkMode} />;\n };\n};\n\nconst BlockquoteRenderer = ({\n className,\n ...props\n}: ComponentProps<'blockquote'>) => (\n <blockquote\n className={cn(\n 'mt-5 gap-3 border-card border-l-4 pl-5 text-neutral [&_strong]:text-neutral',\n className\n )}\n {...props}\n />\n);\n\nconst UlRenderer = ({ className, ...props }: ComponentProps<'ul'>) => (\n <ul\n className={cn(\n 'mt-5 flex list-disc flex-col gap-3 pl-5 marker:text-neutral/80',\n className\n )}\n {...props}\n />\n);\n\nconst OlRenderer = ({ className, ...props }: ComponentProps<'ol'>) => (\n <ol\n className={cn(\n 'mt-5 flex list-decimal flex-col gap-3 pl-5 marker:text-neutral/80',\n className\n )}\n {...props}\n />\n);\n\nconst ImgRenderer = ({\n className,\n alt,\n src,\n ...props\n}: ComponentProps<'img'>) => (\n <img\n {...props}\n alt={alt ?? ''}\n loading=\"lazy\"\n className={cn('max-h-[80vh] max-w-full rounded-md', className)}\n src={\n src?.includes('github.com')\n ? src\n ?.replace('github.com', 'raw.githubusercontent.com')\n .replace('/blob/', '/') // GitHub raw URLs do not use /blob/\n : src\n }\n />\n);\n\nconst createLinkRenderer = (locale?: LocalesValues) => {\n return (props: ComponentProps<'a'>) => (\n <Link\n isExternalLink={props.href?.startsWith('http')}\n underlined\n locale={locale}\n label=\"\"\n color=\"text\"\n {...(props as any)}\n />\n );\n};\n\nconst PreRenderer = (props: ComponentProps<'pre'>) => <>{props.children}</>;\nconst TableRenderer = (props: ComponentProps<typeof SmartTable>) => (\n <SmartTable isRollable displayModal {...props} />\n);\n\nconst TabsRenderer = (props: ComponentProps<typeof Tab>) => (\n <Tab\n {...props}\n className=\"rounded-xl border border-card\"\n headerClassName=\"sticky rounded-xl top-24 z-5 bg-background/70 backdrop-blur overflow-x-auto\"\n />\n);\nconst ColumnsRenderer = ({\n className,\n ...props\n}: ComponentPropsWithoutRef<'div'>) => (\n <div className={cn('flex gap-4 max-md:flex-col', className)} {...props} />\n);\nconst ColumnRenderer = ({\n className,\n ...props\n}: ComponentPropsWithoutRef<'div'>) => (\n <div className={cn('flex-1', className)} {...props} />\n);\n\nconst Iframe = (props: ComponentProps<'iframe'>) => (\n <MarkDownIframe {...props} />\n);\n\n// Static configuration object for static renderers\nconst staticMarkdownComponents = {\n h1: H1Renderer,\n h2: H2Renderer,\n h3: H3Renderer,\n h4: H4Renderer,\n h5: H5Renderer,\n h6: H6Renderer,\n strong: StrongRenderer,\n blockquote: BlockquoteRenderer,\n ul: UlRenderer,\n ol: OlRenderer,\n img: ImgRenderer,\n pre: PreRenderer,\n table: TableRenderer,\n th: Th,\n tr: Tr,\n td: Td,\n hr: Hr,\n Tabs: TabsRenderer,\n Tab: Tab.Item,\n Columns: ColumnsRenderer,\n Column: ColumnRenderer,\n iframe: Iframe,\n};\n\n// Factory function to create components with dynamic props\nconst createMarkdownComponents = (\n isDarkMode?: boolean,\n locale?: LocalesValues\n) => ({\n ...staticMarkdownComponents,\n code: createCodeRenderer(isDarkMode),\n a: createLinkRenderer(locale),\n});\n\n// Export static renderers for backward compatibility\nexport const baseMarkdownComponents = staticMarkdownComponents;\n\ntype MarkdownRendererProps = {\n children: string;\n isDarkMode?: boolean;\n locale?: LocalesValues;\n forceBlock?: boolean;\n preserveFrontmatter?: boolean;\n tagfilter?: boolean;\n components?: ComponentProps<typeof MarkdownRendererIntlayer>['components'];\n wrapper?: ComponentProps<typeof MarkdownRendererIntlayer>['wrapper'];\n};\n\nexport const getIntlayerMarkdownOptions = (_isDarkMode?: boolean) => ({\n components: baseMarkdownComponents,\n});\n\nexport const MarkdownRenderer: FC<MarkdownRendererProps> = ({\n children,\n isDarkMode = false,\n locale,\n forceBlock,\n preserveFrontmatter,\n tagfilter,\n components: componentsProp,\n wrapper,\n}) => {\n const markdownComponents = createMarkdownComponents(isDarkMode, locale);\n\n const markdownContent = renderMarkdown(children, {\n components: {\n ...markdownComponents,\n ...componentsProp,\n },\n wrapper,\n forceBlock,\n preserveFrontmatter,\n tagfilter,\n });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IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,QAAQ;CACR,YAAY;CACZ,IAAI;CACJ,IAAI;CACJ,KAAK;CACL,KAAK;CACL,OAAO;CACP,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,MAAM;CACN,KAAK,IAAI;CACT,SAAS;CACT,QAAQ;CACR,QAAQ;AACV;AAGA,MAAM,4BACJ,YACA,YACI;CACJ,GAAG;CACH,MAAM,mBAAmB,UAAU;CACnC,GAAG,mBAAmB,MAAM;AAC9B;AAGA,MAAa,yBAAyB;AAatC,MAAa,8BAA8B,iBAA2B,EACpE,YAAY,uBACd;AAEA,MAAa,oBAA+C,EAC1D,UACA,aAAa,OACb,QACA,YACA,qBACA,WACA,YAAY,gBACZ,cACI;CAcJ,OACE,oBAAC,cAAD,YACE,oBAAC,aAAD,YAboB,eAAe,UAAU;EAC/C,YAAY;GACV,GAJuB,yBAAyB,YAAY,MAIxC;GACpB,GAAG;EACL;EACA;EACA;EACA;EACA;CACF,CAIgC,EAAe,GAC/B;AAElB"}
1
+ {"version":3,"file":"MarkDownRender.mjs","names":[],"sources":["../../../../src/components/MarkDownRender/MarkDownRender.tsx"],"sourcesContent":["import type { LocalesValues } from '@intlayer/types/module_augmentation';\nimport { cn } from '@utils/cn';\nimport type { ComponentProps, ComponentPropsWithoutRef, FC } from 'react';\nimport { memo } from 'react';\nimport {\n type MarkdownRenderer as MarkdownRendererIntlayer,\n type ParsedMarkdown,\n renderMarkdown,\n} from 'react-intlayer/markdown';\n\nexport type { ParsedMarkdown };\n\nimport type { BundledLanguage } from 'shiki/bundle/web';\nimport { H1, H2, H3, H4, H5, H6 } from '../Headers';\nimport { Code } from '../IDE/Code';\nimport { CodeProvider } from '../IDE/CodeContext';\nimport { Link } from '../Link';\nimport { Tab } from '../Tab';\nimport { TabProvider } from '../Tab/TabContext';\nimport { Hr, SmartTable, Td, Th, Tr } from '../Table';\nimport { MarkDownIframe } from './MarkDownIframe';\n\n// Extracted, stable component renderers\nconst H1Renderer = (props: ComponentProps<'h1'>) => (\n <H1 isClickable className=\"text-text\" {...props} />\n);\nconst H2Renderer = (props: ComponentProps<'h2'>) => (\n <H2 isClickable className=\"mt-16 text-text\" {...props} />\n);\nconst H3Renderer = (props: ComponentProps<'h3'>) => (\n <H3 isClickable className=\"mt-5 text-text\" {...props} />\n);\nconst H4Renderer = (props: ComponentProps<'h4'>) => (\n <H4 isClickable className=\"mt-3 text-text\" {...props} />\n);\nconst H5Renderer = (props: ComponentProps<'h5'>) => (\n <H5 isClickable className=\"mt-3 text-text\" {...props} />\n);\nconst H6Renderer = (props: ComponentProps<'h6'>) => (\n <H6 isClickable className=\"mt-3 text-text\" {...props} />\n);\nconst StrongRenderer = (props: ComponentProps<'strong'>) => (\n <strong className=\"text-text\" {...props} />\n);\n\nconst MemoizedCodeBlock = memo(\n ({\n className,\n children,\n isDarkMode,\n lang, // Destructure html lang prop to prevent passing invalid BCP-47 language tag to Code component\n ...rest\n }: ComponentProps<'code'> & { isDarkMode?: boolean }) => {\n const content = String(children ?? '').replace(/\\n$/, '');\n const isBlock = !!className;\n\n if (!isBlock) {\n const decodedContent = content.replace(\n /&(?:amp;)?#(\\d+);/g,\n (_, code: string) => String.fromCharCode(parseInt(code, 10))\n );\n return (\n <code className=\"rounded-md border border-neutral/30 bg-card/60 box-decoration-clone px-1.5 py-0.5 font-mono text-sm\">\n {decodedContent}\n </code>\n );\n }\n\n const language = (className?.replace(/lang(?:uage)?-/, '') ||\n 'plaintext') as BundledLanguage;\n\n return (\n <Code {...rest} language={language} showHeader isDarkMode={isDarkMode}>\n {content}\n </Code>\n );\n },\n (prevProps, nextProps) =>\n prevProps.children === nextProps.children &&\n prevProps.className === nextProps.className &&\n prevProps.isDarkMode === nextProps.isDarkMode\n);\n\nconst createCodeRenderer = (isDarkMode?: boolean) => {\n return function CodeWrapper(props: ComponentProps<'code'>) {\n return <MemoizedCodeBlock {...props} isDarkMode={isDarkMode} />;\n };\n};\n\nconst BlockquoteRenderer = ({\n className,\n ...props\n}: ComponentProps<'blockquote'>) => (\n <blockquote\n className={cn(\n 'mt-5 gap-3 border-card border-l-4 pl-5 text-neutral [&_strong]:text-neutral',\n className\n )}\n {...props}\n />\n);\n\nconst UlRenderer = ({ className, ...props }: ComponentProps<'ul'>) => (\n <ul\n className={cn(\n 'mt-5 flex list-disc flex-col gap-3 pl-5 marker:text-neutral/80',\n className\n )}\n {...props}\n />\n);\n\nconst OlRenderer = ({ className, ...props }: ComponentProps<'ol'>) => (\n <ol\n className={cn(\n 'mt-5 flex list-decimal flex-col gap-3 pl-5 marker:text-neutral/80',\n className\n )}\n {...props}\n />\n);\n\nconst ImgRenderer = ({\n className,\n alt,\n src,\n ...props\n}: ComponentProps<'img'>) => (\n <img\n {...props}\n alt={alt ?? ''}\n loading=\"lazy\"\n className={cn('max-h-[80vh] max-w-full rounded-md', className)}\n src={\n src?.includes('github.com')\n ? src\n ?.replace('github.com', 'raw.githubusercontent.com')\n .replace('/blob/', '/') // GitHub raw URLs do not use /blob/\n : src\n }\n />\n);\n\nconst createLinkRenderer = (locale?: LocalesValues) => {\n return (props: ComponentProps<'a'>) => (\n <Link\n isExternalLink={props.href?.startsWith('http')}\n underlined\n locale={locale}\n label=\"\"\n color=\"text\"\n {...(props as any)}\n />\n );\n};\n\nconst PreRenderer = (props: ComponentProps<'pre'>) => <>{props.children}</>;\nconst TableRenderer = (props: ComponentProps<typeof SmartTable>) => (\n <SmartTable isRollable displayModal {...props} />\n);\n\nconst TabsRenderer = (props: ComponentProps<typeof Tab>) => (\n <Tab\n {...props}\n className=\"rounded-xl border border-card\"\n headerClassName=\"sticky rounded-xl top-24 z-5 bg-background/70 backdrop-blur overflow-x-auto\"\n />\n);\nconst ColumnsRenderer = ({\n className,\n ...props\n}: ComponentPropsWithoutRef<'div'>) => (\n <div className={cn('flex gap-4 max-md:flex-col', className)} {...props} />\n);\nconst ColumnRenderer = ({\n className,\n ...props\n}: ComponentPropsWithoutRef<'div'>) => (\n <div className={cn('flex-1', className)} {...props} />\n);\n\nconst Iframe = (props: ComponentProps<'iframe'>) => (\n <MarkDownIframe {...props} />\n);\n\n// Static configuration object for static renderers\nconst staticMarkdownComponents = {\n h1: H1Renderer,\n h2: H2Renderer,\n h3: H3Renderer,\n h4: H4Renderer,\n h5: H5Renderer,\n h6: H6Renderer,\n strong: StrongRenderer,\n blockquote: BlockquoteRenderer,\n ul: UlRenderer,\n ol: OlRenderer,\n img: ImgRenderer,\n pre: PreRenderer,\n table: TableRenderer,\n th: Th,\n tr: Tr,\n td: Td,\n hr: Hr,\n Tabs: TabsRenderer,\n Tab: Tab.Item,\n Columns: ColumnsRenderer,\n Column: ColumnRenderer,\n iframe: Iframe,\n};\n\n// Factory function to create components with dynamic props\nconst createMarkdownComponents = (\n isDarkMode?: boolean,\n locale?: LocalesValues\n) => ({\n ...staticMarkdownComponents,\n code: createCodeRenderer(isDarkMode),\n a: createLinkRenderer(locale),\n});\n\n// Export static renderers for backward compatibility\nexport const baseMarkdownComponents = staticMarkdownComponents;\n\ntype MarkdownRendererProps = {\n children: string | ParsedMarkdown;\n isDarkMode?: boolean;\n locale?: LocalesValues;\n forceBlock?: boolean;\n preserveFrontmatter?: boolean;\n tagfilter?: boolean;\n components?: ComponentProps<typeof MarkdownRendererIntlayer>['components'];\n wrapper?: ComponentProps<typeof MarkdownRendererIntlayer>['wrapper'];\n};\n\nexport const getIntlayerMarkdownOptions = (_isDarkMode?: boolean) => ({\n components: baseMarkdownComponents,\n});\n\nexport const MarkdownRenderer: FC<MarkdownRendererProps> = ({\n children,\n isDarkMode = false,\n locale,\n forceBlock,\n preserveFrontmatter,\n tagfilter,\n components: componentsProp,\n wrapper,\n}) => {\n const markdownComponents = createMarkdownComponents(isDarkMode, locale);\n\n const markdownContent = renderMarkdown(children, {\n components: {\n ...markdownComponents,\n ...componentsProp,\n },\n wrapper,\n forceBlock,\n preserveFrontmatter,\n tagfilter,\n });\n\n return (\n <CodeProvider>\n <TabProvider>{markdown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CACJ,QAAQ;CACR,YAAY;CACZ,IAAI;CACJ,IAAI;CACJ,KAAK;CACL,KAAK;CACL,OAAO;CACP,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,MAAM;CACN,KAAK,IAAI;CACT,SAAS;CACT,QAAQ;CACR,QAAQ;AACV;AAGA,MAAM,4BACJ,YACA,YACI;CACJ,GAAG;CACH,MAAM,mBAAmB,UAAU;CACnC,GAAG,mBAAmB,MAAM;AAC9B;AAGA,MAAa,yBAAyB;AAatC,MAAa,8BAA8B,iBAA2B,EACpE,YAAY,uBACd;AAEA,MAAa,oBAA+C,EAC1D,UACA,aAAa,OACb,QACA,YACA,qBACA,WACA,YAAY,gBACZ,cACI;CAcJ,OACE,oBAAC,cAAD,YACE,oBAAC,aAAD,YAboB,eAAe,UAAU;EAC/C,YAAY;GACV,GAJuB,yBAAyB,YAAY,MAIxC;GACpB,GAAG;EACL;EACA;EACA;EACA;EACA;CACF,CAIgC,EAAe,GAC/B;AAElB"}
@@ -76,8 +76,7 @@ const AutoSizedTextArea = ({ className, autoSize = true, onChange, maxRows = 999
76
76
  textAreaStyle.height = "auto";
77
77
  const scrollHeight = textAreaEl.scrollHeight;
78
78
  const maxHeight = LINE_HEIGHT * maxRows + LINE_PADDING;
79
- const minHeight = LINE_HEIGHT + LINE_PADDING;
80
- textAreaStyle.height = `${Math.max(Math.min(scrollHeight, maxHeight), minHeight)}px`;
79
+ textAreaStyle.height = `${Math.max(Math.min(scrollHeight, maxHeight), 36)}px`;
81
80
  };
82
81
  useLayoutEffect(() => {
83
82
  adjustHeight();
@@ -1 +1 @@
1
- {"version":3,"file":"AutoSizeTextArea.mjs","names":[],"sources":["../../../../src/components/TextArea/AutoSizeTextArea.tsx"],"sourcesContent":["'use client';\n\nimport { cn } from '@utils/cn';\nimport {\n type ChangeEventHandler,\n type FC,\n useImperativeHandle,\n useLayoutEffect,\n useRef,\n} from 'react';\nimport { TextArea, type TextAreaProps } from './TextArea';\n\n/**\n * Props for the AutoSizedTextArea component.\n *\n * Extends TextAreaProps with auto-sizing functionality and row limitations.\n *\n * @example\n * ```tsx\n * // Auto-sizing textarea that grows with content\n * <AutoSizedTextArea\n * placeholder=\"Start typing and watch it grow...\"\n * autoSize={true}\n * maxRows={10}\n * />\n *\n * // Limited height with scroll when exceeded\n * <AutoSizedTextArea\n * value={longText}\n * onChange={handleChange}\n * autoSize={true}\n * maxRows={5}\n * className=\"max-h-[120px]\"\n * />\n *\n * // Disable auto-sizing for fixed height\n * <AutoSizedTextArea\n * autoSize={false}\n * rows={3}\n * placeholder=\"Fixed height textarea\"\n * />\n * ```\n */\nexport type AutoSizedTextAreaProps = TextAreaProps & {\n /** Whether to automatically adjust height based on content */\n autoSize?: boolean;\n /** Maximum number of rows before scrolling is enabled */\n maxRows?: number;\n};\n\nconst LINE_HEIGHT = 24; // px\nconst LINE_PADDING = 12; // px\n\n/**\n * AutoSizedTextArea Component\n *\n * An enhanced textarea that automatically adjusts its height based on content,\n * providing a smooth user experience for variable-length text input.\n *\n * ## Features\n * - **Auto-Sizing**: Dynamically grows and shrinks based on content\n * - **Row Limits**: Configurable maximum rows before scrolling\n * - **Smooth Transitions**: Seamless height adjustments as user types\n * - **Scroll Management**: Automatic overflow handling when max height reached\n * - **Performance Optimized**: Efficient height calculations and updates\n *\n * ## Technical Details\n * - Line height: 24px with 12px padding\n * - Height calculation: `scrollHeight` vs `maxRows * lineHeight + padding`\n * - Resize: Disabled when auto-sizing is active for smooth experience\n * - Ref forwarding: Supports imperative access to textarea element\n *\n * ## Use Cases\n * - Chat message composition with dynamic sizing\n * - Comment forms that expand with content\n * - Note-taking interfaces with variable length\n * - Social media post creation\n * - Code snippet input with growth limits\n *\n * @example\n * ```tsx\n * // Chat-style auto-expanding textarea\n * const [message, setMessage] = useState('');\n *\n * <AutoSizedTextArea\n * value={message}\n * onChange={(e) => setMessage(e.target.value)}\n * placeholder=\"Type your message...\"\n * autoSize={true}\n * maxRows={8}\n * className=\"min-h-[40px]\"\n * onKeyDown={(e) => {\n * if (e.key === 'Enter' && !e.shiftKey) {\n * e.preventDefault();\n * sendMessage(message);\n * setMessage('');\n * }\n * }}\n * />\n *\n * // Note-taking with generous height limits\n * <AutoSizedTextArea\n * defaultValue={note.content}\n * onChange={handleNoteChange}\n * placeholder=\"Write your notes here...\"\n * autoSize={true}\n * maxRows={20}\n * variant={InputVariant.DEFAULT}\n * />\n * ```\n */\nexport const AutoSizedTextArea: FC<AutoSizedTextAreaProps> = ({\n className,\n autoSize = true,\n onChange,\n maxRows = 999,\n ref,\n ...props\n}) => {\n const textAreaRef = useRef<HTMLTextAreaElement | null>(null);\n\n useImperativeHandle(ref, () => textAreaRef.current!);\n\n const adjustHeight = () => {\n const textAreaEl = textAreaRef.current;\n\n if (!textAreaEl || !autoSize) return;\n\n const textAreaStyle = textAreaEl.style;\n\n // Reset height to get accurate scrollHeight\n textAreaStyle.height = 'auto';\n const scrollHeight = textAreaEl.scrollHeight;\n const maxHeight = LINE_HEIGHT * maxRows + LINE_PADDING;\n const minHeight = LINE_HEIGHT + LINE_PADDING;\n\n // Set the new height\n textAreaStyle.height = `${Math.max(Math.min(scrollHeight, maxHeight), minHeight)}px`;\n };\n\n useLayoutEffect(() => {\n adjustHeight();\n }, [props.value, props.defaultValue, adjustHeight]);\n\n const handleChange: ChangeEventHandler<HTMLTextAreaElement> = (e) => {\n onChange?.(e);\n adjustHeight();\n };\n\n const setRef = (el: HTMLTextAreaElement | null) => {\n textAreaRef.current = el;\n if (el) {\n adjustHeight();\n }\n };\n\n return (\n <TextArea\n ref={setRef}\n onChange={handleChange}\n className={cn('overflow-y-auto', autoSize && 'resize-none', className)}\n {...props}\n />\n );\n};\n"],"mappings":";;;;;;;;AAkDA,MAAM,cAAc;AACpB,MAAM,eAAe;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4DrB,MAAa,qBAAiD,EAC5D,WACA,WAAW,MACX,UACA,UAAU,KACV,KACA,GAAG,YACC;CACJ,MAAM,cAAc,OAAmC,IAAI;CAE3D,oBAAoB,WAAW,YAAY,OAAQ;CAEnD,MAAM,qBAAqB;EACzB,MAAM,aAAa,YAAY;EAE/B,IAAI,CAAC,cAAc,CAAC,UAAU;EAE9B,MAAM,gBAAgB,WAAW;EAGjC,cAAc,SAAS;EACvB,MAAM,eAAe,WAAW;EAChC,MAAM,YAAY,cAAc,UAAU;EAC1C,MAAM,YAAY,cAAc;EAGhC,cAAc,SAAS,GAAG,KAAK,IAAI,KAAK,IAAI,cAAc,SAAS,GAAG,SAAS,EAAE;CACnF;CAEA,sBAAsB;EACpB,aAAa;CACf,GAAG;EAAC,MAAM;EAAO,MAAM;EAAc;CAAY,CAAC;CAElD,MAAM,gBAAyD,MAAM;EACnE,WAAW,CAAC;EACZ,aAAa;CACf;CAEA,MAAM,UAAU,OAAmC;EACjD,YAAY,UAAU;EACtB,IAAI,IACF,aAAa;CAEjB;CAEA,OACE,oBAAC,UAAD;EACE,KAAK;EACL,UAAU;EACV,WAAW,GAAG,mBAAmB,YAAY,eAAe,SAAS;EACrE,GAAI;CACL;AAEL"}
1
+ {"version":3,"file":"AutoSizeTextArea.mjs","names":[],"sources":["../../../../src/components/TextArea/AutoSizeTextArea.tsx"],"sourcesContent":["'use client';\n\nimport { cn } from '@utils/cn';\nimport {\n type ChangeEventHandler,\n type FC,\n useImperativeHandle,\n useLayoutEffect,\n useRef,\n} from 'react';\nimport { TextArea, type TextAreaProps } from './TextArea';\n\n/**\n * Props for the AutoSizedTextArea component.\n *\n * Extends TextAreaProps with auto-sizing functionality and row limitations.\n *\n * @example\n * ```tsx\n * // Auto-sizing textarea that grows with content\n * <AutoSizedTextArea\n * placeholder=\"Start typing and watch it grow...\"\n * autoSize={true}\n * maxRows={10}\n * />\n *\n * // Limited height with scroll when exceeded\n * <AutoSizedTextArea\n * value={longText}\n * onChange={handleChange}\n * autoSize={true}\n * maxRows={5}\n * className=\"max-h-[120px]\"\n * />\n *\n * // Disable auto-sizing for fixed height\n * <AutoSizedTextArea\n * autoSize={false}\n * rows={3}\n * placeholder=\"Fixed height textarea\"\n * />\n * ```\n */\nexport type AutoSizedTextAreaProps = TextAreaProps & {\n /** Whether to automatically adjust height based on content */\n autoSize?: boolean;\n /** Maximum number of rows before scrolling is enabled */\n maxRows?: number;\n};\n\nconst LINE_HEIGHT = 24; // px\nconst LINE_PADDING = 12; // px\n\n/**\n * AutoSizedTextArea Component\n *\n * An enhanced textarea that automatically adjusts its height based on content,\n * providing a smooth user experience for variable-length text input.\n *\n * ## Features\n * - **Auto-Sizing**: Dynamically grows and shrinks based on content\n * - **Row Limits**: Configurable maximum rows before scrolling\n * - **Smooth Transitions**: Seamless height adjustments as user types\n * - **Scroll Management**: Automatic overflow handling when max height reached\n * - **Performance Optimized**: Efficient height calculations and updates\n *\n * ## Technical Details\n * - Line height: 24px with 12px padding\n * - Height calculation: `scrollHeight` vs `maxRows * lineHeight + padding`\n * - Resize: Disabled when auto-sizing is active for smooth experience\n * - Ref forwarding: Supports imperative access to textarea element\n *\n * ## Use Cases\n * - Chat message composition with dynamic sizing\n * - Comment forms that expand with content\n * - Note-taking interfaces with variable length\n * - Social media post creation\n * - Code snippet input with growth limits\n *\n * @example\n * ```tsx\n * // Chat-style auto-expanding textarea\n * const [message, setMessage] = useState('');\n *\n * <AutoSizedTextArea\n * value={message}\n * onChange={(e) => setMessage(e.target.value)}\n * placeholder=\"Type your message...\"\n * autoSize={true}\n * maxRows={8}\n * className=\"min-h-[40px]\"\n * onKeyDown={(e) => {\n * if (e.key === 'Enter' && !e.shiftKey) {\n * e.preventDefault();\n * sendMessage(message);\n * setMessage('');\n * }\n * }}\n * />\n *\n * // Note-taking with generous height limits\n * <AutoSizedTextArea\n * defaultValue={note.content}\n * onChange={handleNoteChange}\n * placeholder=\"Write your notes here...\"\n * autoSize={true}\n * maxRows={20}\n * variant={InputVariant.DEFAULT}\n * />\n * ```\n */\nexport const AutoSizedTextArea: FC<AutoSizedTextAreaProps> = ({\n className,\n autoSize = true,\n onChange,\n maxRows = 999,\n ref,\n ...props\n}) => {\n const textAreaRef = useRef<HTMLTextAreaElement | null>(null);\n\n useImperativeHandle(ref, () => textAreaRef.current!);\n\n const adjustHeight = () => {\n const textAreaEl = textAreaRef.current;\n\n if (!textAreaEl || !autoSize) return;\n\n const textAreaStyle = textAreaEl.style;\n\n // Reset height to get accurate scrollHeight\n textAreaStyle.height = 'auto';\n const scrollHeight = textAreaEl.scrollHeight;\n const maxHeight = LINE_HEIGHT * maxRows + LINE_PADDING;\n const minHeight = LINE_HEIGHT + LINE_PADDING;\n\n // Set the new height\n textAreaStyle.height = `${Math.max(Math.min(scrollHeight, maxHeight), minHeight)}px`;\n };\n\n useLayoutEffect(() => {\n adjustHeight();\n }, [props.value, props.defaultValue, adjustHeight]);\n\n const handleChange: ChangeEventHandler<HTMLTextAreaElement> = (e) => {\n onChange?.(e);\n adjustHeight();\n };\n\n const setRef = (el: HTMLTextAreaElement | null) => {\n textAreaRef.current = el;\n if (el) {\n adjustHeight();\n }\n };\n\n return (\n <TextArea\n ref={setRef}\n onChange={handleChange}\n className={cn('overflow-y-auto', autoSize && 'resize-none', className)}\n {...props}\n />\n );\n};\n"],"mappings":";;;;;;;;AAkDA,MAAM,cAAc;AACpB,MAAM,eAAe;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4DrB,MAAa,qBAAiD,EAC5D,WACA,WAAW,MACX,UACA,UAAU,KACV,KACA,GAAG,YACC;CACJ,MAAM,cAAc,OAAmC,IAAI;CAE3D,oBAAoB,WAAW,YAAY,OAAQ;CAEnD,MAAM,qBAAqB;EACzB,MAAM,aAAa,YAAY;EAE/B,IAAI,CAAC,cAAc,CAAC,UAAU;EAE9B,MAAM,gBAAgB,WAAW;EAGjC,cAAc,SAAS;EACvB,MAAM,eAAe,WAAW;EAChC,MAAM,YAAY,cAAc,UAAU;EAI1C,cAAc,SAAS,GAAG,KAAK,IAAI,KAAK,IAAI,cAAc,SAAS,GAAG,EAAS,EAAE;CACnF;CAEA,sBAAsB;EACpB,aAAa;CACf,GAAG;EAAC,MAAM;EAAO,MAAM;EAAc;CAAY,CAAC;CAElD,MAAM,gBAAyD,MAAM;EACnE,WAAW,CAAC;EACZ,aAAa;CACf;CAEA,MAAM,UAAU,OAAmC;EACjD,YAAY,UAAU;EACtB,IAAI,IACF,aAAa;CAEjB;CAEA,OACE,oBAAC,UAAD;EACE,KAAK;EACL,UAAU;EACV,WAAW,GAAG,mBAAmB,YAAY,eAAe,SAAS;EACrE,GAAI;CACL;AAEL"}
@@ -1,6 +1,6 @@
1
1
  import { passkeyClient } from "@better-auth/passkey/client";
2
2
  import { ssoClient } from "@better-auth/sso/client";
3
- import configuration from "@intlayer/config/built";
3
+ import { editor } from "@intlayer/config/built";
4
4
  import { BACKEND_URL } from "@intlayer/config/defaultValues";
5
5
  import { createAuthClient } from "better-auth/client";
6
6
  import { magicLinkClient, twoFactorClient } from "better-auth/client/plugins";
@@ -21,13 +21,9 @@ const getAuthClient = (backendURL) => createAuthClient({
21
21
  ]
22
22
  });
23
23
  const getAuthAPI = (intlayerConfig) => {
24
- let backendURL = intlayerConfig?.editor?.backendURL ?? configuration?.editor?.backendURL;
24
+ let backendURL = intlayerConfig?.editor?.backendURL ?? editor?.backendURL;
25
25
  if (!backendURL) {
26
26
  backendURL = BACKEND_URL;
27
- console.dir({
28
- intlayerConfig,
29
- configuration
30
- }, { depth: null });
31
27
  console.error("Backend URL is not defined in the Intlayer configuration.");
32
28
  }
33
29
  const client = getAuthClient(backendURL);
@@ -1 +1 @@
1
- {"version":3,"file":"auth.mjs","names":[],"sources":["../../../src/libs/auth.ts"],"sourcesContent":["import { passkeyClient } from '@better-auth/passkey/client';\nimport { ssoClient } from '@better-auth/sso/client';\nimport { default as configuration } from '@intlayer/config/built';\nimport { BACKEND_URL } from '@intlayer/config/defaultValues';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport { createAuthClient } from 'better-auth/client';\nimport { magicLinkClient, twoFactorClient } from 'better-auth/client/plugins';\n\nconst getAuthClient = (backendURL: string) =>\n createAuthClient({\n baseURL: backendURL,\n withCredentials: true, // makes fetch forward cookies\n plugins: [\n twoFactorClient({\n onTwoFactorRedirect: () => {\n // Preserve redirect_url when redirecting to 2FA\n const searchParams = new URLSearchParams(window.location.search);\n const redirectUrl = searchParams.get('redirect_url');\n const twoFaUrl = redirectUrl\n ? `/auth/2fa?redirect_url=${encodeURIComponent(redirectUrl)}`\n : '/auth/2fa';\n window.location.href = twoFaUrl;\n },\n }),\n passkeyClient(),\n magicLinkClient() as never,\n ssoClient(),\n ],\n });\n\ntype AuthClient = ReturnType<typeof getAuthClient>;\n\nexport interface AuthAPI {\n getAuthClient: () => AuthClient;\n signInEmail: AuthClient['signIn']['email'];\n signUpEmail: AuthClient['signUp']['email'];\n signOut: AuthClient['signOut'];\n signInSocial: AuthClient['signIn']['social'];\n linkSocial: AuthClient['linkSocial'];\n changePasswordSession: AuthClient['changePassword'];\n requestPasswordResetSession: AuthClient['requestPasswordReset'];\n resetPassword: AuthClient['resetPassword'];\n verifyEmailSession: AuthClient['verifyEmail'];\n getSession: AuthClient['getSession'];\n forgetPassword: AuthClient['requestPasswordReset'];\n sendVerificationEmail: AuthClient['sendVerificationEmail'];\n changeEmail: AuthClient['changeEmail'];\n deleteUser: AuthClient['deleteUser'];\n revokeSession: AuthClient['revokeSession'];\n revokeSessions: AuthClient['revokeSessions'];\n revokeOtherSessions: AuthClient['revokeOtherSessions'];\n listAccounts: AuthClient['listAccounts'];\n unlinkAccount: AuthClient['unlinkAccount'];\n refreshToken: AuthClient['refreshToken'];\n getAccessToken: AuthClient['getAccessToken'];\n accountInfo: AuthClient['accountInfo'];\n updateUser: AuthClient['updateUser'];\n listSessions: AuthClient['listSessions'];\n enableTwoFactor: AuthClient['twoFactor']['enable'];\n disableTwoFactor: AuthClient['twoFactor']['disable'];\n verifyTotp: AuthClient['twoFactor']['verifyTotp'];\n verifyBackupCode: AuthClient['twoFactor']['verifyBackupCode'];\n addPasskey: AuthClient['passkey']['addPasskey'];\n signInPasskey: AuthClient['signIn']['passkey'];\n deletePasskey: AuthClient['passkey']['deletePasskey'];\n listPasskeys: () => Promise<any>;\n signInMagicLink: (\n // Redeclare it because of type inference issues\n input: { email: string; callbackURL: string }\n ) => any;\n registerSSO: AuthClient['sso']['register'];\n listSSOProviders: () => Promise<any>;\n deleteSSOProvider: (args: { providerId: string }) => Promise<any>;\n signInSSO: AuthClient['signIn']['sso'];\n}\n\nexport const getAuthAPI = (intlayerConfig?: IntlayerConfig): AuthAPI => {\n let backendURL =\n intlayerConfig?.editor?.backendURL ?? configuration?.editor?.backendURL;\n\n if (!backendURL) {\n backendURL = BACKEND_URL;\n console.dir({ intlayerConfig, configuration }, { depth: null });\n console.error('Backend URL is not defined in the Intlayer configuration.');\n }\n\n const client = getAuthClient(backendURL);\n\n const signInEmail: AuthClient['signIn']['email'] = async (...args) => {\n return client.signIn.email(...args);\n };\n\n const signInSocial: AuthClient['signIn']['social'] = async (...args) => {\n return client.signIn.social(...args);\n };\n\n const signUpEmail: AuthClient['signUp']['email'] = async (...args) => {\n return client.signUp.email(...args);\n };\n\n const signOut: AuthClient['signOut'] = async (...args) => {\n return client.signOut(...args);\n };\n\n const changePasswordSession: AuthClient['changePassword'] = async (\n ...args\n ) => {\n return client.changePassword(...args);\n };\n\n const requestPasswordResetSession: AuthClient['requestPasswordReset'] =\n async (...args) => {\n return client.requestPasswordReset(...args);\n };\n\n // @ts-ignore - resetPassword is not typed\n const resetPassword: AuthClient['resetPassword'] = async (...args) => {\n return client.resetPassword(...args);\n };\n\n const verifyEmailSession: AuthClient['verifyEmail'] = async (...args) => {\n return client.verifyEmail(...args);\n };\n\n const getSession: AuthClient['getSession'] = async (...args) => {\n return client.getSession(...args);\n };\n\n const forgetPassword: AuthClient['requestPasswordReset'] = async (\n ...args\n ) => {\n return client.requestPasswordReset(...args);\n };\n\n const sendVerificationEmail: AuthClient['sendVerificationEmail'] = async (\n ...args\n ) => {\n return client.sendVerificationEmail(...args);\n };\n\n const changeEmail: AuthClient['changeEmail'] = async (...args) => {\n return client.changeEmail(...args);\n };\n\n // @ts-ignore - deleteUser is not typed\n const deleteUser: AuthClient['deleteUser'] = async (...args) => {\n return client.deleteUser(...args);\n };\n\n const revokeSession: AuthClient['revokeSession'] = async (...args) => {\n return client.revokeSession(...args);\n };\n\n const revokeSessions: AuthClient['revokeSessions'] = async (...args) => {\n return client.revokeSessions(...args);\n };\n\n const revokeOtherSessions: AuthClient['revokeOtherSessions'] = async (\n ...args\n ) => {\n return client.revokeOtherSessions(...args);\n };\n\n const linkSocial: AuthClient['linkSocial'] = async (...args) => {\n return client.linkSocial(...args);\n };\n\n const listAccounts: AuthClient['listAccounts'] = async (...args) => {\n return client.listAccounts(...args);\n };\n\n const unlinkAccount: AuthClient['unlinkAccount'] = async (...args) => {\n return client.unlinkAccount(...args);\n };\n\n const refreshToken: AuthClient['refreshToken'] = async (...args) => {\n return client.refreshToken(...args);\n };\n\n const getAccessToken: AuthClient['getAccessToken'] = async (...args) => {\n return client.getAccessToken(...args);\n };\n\n const accountInfo: AuthClient['accountInfo'] = async (...args) => {\n return client.accountInfo(...args);\n };\n\n const updateUser: AuthClient['updateUser'] = async (...args) => {\n return client.updateUser(...args);\n };\n\n const listSessions: AuthClient['listSessions'] = async (...args) => {\n return client.listSessions(...args);\n };\n\n const enableTwoFactor: AuthClient['twoFactor']['enable'] = async (\n ...args\n ) => {\n return client.twoFactor.enable(...args) as ReturnType<\n AuthClient['twoFactor']['enable']\n >;\n };\n\n const disableTwoFactor: AuthClient['twoFactor']['disable'] = async (\n ...args\n ) => {\n return client.twoFactor.disable(...args) as ReturnType<\n AuthClient['twoFactor']['disable']\n >;\n };\n\n const verifyTotp: AuthClient['twoFactor']['verifyTotp'] = async (...args) => {\n return client.twoFactor.verifyTotp(...args) as ReturnType<\n AuthClient['twoFactor']['verifyTotp']\n >;\n };\n\n const verifyBackupCode: AuthClient['twoFactor']['verifyBackupCode'] = async (\n ...args\n ) => {\n return client.twoFactor.verifyBackupCode(...args) as ReturnType<\n AuthClient['twoFactor']['verifyBackupCode']\n >;\n };\n\n const addPasskey: AuthClient['passkey']['addPasskey'] = async (...args) => {\n return client.passkey.addPasskey(...args);\n };\n\n const signInPasskey: AuthClient['signIn']['passkey'] = async (...args) => {\n return client.signIn.passkey(...args);\n };\n\n const deletePasskey: AuthClient['passkey']['deletePasskey'] = async (\n ...args\n ) => {\n return client.passkey.deletePasskey(...args);\n };\n\n const listPasskeys = async () => {\n // @ts-ignore - listPasskeys may not be typed yet\n return client.$fetch('/passkey/list-user-passkeys', {\n method: 'GET',\n });\n };\n\n const signInMagicLink: any = async (...args: any[]) => {\n return (client.signIn as any).magicLink(...args);\n };\n\n const signInSSO: AuthClient['signIn']['sso'] = async (...args) => {\n return client.signIn.sso(...args);\n };\n\n const registerSSO: AuthClient['sso']['register'] = async (...args) => {\n return client.sso.register(...args);\n };\n\n const listSSOProviders = async () => {\n // Not implemented yet\n return [];\n };\n\n const deleteSSOProvider = async (_args: { providerId: string }) => {\n // Not implemented yet\n return { success: true };\n };\n\n return {\n getAuthClient: () => client,\n signInEmail,\n signUpEmail,\n signOut,\n signInSocial,\n linkSocial,\n changePasswordSession,\n requestPasswordResetSession,\n resetPassword,\n verifyEmailSession,\n getSession,\n forgetPassword,\n sendVerificationEmail,\n changeEmail,\n deleteUser,\n revokeSession,\n revokeSessions,\n revokeOtherSessions,\n listAccounts,\n unlinkAccount,\n refreshToken,\n getAccessToken,\n accountInfo,\n updateUser,\n listSessions,\n enableTwoFactor,\n disableTwoFactor,\n verifyTotp,\n verifyBackupCode,\n addPasskey,\n signInPasskey,\n deletePasskey,\n listPasskeys,\n signInMagicLink,\n signInSSO,\n registerSSO,\n listSSOProviders,\n deleteSSOProvider,\n };\n};\n"],"mappings":";;;;;;;;AAQA,MAAM,iBAAiB,eACrB,iBAAiB;C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ACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF;AACF"}
1
+ {"version":3,"file":"auth.mjs","names":[],"sources":["../../../src/libs/auth.ts"],"sourcesContent":["import { passkeyClient } from '@better-auth/passkey/client';\nimport { ssoClient } from '@better-auth/sso/client';\nimport { editor } from '@intlayer/config/built';\nimport { BACKEND_URL } from '@intlayer/config/defaultValues';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport { createAuthClient } from 'better-auth/client';\nimport { magicLinkClient, twoFactorClient } from 'better-auth/client/plugins';\n\nconst getAuthClient = (backendURL: string) =>\n createAuthClient({\n baseURL: backendURL,\n withCredentials: true, // makes fetch forward cookies\n plugins: [\n twoFactorClient({\n onTwoFactorRedirect: () => {\n // Preserve redirect_url when redirecting to 2FA\n const searchParams = new URLSearchParams(window.location.search);\n const redirectUrl = searchParams.get('redirect_url');\n const twoFaUrl = redirectUrl\n ? `/auth/2fa?redirect_url=${encodeURIComponent(redirectUrl)}`\n : '/auth/2fa';\n window.location.href = twoFaUrl;\n },\n }),\n passkeyClient(),\n magicLinkClient() as never,\n ssoClient(),\n ],\n });\n\ntype AuthClient = ReturnType<typeof getAuthClient>;\n\nexport interface AuthAPI {\n getAuthClient: () => AuthClient;\n signInEmail: AuthClient['signIn']['email'];\n signUpEmail: AuthClient['signUp']['email'];\n signOut: AuthClient['signOut'];\n signInSocial: AuthClient['signIn']['social'];\n linkSocial: AuthClient['linkSocial'];\n changePasswordSession: AuthClient['changePassword'];\n requestPasswordResetSession: AuthClient['requestPasswordReset'];\n resetPassword: AuthClient['resetPassword'];\n verifyEmailSession: AuthClient['verifyEmail'];\n getSession: AuthClient['getSession'];\n forgetPassword: AuthClient['requestPasswordReset'];\n sendVerificationEmail: AuthClient['sendVerificationEmail'];\n changeEmail: AuthClient['changeEmail'];\n deleteUser: AuthClient['deleteUser'];\n revokeSession: AuthClient['revokeSession'];\n revokeSessions: AuthClient['revokeSessions'];\n revokeOtherSessions: AuthClient['revokeOtherSessions'];\n listAccounts: AuthClient['listAccounts'];\n unlinkAccount: AuthClient['unlinkAccount'];\n refreshToken: AuthClient['refreshToken'];\n getAccessToken: AuthClient['getAccessToken'];\n accountInfo: AuthClient['accountInfo'];\n updateUser: AuthClient['updateUser'];\n listSessions: AuthClient['listSessions'];\n enableTwoFactor: AuthClient['twoFactor']['enable'];\n disableTwoFactor: AuthClient['twoFactor']['disable'];\n verifyTotp: AuthClient['twoFactor']['verifyTotp'];\n verifyBackupCode: AuthClient['twoFactor']['verifyBackupCode'];\n addPasskey: AuthClient['passkey']['addPasskey'];\n signInPasskey: AuthClient['signIn']['passkey'];\n deletePasskey: AuthClient['passkey']['deletePasskey'];\n listPasskeys: () => Promise<any>;\n signInMagicLink: (\n // Redeclare it because of type inference issues\n input: { email: string; callbackURL: string }\n ) => any;\n registerSSO: AuthClient['sso']['register'];\n listSSOProviders: () => Promise<any>;\n deleteSSOProvider: (args: { providerId: string }) => Promise<any>;\n signInSSO: AuthClient['signIn']['sso'];\n}\n\nexport const getAuthAPI = (\n intlayerConfig?: Pick<IntlayerConfig, 'editor'>\n): AuthAPI => {\n let backendURL = intlayerConfig?.editor?.backendURL ?? editor?.backendURL;\n\n if (!backendURL) {\n backendURL = BACKEND_URL;\n console.error('Backend URL is not defined in the Intlayer configuration.');\n }\n\n const client = getAuthClient(backendURL);\n\n const signInEmail: AuthClient['signIn']['email'] = async (...args) => {\n return client.signIn.email(...args);\n };\n\n const signInSocial: AuthClient['signIn']['social'] = async (...args) => {\n return client.signIn.social(...args);\n };\n\n const signUpEmail: AuthClient['signUp']['email'] = async (...args) => {\n return client.signUp.email(...args);\n };\n\n const signOut: AuthClient['signOut'] = async (...args) => {\n return client.signOut(...args);\n };\n\n const changePasswordSession: AuthClient['changePassword'] = async (\n ...args\n ) => {\n return client.changePassword(...args);\n };\n\n const requestPasswordResetSession: AuthClient['requestPasswordReset'] =\n async (...args) => {\n return client.requestPasswordReset(...args);\n };\n\n // @ts-ignore - resetPassword is not typed\n const resetPassword: AuthClient['resetPassword'] = async (...args) => {\n return client.resetPassword(...args);\n };\n\n const verifyEmailSession: AuthClient['verifyEmail'] = async (...args) => {\n return client.verifyEmail(...args);\n };\n\n const getSession: AuthClient['getSession'] = async (...args) => {\n return client.getSession(...args);\n };\n\n const forgetPassword: AuthClient['requestPasswordReset'] = async (\n ...args\n ) => {\n return client.requestPasswordReset(...args);\n };\n\n const sendVerificationEmail: AuthClient['sendVerificationEmail'] = async (\n ...args\n ) => {\n return client.sendVerificationEmail(...args);\n };\n\n const changeEmail: AuthClient['changeEmail'] = async (...args) => {\n return client.changeEmail(...args);\n };\n\n // @ts-ignore - deleteUser is not typed\n const deleteUser: AuthClient['deleteUser'] = async (...args) => {\n return client.deleteUser(...args);\n };\n\n const revokeSession: AuthClient['revokeSession'] = async (...args) => {\n return client.revokeSession(...args);\n };\n\n const revokeSessions: AuthClient['revokeSessions'] = async (...args) => {\n return client.revokeSessions(...args);\n };\n\n const revokeOtherSessions: AuthClient['revokeOtherSessions'] = async (\n ...args\n ) => {\n return client.revokeOtherSessions(...args);\n };\n\n const linkSocial: AuthClient['linkSocial'] = async (...args) => {\n return client.linkSocial(...args);\n };\n\n const listAccounts: AuthClient['listAccounts'] = async (...args) => {\n return client.listAccounts(...args);\n };\n\n const unlinkAccount: AuthClient['unlinkAccount'] = async (...args) => {\n return client.unlinkAccount(...args);\n };\n\n const refreshToken: AuthClient['refreshToken'] = async (...args) => {\n return client.refreshToken(...args);\n };\n\n const getAccessToken: AuthClient['getAccessToken'] = async (...args) => {\n return client.getAccessToken(...args);\n };\n\n const accountInfo: AuthClient['accountInfo'] = async (...args) => {\n return client.accountInfo(...args);\n };\n\n const updateUser: AuthClient['updateUser'] = async (...args) => {\n return client.updateUser(...args);\n };\n\n const listSessions: AuthClient['listSessions'] = async (...args) => {\n return client.listSessions(...args);\n };\n\n const enableTwoFactor: AuthClient['twoFactor']['enable'] = async (\n ...args\n ) => {\n return client.twoFactor.enable(...args) as ReturnType<\n AuthClient['twoFactor']['enable']\n >;\n };\n\n const disableTwoFactor: AuthClient['twoFactor']['disable'] = async (\n ...args\n ) => {\n return client.twoFactor.disable(...args) as ReturnType<\n AuthClient['twoFactor']['disable']\n >;\n };\n\n const verifyTotp: AuthClient['twoFactor']['verifyTotp'] = async (...args) => {\n return client.twoFactor.verifyTotp(...args) as ReturnType<\n AuthClient['twoFactor']['verifyTotp']\n >;\n };\n\n const verifyBackupCode: AuthClient['twoFactor']['verifyBackupCode'] = async (\n ...args\n ) => {\n return client.twoFactor.verifyBackupCode(...args) as ReturnType<\n AuthClient['twoFactor']['verifyBackupCode']\n >;\n };\n\n const addPasskey: AuthClient['passkey']['addPasskey'] = async (...args) => {\n return client.passkey.addPasskey(...args);\n };\n\n const signInPasskey: AuthClient['signIn']['passkey'] = async (...args) => {\n return client.signIn.passkey(...args);\n };\n\n const deletePasskey: AuthClient['passkey']['deletePasskey'] = async (\n ...args\n ) => {\n return client.passkey.deletePasskey(...args);\n };\n\n const listPasskeys = async () => {\n // @ts-ignore - listPasskeys may not be typed yet\n return client.$fetch('/passkey/list-user-passkeys', {\n method: 'GET',\n });\n };\n\n const signInMagicLink: any = async (...args: any[]) => {\n return (client.signIn as any).magicLink(...args);\n };\n\n const signInSSO: AuthClient['signIn']['sso'] = async (...args) => {\n return client.signIn.sso(...args);\n };\n\n const registerSSO: AuthClient['sso']['register'] = async (...args) => {\n return client.sso.register(...args);\n };\n\n const listSSOProviders = async () => {\n // Not implemented yet\n return [];\n };\n\n const deleteSSOProvider = async (_args: { providerId: string }) => {\n // Not implemented yet\n return { success: true };\n };\n\n return {\n getAuthClient: () => client,\n signInEmail,\n signUpEmail,\n signOut,\n signInSocial,\n linkSocial,\n changePasswordSession,\n requestPasswordResetSession,\n resetPassword,\n verifyEmailSession,\n getSession,\n forgetPassword,\n sendVerificationEmail,\n changeEmail,\n deleteUser,\n revokeSession,\n revokeSessions,\n revokeOtherSessions,\n listAccounts,\n unlinkAccount,\n refreshToken,\n getAccessToken,\n accountInfo,\n updateUser,\n listSessions,\n enableTwoFactor,\n disableTwoFactor,\n verifyTotp,\n verifyBackupCode,\n addPasskey,\n signInPasskey,\n deletePasskey,\n listPasskeys,\n signInMagicLink,\n signInSSO,\n registerSSO,\n listSSOProviders,\n deleteSSOProvider,\n };\n};\n"],"mappings":";;;;;;;;AAQA,MAAM,iBAAiB,eACrB,iBAAiB;CACf,SAAS;CACT,iBAAiB;CACjB,SAAS;EACP,gBAAgB,EACd,2BAA2B;GAGzB,MAAM,cAAc,IADK,gBAAgB,OAAO,SAAS,MAC1B,EAAE,IAAI,cAAc;GACnD,MAAM,WAAW,cACb,0BAA0B,mBAAmB,WAAW,MACxD;GACJ,OAAO,SAAS,OAAO;EACzB,EACF,CAAC;EACD,cAAc;EACd,gBAAgB;EAChB,UAAU;CACZ;AACF,CAAC;AAgDH,MAAa,cACX,mBACY;CACZ,IAAI,aAAa,gBAAgB,QAAQ,cAAc,QAAQ;CAE/D,IAAI,CAAC,YAAY;EACf,aAAa;EACb,QAAQ,MAAM,2DAA2D;CAC3E;CAEA,MAAM,SAAS,cAAc,UAAU;CAEvC,MAAM,cAA6C,OAAO,GAAG,SAAS;EACpE,OAAO,OAAO,OAAO,MAAM,GAAG,IAAI;CACpC;CAEA,MAAM,eAA+C,OAAO,GAAG,SAAS;EACtE,OAAO,OAAO,OAAO,OAAO,GAAG,IAAI;CACrC;CAEA,MAAM,cAA6C,OAAO,GAAG,SAAS;EACpE,OAAO,OAAO,OAAO,MAAM,GAAG,IAAI;CACpC;CAEA,MAAM,UAAiC,OAAO,GAAG,SAAS;EACxD,OAAO,OAAO,QAAQ,GAAG,IAAI;CAC/B;CAEA,MAAM,wBAAsD,OAC1D,GAAG,SACA;EACH,OAAO,OAAO,eAAe,GAAG,IAAI;CACtC;CAEA,MAAM,8BACJ,OAAO,GAAG,SAAS;EACjB,OAAO,OAAO,qBAAqB,GAAG,IAAI;CAC5C;CAGF,MAAM,gBA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