UNPKG

@tldraw/editor

Version:

tldraw infinite canvas SDK (editor).

8 lines (7 loc) 2.78 kB
{ "version": 3, "sources": ["../../../src/lib/hooks/useSafeId.tsx"], "sourcesContent": ["import { assertExists } from '@tldraw/utils'\nimport { createContext, useContext, useId } from 'react'\n\n/**\n * The DOM requires that all IDs are unique. We often use e.g. shape IDs in the dom, but this isn't\n * safe: if tldraw is rendered twice, or an SVG export is taking place, the IDs will clash and the\n * browser will do weird things. This type is used to mark IDs that are unique and safe to use.\n *\n * Use {@link useUniqueSafeId} to generate a unique safe ID. Use {@link useSharedSafeId} to generate\n * the same ID across multiple components, but unique within a single tldraw/editor instance.\n *\n * @public\n */\nexport type SafeId = string & { __brand: 'SafeId' }\n\ndeclare module 'react' {\n\t// eslint-disable-next-line @typescript-eslint/no-unused-vars\n\tinterface HTMLProps<T> {\n\t\tid?: SafeId\n\t}\n\t// eslint-disable-next-line @typescript-eslint/no-unused-vars\n\tinterface SVGProps<T> {\n\t\tid?: SafeId\n\t}\n}\n\n/** @public */\nexport function suffixSafeId(id: SafeId, suffix: string): SafeId {\n\treturn sanitizeId(`${id}_${suffix}`) as SafeId\n}\n\n/**\n * React's useId hook returns a unique id for the component. However, it uses a colon in the id,\n * which is not valid for CSS selectors. This hook replaces the colon with an underscore.\n *\n * @public\n */\nexport function useUniqueSafeId(suffix?: string): SafeId {\n\treturn sanitizeId(`${useId()}${suffix ?? ''}`) as SafeId\n}\n\n/**\n * React's useId hook returns a unique id for the component. However, it uses a colon in the id,\n * which is not valid for CSS selectors. This hook replaces the colon with an underscore.\n *\n * @public\n */\nexport function useSharedSafeId(id: string): SafeId {\n\tconst idScope = assertExists(useContext(IdContext))\n\treturn sanitizeId(`${idScope}_${id}`) as SafeId\n}\n\n/** @public */\nexport function sanitizeId(id: string): string {\n\treturn id.replace(/:/g, '_')\n}\n\nconst IdContext = createContext<SafeId | null>(null)\nexport function IdProvider({ children }: { children: React.ReactNode }) {\n\tconst id = useUniqueSafeId()\n\treturn <IdContext.Provider value={id}>{children}</IdContext.Provider>\n}\n"], "mappings": "AA4DQ;AA5DR,SAAS,oBAAoB;AAC7B,SAAS,eAAe,YAAY,aAAa;AA0B1C,SAAS,aAAa,IAAY,QAAwB;AAChE,SAAO,WAAW,GAAG,EAAE,IAAI,MAAM,EAAE;AACpC;AAQO,SAAS,gBAAgB,QAAyB;AACxD,SAAO,WAAW,GAAG,MAAM,CAAC,GAAG,UAAU,EAAE,EAAE;AAC9C;AAQO,SAAS,gBAAgB,IAAoB;AACnD,QAAM,UAAU,aAAa,WAAW,SAAS,CAAC;AAClD,SAAO,WAAW,GAAG,OAAO,IAAI,EAAE,EAAE;AACrC;AAGO,SAAS,WAAW,IAAoB;AAC9C,SAAO,GAAG,QAAQ,MAAM,GAAG;AAC5B;AAEA,MAAM,YAAY,cAA6B,IAAI;AAC5C,SAAS,WAAW,EAAE,SAAS,GAAkC;AACvE,QAAM,KAAK,gBAAgB;AAC3B,SAAO,oBAAC,UAAU,UAAV,EAAmB,OAAO,IAAK,UAAS;AACjD;", "names": [] }