@cryptlex/web-components 6.6.6-alpha85 → 6.6.6-alpha87
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.
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use client";import{jsx as n,jsxs as C}from"react/jsx-runtime";import{useQuery as w}from"@tanstack/react-query";import{useId as L,useState as K}from"react";import{Select as R,Autocomplete as _}from"react-aria-components";import{Loader as P}from"./loader.js";import{Menu as V,MenuItem as D}from"./menu.js";import{PopoverTrigger as G}from"./popover.js";import{SearchField as Q}from"./searchfield.js";import{useCtxClient as k}from"../utilities/ctx-client.js";import{isEmptyValue as z,getEmptyLabel as F}from"../utilities/empty-option.js";import{getFieldErrorMessage as c}from"../utilities/form.js";import{useFieldContext as M}from"../utilities/form-context.js";import{FormField as H}from"./form.js";import{SelectTrigger as J,SelectPopover as U}from"./select.js";import"../utilities/theme.js";import"clsx";import"./icons.js";import"./list-box.js";import"./button.js";import"class-variance-authority";import"@tanstack/react-form";function W(r){return Array.isArray(r)&&r.every(i=>i&&typeof i=="object"&&"id"in i&&"name"in i)}function N({label:r,description:i,errorMessage:e,requiredIndicator:t,isDisabled:o,isInvalid:s,onBlur:u,path:a,onChange:
|
|
1
|
+
"use client";import{jsx as n,jsxs as C}from"react/jsx-runtime";import{useQuery as w}from"@tanstack/react-query";import{useId as L,useState as K}from"react";import{Select as R,Autocomplete as _}from"react-aria-components";import{Loader as P}from"./loader.js";import{Menu as V,MenuItem as D}from"./menu.js";import{PopoverTrigger as G}from"./popover.js";import{SearchField as Q}from"./searchfield.js";import{useCtxClient as k}from"../utilities/ctx-client.js";import{isEmptyValue as z,getEmptyLabel as F}from"../utilities/empty-option.js";import{getFieldErrorMessage as c}from"../utilities/form.js";import{useFieldContext as M}from"../utilities/form-context.js";import{FormField as H}from"./form.js";import{SelectTrigger as J,SelectPopover as U}from"./select.js";import"../utilities/theme.js";import"clsx";import"./icons.js";import"./list-box.js";import"./button.js";import"class-variance-authority";import"@tanstack/react-form";function W(r){return Array.isArray(r)&&r.every(i=>i&&typeof i=="object"&&"id"in i&&"name"in i)}function N({label:r,description:i,errorMessage:e,requiredIndicator:t,isDisabled:o,isInvalid:s,onBlur:u,path:a,onChange:h,value:f,renderLabel:q,accessor:p,defaultParams:g,className:x,emptyOption:E,...y}){if(a==="/v3/me")throw Error('Path "/v3/me" is not supported with IdSearch since it is not a searchable resource.');const A=L(),S=y.id||A,B=k(),[d,T]=K(""),{data:I,isError:v,isFetching:b,error:j}=w({queryKey:["get",a,d],queryFn:async()=>{const m=(await B.GET(a,{params:{query:{search:d,...g?.query,limit:50,page:1},path:{...g?.path}}})).data;return m&&W(m)?m:[]}});return n("div",{className:"group form-field","data-invalid":s?"":void 0,children:n(H,{label:r,description:i,errorMessage:e,requiredIndicator:t,htmlFor:S,children:n(R,{isInvalid:s,children:C(G,{onOpenChange:l=>{l||u?.(f)},children:[n(J,{id:S,isDisabled:o,className:x??"w-full",children:q(f,I,E)}),n(U,{placement:"bottom start",children:C(_,{inputValue:d,onInputChange:T,children:[n(Q,{className:"p-2",autoFocus:!0}),b&&n("div",{className:"p-input",children:n(P,{className:"mx-auto"})}),!b&&!v&&n(V,{...y,className:"max-h-48",items:I,renderEmptyState:()=>n("div",{className:"body-sm p-2",children:"No results found."}),children:l=>n(D,{id:l[p],children:l.name},l[p])}),v&&n("div",{className:"text-destructive p-icon body-sm",children:j.message})]})})]})})})})}function X({...r}){const i=r.value?[r.value]:[];return n(N,{selectedKeys:i,onSelectionChange:e=>{const t=Array.from(e).filter(o=>typeof o=="string")[0];r.onChange(t)},renderLabel:(e,t,o)=>o&&z(e)?F(o):t?.find(s=>s.id===e)?.name??"",selectionMode:"single",...r})}function Y({...r}){const i=r.value;return n(N,{selectedKeys:i,onSelectionChange:e=>{const t=Array.from(e).filter(o=>typeof o=="string");r.onChange(t.length>0?t:[])},selectionMode:"multiple",renderLabel:(e,t,o)=>{if(o&&(!e||e.length===0))return F(o);const u=(e??[]).map(a=>t?.find(h=>h.id===a)?.name??a);return u.length>0?u.join(","):""},...r})}function Se({isDisabled:r,...i}){const e=M({disabled:r});return n(X,{requiredIndicator:e.isRequired,isDisabled:r||e.isSubmitting,value:e.state.value,onBlur:t=>e.handleBlur(),onChange:t=>e.handleChange(t),isInvalid:!!c(e),errorMessage:c(e),...i})}function Ie({isDisabled:r,...i}){const e=M({disabled:r});return n(Y,{requiredIndicator:e.isRequired,isDisabled:r||e.isSubmitting,value:e.state.value,onBlur:t=>e.handleBlur(),onChange:t=>e.handleChange(t),isInvalid:!!c(e),errorMessage:c(e),...i})}export{Y as MultipleIdSearchInput,X as SingleIdSearchInput,Ie as TfMultipleIdSearchInput,Se as TfSingleIdSearchInput};
|
|
2
2
|
//# sourceMappingURL=id-search.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"id-search.js","sources":["../../lib/components/id-search.tsx"],"sourcesContent":["'use client';\nimport { useQuery } from '@tanstack/react-query';\nimport { useId, useState } from 'react';\nimport { Select as AriaSelect, Autocomplete } from 'react-aria-components';\n\nimport type { ClientPathsWithMethod } from 'openapi-fetch';\nimport { Loader } from '../components/loader';\nimport { Menu, MenuItem } from '../components/menu';\nimport { PopoverTrigger } from '../components/popover';\nimport { SearchField } from '../components/searchfield';\nimport { useCtxClient, type CtxClientType } from '../utilities/ctx-client';\nimport { getEmptyLabel, isEmptyValue, type EmptyOption } from '../utilities/empty-option';\nimport { getFieldErrorMessage } from '../utilities/form';\nimport { useFieldContext } from '../utilities/form-context';\nimport { FormField, type FormFieldProps } from './form';\nimport { SelectPopover, SelectTrigger } from './select';\n\n/**\n * Minimal resource shape used by the ID search inputs.\n * Only `id` and `name` are required.\n *\n * @example\n * const user: BaseSearchableResource = { id: 'u_123', name: 'Nabeel Farooq' };\n */\ntype BaseSearchableResource = {\n /** Unique identifier used as the input value. */\n id: string;\n /** Human-readable label shown to users. */\n name: string;\n};\n\n/**\n * Type guard to check if a value is an array of searchable resources\n */\nfunction isSearchableResourceArray<T extends BaseSearchableResource>(value: unknown): value is T[] {\n return (\n Array.isArray(value) && value.every(item => item && typeof item === 'object' && 'id' in item && 'name' in item)\n );\n}\n\n/**\n * - Generic, accessible ID-search building block.\n * - Search (powered by react-query)\n * - Renders an accessible Autocomplete + Menu listbox\n * - Exposes a controlled `value`/`onChange` contract so callers (and wrappers) can manage state\n *\n * @template T - resource type extending `BaseSearchableResource` (must have `id` and `name`)\n * @template V - controlled value type (e.g. `string` for single-select or `string[]` for multi-select)\n *\n * @param props - props object (see inline property JSDoc for the most important fields)\n *\n * @remarks\n * - Search is automatically handled based on the `resource` prop using the API client from context\n * - When the popover closes, `onBlur` (if provided) is called with the current `value`.\n * - `renderLabel` must convert `value` to a readable string for the control button.\n * - `defaultParams` can be used to pass additional query parameters to the search endpoint\n *\n * @example\n * <BaseIdSearchInput\n * label=\"Owner\"\n * resource=\"user\"\n * value={ownerId}\n * onChange={setOwnerId}\n * renderLabel={(v, data) => data?.find(d => d.id === v)?.name ?? v}\n * />\n *\n * @testing\n * - Ensure API client is provided via context; assert keyboard navigation, open/close behavior, and `onBlur` call on popover close.\n */\nfunction BaseIdSearchInput<T extends BaseSearchableResource, V>({\n label,\n description,\n errorMessage,\n requiredIndicator,\n isDisabled,\n isInvalid,\n onBlur,\n path,\n onChange,\n value,\n renderLabel,\n accessor,\n defaultParams,\n className,\n emptyOption,\n ...props\n}: FormFieldProps & {\n path: ClientPathsWithMethod<CtxClientType, 'get'>;\n /** Disable interactions. */\n isDisabled?: boolean;\n /** Whether the field is invalid. */\n isInvalid?: boolean;\n /** Key used to access an alternate display accessor on item (kept for compatibility). */\n accessor: keyof BaseSearchableResource;\n /** Controlled value. */\n value: V;\n /** Called when popover closes or the field blurs with the current value. */\n onBlur?: (v: V) => void;\n /** Controlled change handler. */\n onChange: (v: V) => void;\n /** Render a human-readable label for the current value using the latest data. */\n renderLabel: (v: V, data: T[] | undefined, emptyOption?: EmptyOption) => string;\n /** Default parameters to include in the request. This is useful when using /v3/users?role='admin' or /v3/organizations/ID/user-groups */\n defaultParams?: Record<'path' | 'query', any>;\n /** Optional className to customize the trigger button styling. */\n className?: string;\n /* Optional empty option to show when value is empty. */\n emptyOption?: EmptyOption;\n} & Omit<React.ComponentProps<typeof Menu>, 'items' | 'className'>) {\n if (path === '/v3/me') {\n throw Error('Path \"/v3/me\" is not supported with IdSearch since it is not a searchable resource.');\n }\n\n const generatedId = useId();\n const fieldId = props.id || generatedId;\n const client = useCtxClient();\n\n const [search, _setSearch] = useState('');\n const { data, isError, isFetching, error } = useQuery({\n // This is the schema that openapi-react-query follows as of 0.5.1\n queryKey: ['get', path],\n queryFn: async (): Promise<T[]> => {\n const result = await client.GET(path, {\n params: {\n query: {\n search,\n ...defaultParams?.query,\n },\n path: {\n ...defaultParams?.path,\n },\n },\n });\n\n // Type narrowing: result.data is inferred as never due to complex union types\n // We use unknown to bypass this and then validate with our type guard\n const responseData: unknown = result.data;\n if (responseData && isSearchableResourceArray<T>(responseData)) {\n return responseData;\n }\n return [];\n },\n });\n\n return (\n <div className=\"group form-field\" data-invalid={isInvalid ? '' : undefined}>\n <FormField {...{ label, description, errorMessage, requiredIndicator, htmlFor: fieldId }}>\n <AriaSelect isInvalid={isInvalid}>\n <PopoverTrigger\n onOpenChange={o => {\n if (!o) {\n // searchInputRef.current?.focus();\n onBlur?.(value);\n }\n }}\n >\n <SelectTrigger id={fieldId} isDisabled={isDisabled} className={className ?? 'w-full'}>\n {renderLabel(value, data, emptyOption)}\n </SelectTrigger>\n <SelectPopover placement=\"bottom start\">\n <Autocomplete inputValue={search} onInputChange={_setSearch}>\n <SearchField className={'p-2'} autoFocus />\n {isFetching && (\n <div className=\"p-input\">\n <Loader className=\"mx-auto\" />\n </div>\n )}\n {!isFetching && !isError && (\n <Menu\n {...props}\n className={'max-h-48'}\n items={data}\n renderEmptyState={() => <div className=\"body-sm p-2\">No results found.</div>}\n >\n {item => (\n <MenuItem key={item[accessor]} id={item[accessor]}>\n {item.name}\n </MenuItem>\n )}\n </Menu>\n )}\n {isError && <div className=\"text-destructive p-icon body-sm\">{error.message}</div>}\n </Autocomplete>\n </SelectPopover>\n </PopoverTrigger>\n </AriaSelect>\n </FormField>\n </div>\n );\n}\n\n/**\n * Single-selection ID search input.\n *\n * Thin, typed wrapper around `BaseIdSearchInput` specialized for the very common single-ID case.\n * Adapts the internal selection events into `onChange(id?: string)` and renders the selected label.\n *\n * @template T - resource type (extends BaseSearchableResource)\n *\n * @param props - Inherits `BaseIdSearchInput` props but uses `string[]` value type.\n *\n * @example\n * <SingleIdSearchInput\n * label=\"Reporter\"\n * value={reporterId}\n * onChange={setReporterId}\n * />\n *\n */\nexport function SingleIdSearchInput<T extends BaseSearchableResource>({\n ...props\n}: Omit<\n React.ComponentProps<typeof BaseIdSearchInput<T, string | null>>,\n 'onSelectionChange' | 'selectionMode' | 'selectedKeys' | 'renderLabel'\n>) {\n const selectedKeys = props.value ? [props.value] : [];\n\n return (\n <BaseIdSearchInput\n selectedKeys={selectedKeys}\n onSelectionChange={e => {\n const val = Array.from(e).filter(v => typeof v === 'string')[0];\n props.onChange(val);\n }}\n renderLabel={(v, d, emptyOption) => {\n // If value is empty and emptyOption is set, show the empty label\n if (emptyOption && isEmptyValue(v)) {\n return getEmptyLabel(emptyOption);\n }\n return d?.find(di => di.id === v)?.name ?? '';\n }}\n selectionMode=\"single\"\n {...props}\n />\n );\n}\n\n/**\n * Multi-selection ID search input.\n *\n * Thin wrapper around `BaseIdSearchInput` for the multiple-ID (`string[]`) case.\n * Adapts internal selection events into `onChange(ids: string[])`.\n *\n * @template T - resource type (extends BaseSearchableResource)\n *\n * @param props - Inherits `BaseIdSearchInput` props but uses `string[]` value type.\n *\n * @example\n * <MultipleIdSearchInput\n * label=\"Reviewers\"\n * value={reviewerIds}\n * onChange={setReviewerIds}\n * />\n *\n * @remarks\n * - The `renderLabel` joins selected item names with commas for compact display.\n */\nexport function MultipleIdSearchInput<T extends BaseSearchableResource>({\n ...props\n}: Omit<\n React.ComponentProps<typeof BaseIdSearchInput<T, string[]>>,\n 'renderLabel' | 'onSelectionChange' | 'selectionMode' | 'selectedKeys'\n>) {\n const selectedKeys = props.value;\n\n return (\n <BaseIdSearchInput\n selectedKeys={selectedKeys}\n onSelectionChange={e => {\n const vals = Array.from(e).filter(v => typeof v === 'string');\n props.onChange(vals.length > 0 ? vals : []);\n }}\n selectionMode=\"multiple\"\n renderLabel={(v, d, emptyOption) => {\n // If array is empty and emptyOption is set, show the empty label\n if (emptyOption && (!v || v.length === 0)) {\n return getEmptyLabel(emptyOption);\n }\n\n const values = v ?? [];\n const labels = values.map(vi => {\n return d?.find(di => di.id === vi)?.name ?? vi;\n });\n return labels.length > 0 ? labels.join(',') : '';\n }}\n {...props}\n />\n );\n}\n\n/**\n * Form-integrated single-select ID input (field wrapper).\n *\n * Integrates `SingleIdSearchInput` into the form system using `useFieldContext`.\n * - wires `value`, `onChange`, and `onBlur`\n * - disables the control while the form is submitting\n * - surfaces field-level error messages\n *\n * @example\n * <TfSingleIdSearchInput name=\"ownerId\" label=\"Owner\" />\n \n */\nexport function TfSingleIdSearchInput({\n isDisabled,\n ...props\n}: Omit<React.ComponentProps<typeof SingleIdSearchInput>, 'value' | 'onChange' | 'onBlur'>) {\n const field = useFieldContext<string | null>({ disabled: isDisabled });\n return (\n <SingleIdSearchInput\n requiredIndicator={field.isRequired}\n isDisabled={isDisabled || field.isSubmitting}\n value={field.state.value}\n onBlur={_ => field.handleBlur()}\n onChange={e => field.handleChange(e)}\n isInvalid={!!getFieldErrorMessage(field)}\n errorMessage={getFieldErrorMessage(field)}\n {...props}\n />\n );\n}\n\n/**\n * Form-integrated multi-select ID input (field wrapper).\n *\n * Integrates `MultipleIdSearchInput` into the form system using `useFieldContext`.\n * - wires `value`, `onChange`, and `onBlur`\n * - disables the control while the form is submitting\n * - surfaces field-level error messages\n *\n * @example\n * <TfMultipleIdSearchInput name=\"reviewerIds\" label=\"Reviewers\" />\n *\n */\nexport function TfMultipleIdSearchInput({\n isDisabled,\n ...props\n}: Omit<React.ComponentProps<typeof MultipleIdSearchInput>, 'value' | 'onChange'>) {\n const field = useFieldContext<string[]>({ disabled: isDisabled });\n return (\n <MultipleIdSearchInput\n requiredIndicator={field.isRequired}\n isDisabled={isDisabled || field.isSubmitting}\n value={field.state.value}\n onBlur={_ => field.handleBlur()}\n onChange={e => field.handleChange(e)}\n isInvalid={!!getFieldErrorMessage(field)}\n errorMessage={getFieldErrorMessage(field)}\n {...props}\n />\n );\n}\n"],"names":["isSearchableResourceArray","value","item","BaseIdSearchInput","label","description","errorMessage","requiredIndicator","isDisabled","isInvalid","onBlur","path","onChange","renderLabel","accessor","defaultParams","className","emptyOption","props","generatedId","useId","fieldId","client","useCtxClient","search","_setSearch","useState","data","isError","isFetching","error","useQuery","responseData","jsx","FormField","AriaSelect","jsxs","PopoverTrigger","o","SelectTrigger","SelectPopover","Autocomplete","SearchField","Loader","Menu","MenuItem","SingleIdSearchInput","selectedKeys","val","v","d","isEmptyValue","getEmptyLabel","di","MultipleIdSearchInput","vals","labels","vi","TfSingleIdSearchInput","field","useFieldContext","_","e","getFieldErrorMessage","TfMultipleIdSearchInput"],"mappings":"65BAkCA,SAASA,EAA4DC,EAA8B,CAC/F,OACI,MAAM,QAAQA,CAAK,GAAKA,EAAM,MAAMC,GAAQA,GAAQ,OAAOA,GAAS,UAAY,OAAQA,GAAQ,SAAUA,CAAI,CAEtH,CA+BA,SAASC,EAAuD,CAC5D,MAAAC,EACA,YAAAC,EACA,aAAAC,EACA,kBAAAC,EACA,WAAAC,EACA,UAAAC,EACA,OAAAC,EACA,KAAAC,EACA,SAAAC,EACA,MAAAX,EACA,YAAAY,EACA,SAAAC,EACA,cAAAC,EACA,UAAAC,EACA,YAAAC,EACA,GAAGC,CACP,EAsBoE,CAChE,GAAIP,IAAS,SACT,MAAM,MAAM,qFAAqF,EAGrG,MAAMQ,EAAcC,EAAA,EACdC,EAAUH,EAAM,IAAMC,EACtBG,EAAS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AG,MAAQA,CAC/C,EACD,OAAOD,EAAO,OAAS,EAAIA,EAAO,KAAK,GAAG,EAAI,EAClD,EACC,GAAGtC,CAAA,CAAA,CAGhB,CAcO,SAASwC,GAAsB,CAClC,WAAAlD,EACA,GAAGU,CACP,EAA4F,CACxF,MAAMyC,EAAQC,EAA+B,CAAE,SAAUpD,EAAY,EACrE,OACIyB,EAACa,EAAA,CACG,kBAAmBa,EAAM,WACzB,WAAYnD,GAAcmD,EAAM,aAChC,MAAOA,EAAM,MAAM,MACnB,OAAQE,GAAKF,EAAM,WAAA,EACnB,SAAUG,GAAKH,EAAM,aAAaG,CAAC,EACnC,UAAW,CAAC,CAACC,EAAqBJ,CAAK,EACvC,aAAcI,EAAqBJ,CAAK,EACvC,GAAGzC,CAAA,CAAA,CAGhB,CAcO,SAAS8C,GAAwB,CACpC,WAAAxD,EACA,GAAGU,CACP,EAAmF,CAC/E,MAAMyC,EAAQC,EAA0B,CAAE,SAAUpD,EAAY,EAChE,OACIyB,EAACqB,EAAA,CACG,kBAAmBK,EAAM,WACzB,WAAYnD,GAAcmD,EAAM,aAChC,MAAOA,EAAM,MAAM,MACnB,OAAQE,GAAKF,EAAM,WAAA,EACnB,SAAUG,GAAKH,EAAM,aAAaG,CAAC,EACnC,UAAW,CAAC,CAACC,EAAqBJ,CAAK,EACvC,aAAcI,EAAqBJ,CAAK,EACvC,GAAGzC,CAAA,CAAA,CAGhB"}
|
|
1
|
+
{"version":3,"file":"id-search.js","sources":["../../lib/components/id-search.tsx"],"sourcesContent":["'use client';\nimport { useQuery } from '@tanstack/react-query';\nimport { useId, useState } from 'react';\nimport { Select as AriaSelect, Autocomplete } from 'react-aria-components';\n\nimport type { ClientPathsWithMethod } from 'openapi-fetch';\nimport { Loader } from '../components/loader';\nimport { Menu, MenuItem } from '../components/menu';\nimport { PopoverTrigger } from '../components/popover';\nimport { SearchField } from '../components/searchfield';\nimport { useCtxClient, type CtxClientType } from '../utilities/ctx-client';\nimport { getEmptyLabel, isEmptyValue, type EmptyOption } from '../utilities/empty-option';\nimport { getFieldErrorMessage } from '../utilities/form';\nimport { useFieldContext } from '../utilities/form-context';\nimport { FormField, type FormFieldProps } from './form';\nimport { SelectPopover, SelectTrigger } from './select';\n\n/**\n * Minimal resource shape used by the ID search inputs.\n * Only `id` and `name` are required.\n *\n * @example\n * const user: BaseSearchableResource = { id: 'u_123', name: 'Nabeel Farooq' };\n */\ntype BaseSearchableResource = {\n /** Unique identifier used as the input value. */\n id: string;\n /** Human-readable label shown to users. */\n name: string;\n};\n\n/**\n * Type guard to check if a value is an array of searchable resources\n */\nfunction isSearchableResourceArray<T extends BaseSearchableResource>(value: unknown): value is T[] {\n return (\n Array.isArray(value) && value.every(item => item && typeof item === 'object' && 'id' in item && 'name' in item)\n );\n}\n\n/**\n * - Generic, accessible ID-search building block.\n * - Search (powered by react-query)\n * - Renders an accessible Autocomplete + Menu listbox\n * - Exposes a controlled `value`/`onChange` contract so callers (and wrappers) can manage state\n *\n * @template T - resource type extending `BaseSearchableResource` (must have `id` and `name`)\n * @template V - controlled value type (e.g. `string` for single-select or `string[]` for multi-select)\n *\n * @param props - props object (see inline property JSDoc for the most important fields)\n *\n * @remarks\n * - Search is automatically handled based on the `resource` prop using the API client from context\n * - When the popover closes, `onBlur` (if provided) is called with the current `value`.\n * - `renderLabel` must convert `value` to a readable string for the control button.\n * - `defaultParams` can be used to pass additional query parameters to the search endpoint\n *\n * @example\n * <BaseIdSearchInput\n * label=\"Owner\"\n * resource=\"user\"\n * value={ownerId}\n * onChange={setOwnerId}\n * renderLabel={(v, data) => data?.find(d => d.id === v)?.name ?? v}\n * />\n *\n * @testing\n * - Ensure API client is provided via context; assert keyboard navigation, open/close behavior, and `onBlur` call on popover close.\n */\nfunction BaseIdSearchInput<T extends BaseSearchableResource, V>({\n label,\n description,\n errorMessage,\n requiredIndicator,\n isDisabled,\n isInvalid,\n onBlur,\n path,\n onChange,\n value,\n renderLabel,\n accessor,\n defaultParams,\n className,\n emptyOption,\n ...props\n}: FormFieldProps & {\n path: ClientPathsWithMethod<CtxClientType, 'get'>;\n /** Disable interactions. */\n isDisabled?: boolean;\n /** Whether the field is invalid. */\n isInvalid?: boolean;\n /** Key used to access an alternate display accessor on item (kept for compatibility). */\n accessor: keyof BaseSearchableResource;\n /** Controlled value. */\n value: V;\n /** Called when popover closes or the field blurs with the current value. */\n onBlur?: (v: V) => void;\n /** Controlled change handler. */\n onChange: (v: V) => void;\n /** Render a human-readable label for the current value using the latest data. */\n renderLabel: (v: V, data: T[] | undefined, emptyOption?: EmptyOption) => string;\n /** Default parameters to include in the request. This is useful when using /v3/users?role='admin' or /v3/organizations/ID/user-groups */\n defaultParams?: Record<'path' | 'query', any>;\n /** Optional className to customize the trigger button styling. */\n className?: string;\n /* Optional empty option to show when value is empty. */\n emptyOption?: EmptyOption;\n} & Omit<React.ComponentProps<typeof Menu>, 'items' | 'className'>) {\n if (path === '/v3/me') {\n throw Error('Path \"/v3/me\" is not supported with IdSearch since it is not a searchable resource.');\n }\n\n const generatedId = useId();\n const fieldId = props.id || generatedId;\n const client = useCtxClient();\n\n const [search, _setSearch] = useState('');\n const { data, isError, isFetching, error } = useQuery({\n // This is the schema that openapi-react-query follows as of 0.5.1\n queryKey: ['get', path, search],\n queryFn: async (): Promise<T[]> => {\n const result = await client.GET(path, {\n params: {\n query: {\n search,\n ...defaultParams?.query,\n limit: 50,\n page: 1,\n },\n path: {\n ...defaultParams?.path,\n },\n },\n });\n\n // Type narrowing: result.data is inferred as never due to complex union types\n // We use unknown to bypass this and then validate with our type guard\n const responseData: unknown = result.data;\n if (responseData && isSearchableResourceArray<T>(responseData)) {\n return responseData;\n }\n return [];\n },\n });\n\n return (\n <div className=\"group form-field\" data-invalid={isInvalid ? '' : undefined}>\n <FormField {...{ label, description, errorMessage, requiredIndicator, htmlFor: fieldId }}>\n <AriaSelect isInvalid={isInvalid}>\n <PopoverTrigger\n onOpenChange={o => {\n if (!o) {\n // searchInputRef.current?.focus();\n onBlur?.(value);\n }\n }}\n >\n <SelectTrigger id={fieldId} isDisabled={isDisabled} className={className ?? 'w-full'}>\n {renderLabel(value, data, emptyOption)}\n </SelectTrigger>\n <SelectPopover placement=\"bottom start\">\n <Autocomplete inputValue={search} onInputChange={_setSearch}>\n <SearchField className={'p-2'} autoFocus />\n {isFetching && (\n <div className=\"p-input\">\n <Loader className=\"mx-auto\" />\n </div>\n )}\n {!isFetching && !isError && (\n <Menu\n {...props}\n className={'max-h-48'}\n items={data}\n renderEmptyState={() => <div className=\"body-sm p-2\">No results found.</div>}\n >\n {item => (\n <MenuItem key={item[accessor]} id={item[accessor]}>\n {item.name}\n </MenuItem>\n )}\n </Menu>\n )}\n {isError && <div className=\"text-destructive p-icon body-sm\">{error.message}</div>}\n </Autocomplete>\n </SelectPopover>\n </PopoverTrigger>\n </AriaSelect>\n </FormField>\n </div>\n );\n}\n\n/**\n * Single-selection ID search input.\n *\n * Thin, typed wrapper around `BaseIdSearchInput` specialized for the very common single-ID case.\n * Adapts the internal selection events into `onChange(id?: string)` and renders the selected label.\n *\n * @template T - resource type (extends BaseSearchableResource)\n *\n * @param props - Inherits `BaseIdSearchInput` props but uses `string[]` value type.\n *\n * @example\n * <SingleIdSearchInput\n * label=\"Reporter\"\n * value={reporterId}\n * onChange={setReporterId}\n * />\n *\n */\nexport function SingleIdSearchInput<T extends BaseSearchableResource>({\n ...props\n}: Omit<\n React.ComponentProps<typeof BaseIdSearchInput<T, string | null>>,\n 'onSelectionChange' | 'selectionMode' | 'selectedKeys' | 'renderLabel'\n>) {\n const selectedKeys = props.value ? [props.value] : [];\n\n return (\n <BaseIdSearchInput\n selectedKeys={selectedKeys}\n onSelectionChange={e => {\n const val = Array.from(e).filter(v => typeof v === 'string')[0];\n props.onChange(val);\n }}\n renderLabel={(v, d, emptyOption) => {\n // If value is empty and emptyOption is set, show the empty label\n if (emptyOption && isEmptyValue(v)) {\n return getEmptyLabel(emptyOption);\n }\n return d?.find(di => di.id === v)?.name ?? '';\n }}\n selectionMode=\"single\"\n {...props}\n />\n );\n}\n\n/**\n * Multi-selection ID search input.\n *\n * Thin wrapper around `BaseIdSearchInput` for the multiple-ID (`string[]`) case.\n * Adapts internal selection events into `onChange(ids: string[])`.\n *\n * @template T - resource type (extends BaseSearchableResource)\n *\n * @param props - Inherits `BaseIdSearchInput` props but uses `string[]` value type.\n *\n * @example\n * <MultipleIdSearchInput\n * label=\"Reviewers\"\n * value={reviewerIds}\n * onChange={setReviewerIds}\n * />\n *\n * @remarks\n * - The `renderLabel` joins selected item names with commas for compact display.\n */\nexport function MultipleIdSearchInput<T extends BaseSearchableResource>({\n ...props\n}: Omit<\n React.ComponentProps<typeof BaseIdSearchInput<T, string[]>>,\n 'renderLabel' | 'onSelectionChange' | 'selectionMode' | 'selectedKeys'\n>) {\n const selectedKeys = props.value;\n\n return (\n <BaseIdSearchInput\n selectedKeys={selectedKeys}\n onSelectionChange={e => {\n const vals = Array.from(e).filter(v => typeof v === 'string');\n props.onChange(vals.length > 0 ? vals : []);\n }}\n selectionMode=\"multiple\"\n renderLabel={(v, d, emptyOption) => {\n // If array is empty and emptyOption is set, show the empty label\n if (emptyOption && (!v || v.length === 0)) {\n return getEmptyLabel(emptyOption);\n }\n\n const values = v ?? [];\n const labels = values.map(vi => {\n return d?.find(di => di.id === vi)?.name ?? vi;\n });\n return labels.length > 0 ? labels.join(',') : '';\n }}\n {...props}\n />\n );\n}\n\n/**\n * Form-integrated single-select ID input (field wrapper).\n *\n * Integrates `SingleIdSearchInput` into the form system using `useFieldContext`.\n * - wires `value`, `onChange`, and `onBlur`\n * - disables the control while the form is submitting\n * - surfaces field-level error messages\n *\n * @example\n * <TfSingleIdSearchInput name=\"ownerId\" label=\"Owner\" />\n \n */\nexport function TfSingleIdSearchInput({\n isDisabled,\n ...props\n}: Omit<React.ComponentProps<typeof SingleIdSearchInput>, 'value' | 'onChange' | 'onBlur'>) {\n const field = useFieldContext<string | null>({ disabled: isDisabled });\n return (\n <SingleIdSearchInput\n requiredIndicator={field.isRequired}\n isDisabled={isDisabled || field.isSubmitting}\n value={field.state.value}\n onBlur={_ => field.handleBlur()}\n onChange={e => field.handleChange(e)}\n isInvalid={!!getFieldErrorMessage(field)}\n errorMessage={getFieldErrorMessage(field)}\n {...props}\n />\n );\n}\n\n/**\n * Form-integrated multi-select ID input (field wrapper).\n *\n * Integrates `MultipleIdSearchInput` into the form system using `useFieldContext`.\n * - wires `value`, `onChange`, and `onBlur`\n * - disables the control while the form is submitting\n * - surfaces field-level error messages\n *\n * @example\n * <TfMultipleIdSearchInput name=\"reviewerIds\" label=\"Reviewers\" />\n *\n */\nexport function TfMultipleIdSearchInput({\n isDisabled,\n ...props\n}: Omit<React.ComponentProps<typeof MultipleIdSearchInput>, 'value' | 'onChange'>) {\n const field = useFieldContext<string[]>({ disabled: isDisabled });\n return (\n <MultipleIdSearchInput\n requiredIndicator={field.isRequired}\n isDisabled={isDisabled || field.isSubmitting}\n value={field.state.value}\n onBlur={_ => field.handleBlur()}\n onChange={e => field.handleChange(e)}\n isInvalid={!!getFieldErrorMessage(field)}\n errorMessage={getFieldErrorMessage(field)}\n {...props}\n />\n );\n}\n"],"names":["isSearchableResourceArray","value","item","BaseIdSearchInput","label","description","errorMessage","requiredIndicator","isDisabled","isInvalid","onBlur","path","onChange","renderLabel","accessor","defaultParams","className","emptyOption","props","generatedId","useId","fieldId","client","useCtxClient","search","_setSearch","useState","data","isError","isFetching","error","useQuery","responseData","jsx","FormField","AriaSelect","jsxs","PopoverTrigger","o","SelectTrigger","SelectPopover","Autocomplete","SearchField","Loader","Menu","MenuItem","SingleIdSearchInput","selectedKeys","val","v","d","isEmptyValue","getEmptyLabel","di","MultipleIdSearchInput","vals","labels","vi","TfSingleIdSearchInput","field","useFieldContext","_","e","getFieldErrorMessage","TfMultipleIdSearchInput"],"mappings":"65BAkCA,SAASA,EAA4DC,EAA8B,CAC/F,OACI,MAAM,QAAQA,CAAK,GAAKA,EAAM,MAAMC,GAAQA,GAAQ,OAAO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,CAAK,EACvC,aAAcI,EAAqBJ,CAAK,EACvC,GAAGzC,CAAA,CAAA,CAGhB"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{jsx as r}from"react/jsx-runtime";import{createContext as s,use as d}from"react";import{toTitleCase as i}from"./string.js";import"lodash-es";const
|
|
1
|
+
import{jsx as r}from"react/jsx-runtime";import{createContext as s,use as d}from"react";import{toTitleCase as i}from"./string.js";import"lodash-es";const o={"product.displayName":"Product",planId:"Plan",tenantDatabaseClusterId:"Tenant Database Cluster",product_displayName:"Product"},g=["access-token","account","activation","activation-log","admin-role","audit-log","automated-email","automated-email-event-log","card","entitlement-set","feature-flag","feature","invoice","license","license-template","maintenance-policy","organization","plan","product","product-version","profile","release","release-channel","release-file","release-platform","role","role-claim","saml-configuration","segment","sending-domain","tag","trial","trial-policy","user","user-group","webhook","webhook-event-log","webhook-event","reseller","oidc-configuration","tenant-database-cluster"],a={id:"ID",createdAt:"Creation Date",scopes:"Permissions",updatedAt:"Last Updated",expiresAt:"Expiration Date",lastSeenAt:"Last Seen",os:"OS",osVersion:"OS Version",key:"License Key",vmName:"VM Name",container:"Container",allowedIpRange:"Allowed IP Range",allowedIpRanges:"Allowed IP Ranges",allowedIpAddresses:"Allowed IP Addresses",disallowedIpAddresses:"Disallowed IP Addresses",allowVmActivation:"Allow VM Activation",disableGeoLocation:"Disable Geolocation","user.id":"User ID",userId:"User",productId:"Product",downloads:"Total Downloads",claims:"Permissions",googleSsoEnabled:"Google Login Enabled",lastAttemptedAt:"Last Attempt Date",url:"URL","trialPolicy.name":"Trial Policy Name","licensePolicy.name":"License Template Name",licensePolicy:"License Template",eventLog:"Audit Log",cc:"CC Recepients",bcc:"BCC Recepients",ipAddress:"IP Address",resellerId:"Reseller",productVersionId:"Product Version",releaseId:"Release",maintenancePolicyId:"Maintenance Policy",webhookId:"Webhook",automatedEmailId:"Automated Email","location.countryName":"Country","location.ipAddress":"IP Address","location.countryCode":"Country",organizationId:"Organization","address.country":"Country","address.addressLine1":"Address Line 1","address.addressLine2":"Address Line 2",responseStatusCode:"HTTP Status Code",resourceId:"Resource ID",Sso:"SAML SSO 2.0","reseller.name":"Reseller",sendingDomain:"Email Sending Domain"};function l(e,t){return t!=="admin-portal"&&e in o?o[e]:e in a?a[e]:i(e)}const n=s("admin-portal");function P({projectName:e,children:t}){return r(n.Provider,{value:e,children:t})}function c(){return d(n)}function I(){const e=c();return t=>l(t,e)}function S(e){const t=e.expiresAt&&new Date(e.expiresAt)<new Date;switch(!0){case(e.revoked&&e.suspended&&t):return"Revoked, Suspended, Expired";case(e.revoked&&e.suspended):return"Revoked, Suspended";case(e.revoked&&t):return"Revoked, Expired";case(e.suspended&&t):return"Suspended, Expired";case e.suspended:return"Suspended";case e.revoked:return"Revoked";case t:return"Expired";default:return"Active"}}const v={windows:"Windows",macos:"macOS",linux:"Linux",ios:"iOS",android:"Android"};export{v as ALL_OS,P as ProjectProvider,g as RESOURCE_NAMES,S as getLicenseStatus,c as useProjectName,I as useResourceFormatter};
|
|
2
2
|
//# sourceMappingURL=resources.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resources.js","sources":["../../lib/utilities/resources.tsx"],"sourcesContent":["import type { components, operations } from '@cryptlex/web-api-types/develop';\nimport { createContext, use } from 'react';\nimport { toTitleCase } from './string';\n\nexport type ApiSchema<T extends keyof components['schemas']> = components['schemas'][T];\nexport type ApiResponseBody<T extends keyof operations> = operations[T] extends {\n responses: { 200: { content: { 'application/json': infer R } } };\n}\n ? R extends Array<infer U>\n ? U\n : R\n : never;\nexport type ApiQuery<T extends keyof operations> = NonNullable<operations[T]['parameters']['query']>;\nexport type ApiPathParameters<T extends keyof operations> = operations[T]['parameters']['path'];\nexport type ApiFilter<T extends keyof operations> = Omit<ApiQuery<T>, 'page' | 'limit' | 'sort' | 'search'>;\nexport type ApiFilters<T extends keyof operations> = NonNullable<ApiFilter<T>>;\nexport type CtxPortals = 'customer-portal' | 'system-portal' | 'reseller-portal' | 'admin-portal';\n// Display names specific to customer and reseller portal\nconst OTHER_PORTALS_DISPLAY_NAME: Record<string, string> = {\n 'product.displayName': 'Product',\n // TanStack Table converts . -> _ TODO\n product_displayName: 'Product',\n};\n\n// TODO, delegate to openapi.json\n// TODO, this drifts quite a lot from the API, should be updated\n/** Resource Name should ALWAYS be in singular form */\nexport const RESOURCE_NAMES = [\n 'access-token',\n 'account',\n 'activation',\n 'activation-log',\n 'admin-role',\n 'audit-log',\n 'automated-email',\n 'automated-email-event-log',\n 'card',\n 'entitlement-set',\n 'feature-flag',\n 'feature',\n 'invoice',\n 'license',\n 'license-template',\n 'maintenance-policy',\n 'organization',\n 'plan',\n 'product',\n 'product-version',\n 'profile',\n 'release',\n 'release-channel',\n 'release-file',\n 'release-platform',\n 'role',\n 'role-claim',\n 'saml-configuration',\n 'segment',\n 'sending-domain',\n 'tag',\n 'trial',\n 'trial-policy',\n 'user',\n 'user-group',\n 'webhook',\n 'webhook-event-log',\n 'webhook-event',\n 'reseller',\n 'oidc-configuration',\n 'tenant-database-cluster',\n] as const;\nexport type CtxResourceName = (typeof RESOURCE_NAMES)[number];\n\n// TODO, use OpenAPI spec for resource definitions\n\nconst RESOURCE_DISPLAY_NAMES: Record<string, string> = {\n id: 'ID',\n createdAt: 'Creation Date',\n scopes: 'Permissions',\n updatedAt: 'Last Updated',\n expiresAt: 'Expiration Date',\n lastSeenAt: 'Last Seen',\n os: 'OS',\n osVersion: 'OS Version',\n key: 'License Key',\n vmName: 'VM Name',\n container: 'Container',\n allowedIpRange: 'Allowed IP Range',\n allowedIpRanges: 'Allowed IP Ranges',\n allowedIpAddresses: 'Allowed IP Addresses',\n disallowedIpAddresses: 'Disallowed IP Addresses',\n allowVmActivation: 'Allow VM Activation',\n disableGeoLocation: 'Disable Geolocation',\n 'user.id': 'User ID',\n userId: 'User',\n productId: 'Product',\n downloads: 'Total Downloads',\n claims: 'Permissions',\n googleSsoEnabled: 'Google Login Enabled',\n lastAttemptedAt: 'Last Attempt Date',\n url: 'URL',\n 'trialPolicy.name': 'Trial Policy Name',\n 'licensePolicy.name': 'License Template Name',\n licensePolicy: 'License Template',\n eventLog: 'Audit Log',\n cc: 'CC Recepients',\n bcc: 'BCC Recepients',\n ipAddress: 'IP Address',\n resellerId: 'Reseller',\n productVersionId: 'Product Version',\n releaseId: 'Release',\n maintenancePolicyId: 'Maintenance Policy',\n webhookId: 'Webhook',\n automatedEmailId: 'Automated Email',\n 'location.countryName': 'Country',\n 'location.ipAddress': 'IP Address',\n 'location.countryCode': 'Country',\n organizationId: 'Organization',\n 'address.country': 'Country',\n 'address.addressLine1': 'Address Line 1',\n 'address.addressLine2': 'Address Line 2',\n responseStatusCode: 'HTTP Status Code',\n resourceId: 'Resource ID',\n Sso: 'SAML SSO 2.0',\n 'reseller.name': 'Reseller',\n sendingDomain: 'Email Sending Domain',\n};\n\nfunction getResourceDisplayName(resourceName: string, portal: CtxPortals) {\n if (portal !== 'admin-portal' && resourceName in OTHER_PORTALS_DISPLAY_NAME) {\n return OTHER_PORTALS_DISPLAY_NAME[resourceName];\n } else if (resourceName in RESOURCE_DISPLAY_NAMES) {\n return RESOURCE_DISPLAY_NAMES[resourceName];\n } else {\n return toTitleCase(resourceName);\n }\n}\n\nconst ProjectContext = createContext<CtxPortals>('admin-portal');\n\nexport function ProjectProvider({ projectName, children }: { projectName: CtxPortals; children: React.ReactNode }) {\n return <ProjectContext.Provider value={projectName}>{children}</ProjectContext.Provider>;\n}\n\nexport function useProjectName(): CtxPortals {\n const projectName = use(ProjectContext);\n return projectName;\n}\n\nexport function useResourceFormatter(): (resourceName: string) => string {\n const portal = useProjectName();\n return (resourceName: string) => getResourceDisplayName(resourceName, portal);\n}\n\n/**\n * Format multiple license parameters (expired, suspended, revoked) into a single status\n */\nexport function getLicenseStatus(license: any): string {\n const licenseExpired = license.expiresAt && new Date(license.expiresAt) < new Date();\n // Status Column\n switch (true) {\n case license.revoked && license.suspended && licenseExpired:\n return 'Revoked, Suspended, Expired';\n case license.revoked && license.suspended:\n return 'Revoked, Suspended';\n case license.revoked && licenseExpired:\n return 'Revoked, Expired';\n case license.suspended && licenseExpired:\n return 'Suspended, Expired';\n case license.suspended:\n return 'Suspended';\n case license.revoked:\n return 'Revoked';\n case licenseExpired:\n return 'Expired';\n default:\n return 'Active';\n }\n}\ntype OsType = ApiSchema<'ActivationCreateRequestModel'>['os'];\nexport const ALL_OS: Record<OsType, string> = {\n windows: 'Windows',\n macos: 'macOS',\n linux: 'Linux',\n ios: 'iOS',\n android: 'Android',\n};\n"],"names":["OTHER_PORTALS_DISPLAY_NAME","RESOURCE_NAMES","RESOURCE_DISPLAY_NAMES","getResourceDisplayName","resourceName","portal","toTitleCase","ProjectContext","createContext","ProjectProvider","projectName","children","useProjectName","use","useResourceFormatter","getLicenseStatus","license","licenseExpired","ALL_OS"],"mappings":"mJAkBA,MAAMA,EAAqD,CACvD,sBAAuB,UAEvB,oBAAqB,SACzB,EAKaC,EAAiB,CAC1B,eACA,UACA,aACA,iBACA,aACA,YACA,kBACA,4BACA,OACA,kBACA,eACA,UACA,UACA,UACA,mBACA,qBACA,eACA,OACA,UACA,kBACA,UACA,UACA,kBACA,eACA,mBACA,OACA,aACA,qBACA,UACA,iBACA,MACA,QACA,eACA,OACA,aACA,UACA,oBACA,gBACA,WACA,qBACA,yBACJ,EAKMC,EAAiD,CACnD,GAAI,KACJ,UAAW,gBACX,OAAQ,cACR,UAAW,eACX,UAAW,kBACX,WAAY,YACZ,GAAI,KACJ,UAAW,aACX,IAAK,cACL,OAAQ,UACR,UAAW,YACX,eAAgB,mBAChB,gBAAiB,oBACjB,mBAAoB,uBACpB,sBAAuB,0BACvB,kBAAmB,sBACnB,mBAAoB,sBACpB,UAAW,UACX,OAAQ,OACR,UAAW,UACX,UAAW,kBACX,OAAQ,cACR,iBAAkB,uBAClB,gBAAiB,oBACjB,IAAK,MACL,mBAAoB,oBACpB,qBAAsB,wBACtB,cAAe,mBACf,SAAU,YACV,GAAI,gBACJ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ACb"}
|
|
1
|
+
{"version":3,"file":"resources.js","sources":["../../lib/utilities/resources.tsx"],"sourcesContent":["import type { components, operations } from '@cryptlex/web-api-types/develop';\nimport { createContext, use } from 'react';\nimport { toTitleCase } from './string';\n\nexport type ApiSchema<T extends keyof components['schemas']> = components['schemas'][T];\nexport type ApiResponseBody<T extends keyof operations> = operations[T] extends {\n responses: { 200: { content: { 'application/json': infer R } } };\n}\n ? R extends Array<infer U>\n ? U\n : R\n : never;\nexport type ApiQuery<T extends keyof operations> = NonNullable<operations[T]['parameters']['query']>;\nexport type ApiPathParameters<T extends keyof operations> = operations[T]['parameters']['path'];\nexport type ApiFilter<T extends keyof operations> = Omit<ApiQuery<T>, 'page' | 'limit' | 'sort' | 'search'>;\nexport type ApiFilters<T extends keyof operations> = NonNullable<ApiFilter<T>>;\nexport type CtxPortals = 'customer-portal' | 'system-portal' | 'reseller-portal' | 'admin-portal';\n// Display names specific to customer and reseller portal\nconst OTHER_PORTALS_DISPLAY_NAME: Record<string, string> = {\n 'product.displayName': 'Product',\n // TanStack Table converts . -> _ TODO\n planId: 'Plan',\n tenantDatabaseClusterId: 'Tenant Database Cluster',\n product_displayName: 'Product',\n};\n\n// TODO, delegate to openapi.json\n// TODO, this drifts quite a lot from the API, should be updated\n/** Resource Name should ALWAYS be in singular form */\nexport const RESOURCE_NAMES = [\n 'access-token',\n 'account',\n 'activation',\n 'activation-log',\n 'admin-role',\n 'audit-log',\n 'automated-email',\n 'automated-email-event-log',\n 'card',\n 'entitlement-set',\n 'feature-flag',\n 'feature',\n 'invoice',\n 'license',\n 'license-template',\n 'maintenance-policy',\n 'organization',\n 'plan',\n 'product',\n 'product-version',\n 'profile',\n 'release',\n 'release-channel',\n 'release-file',\n 'release-platform',\n 'role',\n 'role-claim',\n 'saml-configuration',\n 'segment',\n 'sending-domain',\n 'tag',\n 'trial',\n 'trial-policy',\n 'user',\n 'user-group',\n 'webhook',\n 'webhook-event-log',\n 'webhook-event',\n 'reseller',\n 'oidc-configuration',\n 'tenant-database-cluster',\n] as const;\nexport type CtxResourceName = (typeof RESOURCE_NAMES)[number];\n\n// TODO, use OpenAPI spec for resource definitions\n\nconst RESOURCE_DISPLAY_NAMES: Record<string, string> = {\n id: 'ID',\n createdAt: 'Creation Date',\n scopes: 'Permissions',\n updatedAt: 'Last Updated',\n expiresAt: 'Expiration Date',\n lastSeenAt: 'Last Seen',\n os: 'OS',\n osVersion: 'OS Version',\n key: 'License Key',\n vmName: 'VM Name',\n container: 'Container',\n allowedIpRange: 'Allowed IP Range',\n allowedIpRanges: 'Allowed IP Ranges',\n allowedIpAddresses: 'Allowed IP Addresses',\n disallowedIpAddresses: 'Disallowed IP Addresses',\n allowVmActivation: 'Allow VM Activation',\n disableGeoLocation: 'Disable Geolocation',\n 'user.id': 'User ID',\n userId: 'User',\n productId: 'Product',\n downloads: 'Total Downloads',\n claims: 'Permissions',\n googleSsoEnabled: 'Google Login Enabled',\n lastAttemptedAt: 'Last Attempt Date',\n url: 'URL',\n 'trialPolicy.name': 'Trial Policy Name',\n 'licensePolicy.name': 'License Template Name',\n licensePolicy: 'License Template',\n eventLog: 'Audit Log',\n cc: 'CC Recepients',\n bcc: 'BCC Recepients',\n ipAddress: 'IP Address',\n resellerId: 'Reseller',\n productVersionId: 'Product Version',\n releaseId: 'Release',\n maintenancePolicyId: 'Maintenance Policy',\n webhookId: 'Webhook',\n automatedEmailId: 'Automated Email',\n 'location.countryName': 'Country',\n 'location.ipAddress': 'IP Address',\n 'location.countryCode': 'Country',\n organizationId: 'Organization',\n 'address.country': 'Country',\n 'address.addressLine1': 'Address Line 1',\n 'address.addressLine2': 'Address Line 2',\n responseStatusCode: 'HTTP Status Code',\n resourceId: 'Resource ID',\n Sso: 'SAML SSO 2.0',\n 'reseller.name': 'Reseller',\n sendingDomain: 'Email Sending Domain',\n};\n\nfunction getResourceDisplayName(resourceName: string, portal: CtxPortals) {\n if (portal !== 'admin-portal' && resourceName in OTHER_PORTALS_DISPLAY_NAME) {\n return OTHER_PORTALS_DISPLAY_NAME[resourceName];\n } else if (resourceName in RESOURCE_DISPLAY_NAMES) {\n return RESOURCE_DISPLAY_NAMES[resourceName];\n } else {\n return toTitleCase(resourceName);\n }\n}\n\nconst ProjectContext = createContext<CtxPortals>('admin-portal');\n\nexport function ProjectProvider({ projectName, children }: { projectName: CtxPortals; children: React.ReactNode }) {\n return <ProjectContext.Provider value={projectName}>{children}</ProjectContext.Provider>;\n}\n\nexport function useProjectName(): CtxPortals {\n const projectName = use(ProjectContext);\n return projectName;\n}\n\nexport function useResourceFormatter(): (resourceName: string) => string {\n const portal = useProjectName();\n return (resourceName: string) => getResourceDisplayName(resourceName, portal);\n}\n\n/**\n * Format multiple license parameters (expired, suspended, revoked) into a single status\n */\nexport function getLicenseStatus(license: any): string {\n const licenseExpired = license.expiresAt && new Date(license.expiresAt) < new Date();\n // Status Column\n switch (true) {\n case license.revoked && license.suspended && licenseExpired:\n return 'Revoked, Suspended, Expired';\n case license.revoked && license.suspended:\n return 'Revoked, Suspended';\n case license.revoked && licenseExpired:\n return 'Revoked, Expired';\n case license.suspended && licenseExpired:\n return 'Suspended, Expired';\n case license.suspended:\n return 'Suspended';\n case license.revoked:\n return 'Revoked';\n case licenseExpired:\n return 'Expired';\n default:\n return 'Active';\n }\n}\ntype OsType = ApiSchema<'ActivationCreateRequestModel'>['os'];\nexport const ALL_OS: Record<OsType, string> = {\n windows: 'Windows',\n macos: 'macOS',\n linux: 'Linux',\n ios: 'iOS',\n android: 'Android',\n};\n"],"names":["OTHER_PORTALS_DISPLAY_NAME","RESOURCE_NAMES","RESOURCE_DISPLAY_NAMES","getResourceDisplayName","resourceName","portal","toTitleCase","ProjectContext","createContext","ProjectProvider","projectName","children","useProjectName","use","useResourceFormatter","getLicenseStatus","license","licenseExpired","ALL_OS"],"mappings":"mJAkBA,MAAMA,EAAqD,CACvD,sBAAuB,UAEvB,OAAQ,OACR,wBAAyB,0BACzB,oBAAqB,SACzB,EAKaC,EAAiB,CAC1B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