Skip to content

Commit

Permalink
Added style functions
Browse files Browse the repository at this point in the history
  • Loading branch information
djalmajr committed Apr 19, 2023
1 parent f245efe commit d9781a5
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 6 deletions.
2 changes: 1 addition & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,11 +54,11 @@ export * from './set';
export * from './size';
export * from './sleep';
export * from './sortBy';
export * from './styles';
export * from './template';
export * from './times';
export * from './toFormData';
export * from './typeOf';
export * from './uniq';
export * from './uniqBy';
export * from './uniqWith';
export * from './useSheet';
25 changes: 25 additions & 0 deletions src/styles.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
const isFrag = (n: Node) => {
return [Node.DOCUMENT_FRAGMENT_NODE, Node.DOCUMENT_NODE].includes(n.nodeType as never);
};

export function css(arr: string[], ...val: unknown[]) {
const sheet = new CSSStyleSheet();
sheet.replaceSync(val.reduce((r: string, v, i) => r + v + arr[i + 1], arr[0]) as string);
return sheet;
}

export function addStyle(
sheets: CSSStyleSheet | CSSStyleSheet[],
target: Document | ShadowRoot | HTMLElement = document,
) {
const styles = (<CSSStyleSheet[]>[]).concat(sheets);
while (!isFrag(target)) target = <Document>(target.parentNode || document);
styles.forEach((sheet) => {
const arr = (<Document>target).adoptedStyleSheets || [];
if (!arr.includes(sheet)) (<Document>target).adoptedStyleSheets = [...arr, sheet];
});
return () => {
const arr = (<Document>target).adoptedStyleSheets;
arr.forEach((sheet, idx, arr) => styles.includes(sheet) && arr.splice(idx, 1));
};
}
5 changes: 0 additions & 5 deletions src/useSheet.ts

This file was deleted.

0 comments on commit d9781a5

Please sign in to comment.