{"version":3,"file":"IconProvider.mjs","sources":["../../../src/components/Icon/IconProvider.tsx"],"sourcesContent":["import React, { createContext, Fragment, useContext, useMemo } from 'react';\nimport type { ReactNode } from 'react';\nimport { willRenderSlotContent } from './IconSlot';\nimport type { IconName } from '../../icons/spritemap';\nimport { assertEdsUsage } from '../../util/logging';\nimport type { IconOrContent } from '../../util/utility-types';\nimport type { Status } from '../../util/variant-types';\n\n/**\n * The roles a component fills with an icon it picks itself.\n *\n * These are not slots a consumer fills per instance. Each one has a single, well-defined\n * job, so the same role has to look the same everywhere it appears: every close button in\n * an app is the same glyph, whether it closes a `Modal`, an `InputChip`, or a\n * `PageNotification`.\n *\n * The four status names are the `Status` union, so a component holding a `Status` can\n * look its icon up directly.\n */\nexport type SemanticIconName =\n  | Status\n  | 'back'\n  | 'close'\n  | 'collapse'\n  | 'copy'\n  | 'expand'\n  | 'forward'\n  | 'menu'\n  | 'open-in-new';\n\n/**\n * A full set of semantic icons. Each role takes an EDS icon name or a node, on the same\n * terms as any other content slot.\n *\n * A string here cannot be narrowed to `IconName` by the type system: `IconOrContent` unions\n * it with `ReactNode`, and even excluding `ReactNode`'s own `string` member leaves\n * `Iterable<ReactNode>`, which a string satisfies structurally. So a name that is not in the\n * spritemap type-checks, and `Icon` warns and renders nothing when it reaches one.\n */\nexport type SemanticIconMap = Record<SemanticIconName, IconOrContent>;\n\n/**\n * The glyph each status is drawn with.\n *\n * Kept as its own map, typed `Record<Status, IconName>`, so it has to name every member of\n * `Status` — no more and no fewer. Spread into the defaults below rather than written out\n * among them, because a status added to `Status` then fails to compile here until it is\n * given an icon, instead of quietly having none.\n */\nconst statusIcons: Record<Status, IconName> = {\n  informational: 'info-encircled-filled',\n  critical: 'critical-encircled-filled',\n  warning: 'warning-filled',\n  favorable: 'checkmark-encircled-filled',\n};\n\n/**\n * The icons EDS draws each semantic role with when no provider supplies its own.\n *\n * Exported so a consumer can build a partial override on top of the set EDS ships, and\n * so they can point at a single role's default without hard-coding the glyph. Read it,\n * spread it, index it — but it is frozen, because it is also the context's default value:\n * assigning to it would change what every tree without an override renders, from anywhere\n * in an app, which is the opposite of the consistency the provider is for. Build a new\n * object and hand it to an `IconProvider` instead.\n */\nexport const defaultSemanticIcons: Readonly<SemanticIconMap> = Object.freeze({\n  back: 'chevron-left',\n  close: 'close',\n  collapse: 'chevron-up',\n  copy: 'copy',\n  expand: 'chevron-down',\n  forward: 'chevron-right',\n  menu: 'menu',\n  'open-in-new': 'open-in-new',\n  ...statusIcons,\n});\n\n/**\n * Holds the semantic icon set in effect for the tree below it.\n *\n * Defaults to the full EDS set, so a component reading from it renders an icon whether or\n * not the app wrapped anything in an `IconProvider`.\n */\nconst IconProviderContext =\n  createContext<Readonly<SemanticIconMap>>(defaultSemanticIcons);\n\nexport type IconProviderProps = {\n  /**\n   * The tree the icon set applies to.\n   */\n  children?: ReactNode;\n  /**\n   * Semantic roles to draw with something other than the EDS default. Anything left out\n   * keeps the icon it inherits, so overriding one role does not mean restating the rest.\n   *\n   * Each value takes an EDS icon name or a node, matching the content slots elsewhere in\n   * the system.\n   *\n   * Every entry has to draw something. An icon name the spritemap does not have, or a value\n   * that renders nothing — `null`, `false`, `undefined`, `[]`, `<></>` — throws rather than\n   * quietly falling back, because a role resolving to nothing leaves whatever draws it in a\n   * state no component can make sense of, and inheriting instead would hide the mistake\n   * behind an icon nobody chose.\n   *\n   * So to leave a role alone, leave it out. Build a conditional override by adding the key\n   * only when it applies:\n   *\n   * ```tsx\n   * <IconProvider icons={{ ...(isCustom && { close: <Custom /> }) }}>\n   * ```\n   *\n   * There is deliberately no way to turn a role off here. A role says which glyph draws it,\n   * not whether the thing drawing it exists — and most of these sit in controls whose only\n   * content is the icon, so an empty one is a button a person can still click and no longer\n   * see. Whether such a control exists belongs to the component that owns it:\n   * `Modal`'s `hideCloseButton`, a notification's `onDismiss`, `CodeBlock`'s `copyStyle`.\n   *\n   * @example\n   * ```tsx\n   * <IconProvider icons={{ expand: 'chevron-down', close: <CustomGlyph /> }}>\n   *   <App />\n   * </IconProvider>\n   * ```\n   */\n  icons?: Partial<SemanticIconMap>;\n};\n\n/**\n * Whether a key in a consumer's map names a role this provider knows.\n *\n * An own-property check against the shipped defaults, which is the list of roles. Both\n * halves matter: a key that is not a role has to be dropped rather than merged, or an\n * untyped `{ toString: 'custom' }` would put `toString` on the map as an own property and\n * let it be read back as though it were a role.\n */\nfunction isSemanticIconName(key: string): key is SemanticIconName {\n  return Object.prototype.hasOwnProperty.call(defaultSemanticIcons, key);\n}\n\n/**\n * Describes a value that draws nothing, for an error a reader has to act on.\n *\n * By shape rather than by contents, and deliberately: an array holding `[null, false]` and a\n * fragment wrapping `{null}` both render nothing while plainly having children, so saying\n * either is empty would be wrong. What is true of all of them is that nothing comes out.\n *\n * `String(value)` will not do on its own either — an array and an element each stringify to\n * something a reader cannot act on.\n *\n * The only element that can reach here is a fragment: `hasSlotContent` counts every other\n * element as content, since what a component renders cannot be known from here.\n */\nfunction describeEmptyValue(icon: unknown): string {\n  if (Array.isArray(icon)) {\n    return 'an array that renders nothing';\n  }\n\n  if (React.isValidElement(icon)) {\n    return 'a fragment that renders nothing';\n  }\n\n  return `\\`${String(icon)}\\`, which renders nothing`;\n}\n\n/**\n * Whether a value is a collection this provider cannot vouch for.\n *\n * React renders any iterable of children, but checking what one holds means iterating it,\n * and that exhausts a generator — the check would consume the very content it was meant to\n * confirm. So the provider does not accept the shape at all: it promises every role draws\n * something, and it cannot promise that about a collection it is not allowed to look in.\n * An array can be looked in as often as you like.\n */\nfunction isUnverifiableCollection(icon: unknown): boolean {\n  return (\n    typeof icon === 'object' &&\n    icon !== null &&\n    Symbol.iterator in icon &&\n    !Array.isArray(icon)\n  );\n}\n\n/**\n * Whether a value is, or holds, a collection this provider cannot vouch for.\n *\n * Nesting one changes nothing about the problem. An array and a fragment are both judged by\n * what they hold, so a `Set` inside either is the thing that decides whether the role draws\n * anything — and it is exactly the thing that cannot be checked. `[new Set()]` and\n * `<>{items()}</>` used to pass, the array having a member and the fragment having children,\n * and then left an icon-only control blank and still clickable, which is what refusing the\n * shape at the top level was for.\n *\n * Walks the way `hasSlotContent` does, into arrays and through fragments, and stops at every\n * other element: what a component renders is its own business and cannot be known from here.\n */\nfunction holdsUnverifiableCollection(icon: unknown): boolean {\n  if (Array.isArray(icon)) {\n    return icon.some(holdsUnverifiableCollection);\n  }\n\n  if (React.isValidElement(icon) && icon.type === Fragment) {\n    return holdsUnverifiableCollection(\n      (icon.props as { children?: ReactNode }).children,\n    );\n  }\n\n  return isUnverifiableCollection(icon);\n}\n\n/**\n * ## Usage\n *\n * Swaps the icons EDS uses for the roles it fills on its own behalf: the chevron on a\n * `Menu.Button`, the close button in a `Modal`, the status icon on a `ToastNotification`,\n * and so on. Wrap the app once and every component below it picks the new glyph up.\n *\n * This is how those icons are set. The components that draw them do not take a per-instance\n * override, because a role that renders one glyph in one place and a different one two\n * screens over stops reading as that role at all.\n *\n * One exception: `FieldNote.icon` still wins over the `warning` and `critical` defaults for\n * a single note. That slot predates these roles and stays a content slot, so a note can\n * carry the status treatment and its own content at once. It warns when used without a\n * status, since an icon on a note with nothing to report reads as a status the note does\n * not have.\n *\n * Nesting merges: an inner provider only has to name the roles it changes, and inherits\n * the rest from the provider around it.\n *\n * ### Don'ts\n *\n * * Don't give a role a glyph that reads as a different role (a checkmark for `close`).\n * * Don't define the map inline in render if the tree below it is large. A new object\n *   every render re-renders every component reading from it; hoist it to a module\n *   constant instead.\n */\nexport const IconProvider = ({ children, icons }: IconProviderProps) => {\n  const inherited = useContext(IconProviderContext);\n\n  const unknownRoles = Object.keys(icons ?? {}).filter(\n    (key) => !isSemanticIconName(key),\n  );\n\n  // A misspelled role used to do nothing at all, in silence: the key was merged, no\n  // component ever asked for it, and the icon the consumer meant to change kept its\n  // default. Asserted out here rather than in the merge below, so it is not a side effect\n  // inside a `useMemo` that React may run more than once.\n  assertEdsUsage(\n    [unknownRoles.length > 0],\n    `IconProvider: ${unknownRoles\n      .map((role) => `\"${role}\"`)\n      .join(\n        ', ',\n      )} ${unknownRoles.length === 1 ? 'is not a semantic icon role' : 'are not semantic icon roles'}, so ${unknownRoles.length === 1 ? 'it does' : 'they do'} nothing. The roles are: ${Object.keys(\n      defaultSemanticIcons,\n    )\n      .sort()\n      .join(', ')}.`,\n  );\n\n  // Every entry has to draw something. A role that resolves to nothing leaves whatever\n  // draws it in a state no component can make sense of — most of these sit in controls\n  // whose only content is the icon, so an empty one is a button still clickable and no\n  // longer visible — and inheriting instead would hide the mistake behind an icon the\n  // consumer did not choose. Thrown rather than warned because it is a configuration error\n  // with one fix, and because a provider is set up once at a root: it surfaces on the first\n  // render in development long before it could reach anyone.\n  const rule =\n    'Every entry has to be an EDS icon name or content that renders; a role cannot be emptied here.';\n\n  for (const key of Object.keys(icons ?? {})) {\n    if (!isSemanticIconName(key)) {\n      continue;\n    }\n\n    const icon = icons?.[key];\n\n    if (holdsUnverifiableCollection(icon)) {\n      const where = isUnverifiableCollection(icon)\n        ? 'is set to an iterable that is not an array'\n        : 'holds an iterable that is not an array';\n\n      throw new Error(\n        `IconProvider: the \\`${key}\\` role ${where}. ${rule} Checking one means consuming it, which would leave nothing to render, so pass an array instead.`,\n      );\n    }\n\n    if (!willRenderSlotContent(icon)) {\n      const fault =\n        typeof icon === 'string'\n          ? `is set to \"${icon}\", which is not an EDS icon name`\n          : `is set to ${describeEmptyValue(icon)}`;\n\n      throw new Error(\n        `IconProvider: the \\`${key}\\` role ${fault}. ${rule} To leave a role as it is, omit it rather than passing an empty value: \\`{...(isCustom && { ${key}: <Custom /> })}\\` rather than \\`{ ${key}: isCustom ? <Custom /> : null }\\`.`,\n      );\n    }\n  }\n\n  const value = useMemo(() => {\n    const merged = { ...inherited };\n\n    // Safe to take as given: anything that would not render threw above, and a key that is\n    // not a role was reported and is skipped here.\n    for (const key of Object.keys(icons ?? {})) {\n      if (isSemanticIconName(key)) {\n        merged[key] = icons?.[key];\n      }\n    }\n\n    return merged;\n  }, [inherited, icons]);\n\n  return (\n    <IconProviderContext.Provider value={value}>\n      {children}\n    </IconProviderContext.Provider>\n  );\n};\n\nIconProvider.displayName = 'IconProvider';\n\n/**\n * Reads the icon in effect for one semantic role.\n *\n * For EDS components' own use. Consumers change what this returns with `IconProvider`\n * rather than calling it themselves, so it is not exported from the package root.\n *\n * Takes `undefined` for the components whose role depends on runtime state and is\n * sometimes no role at all, so they can resolve the icon in one unconditional call\n * instead of reading a role they will not render.\n *\n * Anything it returns draws something. A value that would not render cannot be in the map:\n * `IconProvider` throws for one, and the shipped defaults are all real icons. So the two\n * ways to get `undefined` back are both about the role asked for, not the value found — no\n * role was asked for, or the name is not a role at all, which untyped code can reach and\n * which is reported here as a usage error.\n *\n * @param name the semantic role being drawn, or `undefined` to draw nothing\n * @returns the icon name or node to hand to `IconSlot`, or `undefined` when `name` is\n * `undefined` or names no role\n */\nexport function useSemanticIcon(\n  name: SemanticIconName | undefined,\n): IconOrContent {\n  const icons = useContext(IconProviderContext);\n\n  // An own-property check, because the map inherits from `Object.prototype`: a role name\n  // that is not one — reachable from untyped code, e.g. `Link icon=\"toString\"` — used to\n  // resolve to the inherited function, get handed to `IconSlot` as content, and reach React\n  // as a child it cannot render.\n  const isRole =\n    name !== undefined && Object.prototype.hasOwnProperty.call(icons, name);\n\n  assertEdsUsage(\n    [name !== undefined && !isRole],\n    `IconProvider: \"${String(name)}\" is not a semantic icon role, so nothing renders for it.`,\n  );\n\n  // No check on the value: `IconProvider` throws for an entry that would not render, and\n  // the defaults are all real icons, so anything reaching here draws something. Only the\n  // role name can be wrong at this point, which is what the assert above covers.\n  return isRole ? icons[name] : undefined;\n}\n"],"names":["React"],"mappings":";;;;AAyCA;;;;;;;AAOG;AACH,MAAM,WAAW,GAA6B;AAC5C,IAAA,aAAa,EAAE,uBAAuB;AACtC,IAAA,QAAQ,EAAE,2BAA2B;AACrC,IAAA,OAAO,EAAE,gBAAgB;AACzB,IAAA,SAAS,EAAE,4BAA4B;CACxC;AAED;;;;;;;;;AASG;AACI,M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