UNPKG

carbon-custom-elements

Version:

A Carbon Design System variant that's as easy to use as native HTML elements, with no framework tax, no framework silo.

1 lines 2.37 kB
{"version":3,"sources":["globals/directives/spread.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,EAAE,IAAI,EAA2B,MAAM,UAAU,CAAC;AAEzD,MAAM,WAAW,cAAc;IAC7B,QAAQ,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,CAAC;CACjC;AAQD;;;;;;GAMG;AACH,QAAA,MAAM,MAAM,0DA6BV,CAAC;AAEH,eAAe,MAAM,CAAC","file":"spread.d.ts","sourcesContent":["/**\n * @license\n *\n * Copyright IBM Corp. 2019\n *\n * This source code is licensed under the Apache-2.0 license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\nimport { Part, PropertyPart, directive } from 'lit-html';\n\nexport interface AttributesInfo {\n readonly [name: string]: string;\n}\n\n/**\n * Stores the ClassInfo object applied to a given AttributePart.\n * Used to unset existing values when a new ClassInfo object is applied.\n */\nconst attributesMapCache = new WeakMap();\n\n/**\n * A directive that applies attributes from a key-value pairs.\n * This must be used in the `...` name and must be the only part used in the attribute.\n * It applies the key-value pairs in the `attributesInfo` argument\n * and sets them as attribute name/value pairs.\n * @param classInfo The key-value pair to be set as the attribute name/value pairs.\n */\nconst spread = directive((attributesInfo: AttributesInfo) => (part: Part) => {\n // The first character of `...` is interpreted as one for `PropertyPart`\n if (!(part instanceof PropertyPart) || part.committer.name !== '..' || part.committer.parts.length > 1) {\n throw new Error('The `spread` directive must be used in with `...` name and must be the only part in the attribute.');\n }\n\n const { committer } = part;\n const { element } = committer;\n\n // Removes old attributes that are no longer there\n const oldAttributesInfo = attributesMapCache.get(part);\n if (oldAttributesInfo) {\n Object.keys(oldAttributesInfo).forEach(name => {\n if (!(name in attributesInfo)) {\n element.removeAttribute(name);\n }\n });\n }\n\n // Adds new attributes\n Object.keys(attributesInfo).forEach(name => {\n const value = attributesInfo[name];\n if ((!oldAttributesInfo || !Object.is(value, oldAttributesInfo[name])) && typeof value !== 'undefined') {\n element.setAttribute(name, value);\n }\n });\n\n // Updates the cache\n attributesMapCache.set(part, attributesInfo);\n});\n\nexport default spread;\n"]}