style.mjs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import { isShadowRoot } from "./aria.mjs";
  2. import { isClient } from "../browser.mjs";
  3. import { isNumber, isObject, isString, isStringNumber } from "../types.mjs";
  4. import { camelize } from "../strings.mjs";
  5. import { entriesOf, keysOf } from "../objects.mjs";
  6. import { debugWarn } from "../error.mjs";
  7. //#region ../../packages/utils/dom/style.ts
  8. const SCOPE = "utils/dom/style";
  9. const classNameToArray = (cls = "") => cls.split(" ").filter((item) => !!item.trim());
  10. const hasClass = (el, cls) => {
  11. if (!el || !cls) return false;
  12. if (cls.includes(" ")) throw new Error("className should not contain space.");
  13. return el.classList.contains(cls);
  14. };
  15. const addClass = (el, cls) => {
  16. if (!el || !cls.trim()) return;
  17. el.classList.add(...classNameToArray(cls));
  18. };
  19. const removeClass = (el, cls) => {
  20. if (!el || !cls.trim()) return;
  21. el.classList.remove(...classNameToArray(cls));
  22. };
  23. const getStyle = (element, styleName) => {
  24. if (!isClient || !element || !styleName || isShadowRoot(element)) return "";
  25. let key = camelize(styleName);
  26. if (key === "float") key = "cssFloat";
  27. try {
  28. const style = element.style[key];
  29. if (style) return style;
  30. const computed = document.defaultView?.getComputedStyle(element, "");
  31. return computed ? computed[key] : "";
  32. } catch {
  33. return element.style[key];
  34. }
  35. };
  36. const setStyle = (element, styleName, value) => {
  37. if (!element || !styleName) return;
  38. if (isObject(styleName)) entriesOf(styleName).forEach(([prop, value]) => setStyle(element, prop, value));
  39. else {
  40. const key = camelize(styleName);
  41. element.style[key] = value;
  42. }
  43. };
  44. const removeStyle = (element, style) => {
  45. if (!element || !style) return;
  46. if (isObject(style)) keysOf(style).forEach((prop) => removeStyle(element, prop));
  47. else setStyle(element, style, "");
  48. };
  49. function addUnit(value, defaultUnit = "px") {
  50. if (!value && value !== 0) return "";
  51. if (isNumber(value) || isStringNumber(value)) return `${value}${defaultUnit}`;
  52. else if (isString(value)) return value;
  53. debugWarn(SCOPE, "binding value must be a string or number");
  54. }
  55. //#endregion
  56. export { addClass, addUnit, classNameToArray, getStyle, hasClass, removeClass, removeStyle, setStyle };
  57. //# sourceMappingURL=style.mjs.map