Skip to content

Commit

Permalink
Chore: Convert useSidebarPaletteColor (#26065)
Browse files Browse the repository at this point in the history
<!-- This is a pull request template, you do not need to uncomment or remove the comments, they won't show up in the PR text. -->

<!-- Your Pull Request name should start with one of the following tags
  [NEW] For new features
  [IMPROVE] For an improvement (performance or little improvements) in existing features
  [FIX] For bug fixes that affect the end-user
  [BREAK] For pull requests including breaking changes
  Chore: For small tasks
  Doc: For documentation
-->

<!-- Checklist!!! If you're unsure about any of them, don't hesitate to ask. We're here to help! This is simply a reminder of what we are going to look for before merging your code. 
  - I have read the Contributing Guide - https://github.com/RocketChat/Rocket.Chat/blob/develop/.github/CONTRIBUTING.md#contributing-to-rocketchat doc
  - I have signed the CLA - https://cla-assistant.io/RocketChat/Rocket.Chat
  - Lint and unit tests pass locally with my changes
  - I have added tests that prove my fix is effective or that my feature works (if applicable)
  - I have added necessary documentation (if applicable)
  - Any dependent changes have been merged and published in downstream modules
-->

## Proposed changes (including videos or screenshots)
<!-- CHANGELOG -->
<!--
  Describe the big picture of your changes here to communicate to the maintainers why we should accept this pull request.
  If it fixes a bug or resolves a feature request, be sure to link to that issue below.
  This description will appear in the release notes if we accept the contribution.
-->

<!-- END CHANGELOG -->

## Issue(s)
<!-- Link the issues being closed by or related to this PR. For example, you can use #594 if this PR closes issue number 594 -->

## Steps to test or reproduce
<!-- Mention how you would reproduce the bug if not mentioned on the issue page already. Also mention which screens are going to have the changes if applicable -->

## Further comments
<!-- If this is a relatively large or complex change, kick off the discussion by explaining why you chose the solution you did and what alternatives you considered, etc... -->
  • Loading branch information
juliajforesti authored Jun 29, 2022
1 parent d00b35a commit 79de11a
Show file tree
Hide file tree
Showing 4 changed files with 39 additions and 63 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import colors from '@rocket.chat/fuselage-tokens/colors';
import colors from '@rocket.chat/fuselage-tokens/colors.json';
import { useSettings } from '@rocket.chat/ui-contexts';
import { CSSStyleRule } from 'cssom';
import { useLayoutEffect, useEffect, useMemo } from 'react';

import { isIE11 } from '../../lib/utils/isIE11';
Expand Down Expand Up @@ -37,7 +38,7 @@ const oldPallet = {
'color-white': '#ffffff',
};

const getStyleTag = () => {
const getStyleTag = (): HTMLStyleElement | HTMLElement => {
const style = document.getElementById('sidebar-style');
if (style) {
return style;
Expand All @@ -51,44 +52,7 @@ const getStyleTag = () => {
return newElement;
};

function lightenDarkenColor(col, amt) {
let usePound = false;

if (col[0] === '#') {
col = col.slice(1);
usePound = true;
}

const num = parseInt(col, 16);

let r = (num >> 16) + amt;

if (r > 255) {
r = 255;
} else if (r < 0) {
r = 0;
}

let b = ((num >> 8) & 0x00ff) + amt;

if (b > 255) {
b = 255;
} else if (b < 0) {
b = 0;
}

let g = (num & 0x0000ff) + amt;

if (g > 255) {
g = 255;
} else if (g < 0) {
g = 0;
}

return (usePound ? '#' : '') + (g | (b << 8) | (r << 16)).toString(16);
}

function h2r(hex = '', a) {
function h2r(hex: string, a: any): string {
const [hash, r, g, b] = hex.match(/#([0-f]{2})([0-f]{2})([0-f]{2})/i) || [];

return hash ? `rgba(${[r, g, b].map((value) => parseInt(value, 16)).join()}, ${a})` : hex;
Expand All @@ -97,8 +61,8 @@ function h2r(hex = '', a) {
const modifier = '.sidebar--custom-colors';

const query = { _id: /theme-color-rc/ };
const useTheme = () => {
const customColors = useSettings(query);
const useTheme = (): { [key: string]: string } => {
const customColors = useSettings(query) as { value: string; _id: string }[];
const result = useMemo(() => {
const n900 = customColors.find(({ _id }) => _id === 'theme-color-rc-color-primary-darkest');
const n800 = customColors.find(({ _id }) => _id === 'theme-color-rc-color-primary-dark');
Expand All @@ -116,10 +80,7 @@ const useTheme = () => {
...colors,
...(n900 && { n900: n900.value }),
...(n800 && { n800: n800.value }),
...((sibebarSurface || n800) && { sibebarSurface: sibebarSurface.value || n800.value }),
...((n700?.value[0] === '#' || n800?.value[0] === '#') && {
n700: n700?.value || lightenDarkenColor(n800.value, 10),
}),
...((sibebarSurface || n800) && { sibebarSurface: sibebarSurface?.value || n800?.value }),
...(n700 && { n700: n700.value }),
...(n600 && { n600: n600.value }),
...(n500 && { n500: n500.value }),
Expand All @@ -134,10 +95,12 @@ const useTheme = () => {
return result;
};

const toVar = (color) => (color && color[0] === '#' ? color : oldPallet[color] || `var(--${color})`);
const toVar = (color: string): string =>
color && color[0] === '#' ? color : oldPallet[color as keyof typeof oldPallet] || `var(--${color})`;

const getStyle = (
(selector) => (colors) =>
(selector) =>
(colors: { [key: string]: string }): string =>
`
${selector} {
--rcx-color-neutral-100: ${toVar(colors.n900)};
Expand Down Expand Up @@ -205,10 +168,10 @@ const getStyle = (
`
)(isIE11 ? ':root' : modifier);

const useSidebarPaletteColorIE11 = () => {
const useSidebarPaletteColorIE11 = (): void => {
const colors = useTheme();
useEffect(() => {
(async () => {
(async (): Promise<void> => {
const [{ default: cssVars }, CSSOM] = await Promise.all([import('css-vars-ponyfill'), import('cssom')]);
try {
getStyleTag().innerHTML = getStyle(colors);
Expand All @@ -218,24 +181,25 @@ const useSidebarPaletteColorIE11 = () => {
return;
}

const sidebarStyle = fuselageStyle.cloneNode(true);
const sidebarStyle = fuselageStyle.cloneNode(true) as HTMLElement;
sidebarStyle.setAttribute('id', 'sidebar-modifier');
document.head.appendChild(sidebarStyle);

const fuselageStyleRules = sidebarStyle.innerText
.match(/(.|\n)*?\{((.|\n)*?)\}(.|\n)*?/gi)
.filter((text) => /\.rcx-(sidebar|button|divider|input)/.test(text));
const fuselageStyleRules: string[] =
sidebarStyle.innerText
.match(/(.|\n)*?\{((.|\n)*?)\}(.|\n)*?/gi)
?.filter((text: string) => /\.rcx-(sidebar|button|divider|input)/.test(text)) || [];

const sheet = CSSOM.parse(
fuselageStyleRules
.join(' ')
.match(/((?!\}).|\n)*?\{|(.)*(color|background|shadow)(.)*|\}/gi)
.join(' '),
?.join(' ') || '',
);

const filterSelectors = (selector) => /rcx-(sidebar|button|divider|input)/.test(selector);
const insertSelector = (selector) =>
selector.replace(/^((html:not\(\.js-focus-visible\)|\.js-focus-visible)|\.)(.*)/, (match, group, g2, g3, offset, text) => {
const filterSelectors = (selector: string): boolean => /rcx-(sidebar|button|divider|input)/.test(selector);
const insertSelector = (selector: string): string =>
selector.replace(/^((html:not\(\.js-focus-visible\)|\.js-focus-visible)|\.)(.*)/, (match, group, _g2, g3, _offset, text) => {
if (group === '.') {
return `${modifier} ${text}`;
}
Expand All @@ -244,12 +208,15 @@ const useSidebarPaletteColorIE11 = () => {

sidebarStyle.innerHTML = sheet.cssRules
.map((rule) => {
if (!(rule instanceof CSSStyleRule)) {
return '';
}
rule.selectorText = rule.selectorText
.split(/,[ \n]/)
.filter(filterSelectors)
.map(insertSelector)
.join();
Array.from(rule.style.length)
Array.from({ length: rule.style.length })
.map((_, index) => rule.style[index])
.forEach((key, index) => !/color|background|shadow/.test(key) && rule.style.removeProperty(rule.style[index]));
return rule.cssText;
Expand All @@ -266,20 +233,20 @@ const useSidebarPaletteColorIE11 = () => {
console.log(error);
}
})();
return () => {
return (): void => {
getStyleTag().remove();
};
}, [colors]);
};

export const useSidebarPaletteColor = isIE11
? useSidebarPaletteColorIE11
: () => {
: (): void => {
const colors = useTheme();
useLayoutEffect(() => {
getStyleTag().innerHTML = getStyle(colors);

return () => {
return (): void => {
getStyleTag().innerHTML = '';
};
}, [colors]);
Expand Down
1 change: 1 addition & 0 deletions apps/meteor/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@
"@types/codemirror": "^5",
"@types/cookie-parser": "^1.4.2",
"@types/cors": "^2.8.5",
"@types/cssom": "^0.4.1",
"@types/dompurify": "^2.2.2",
"@types/ejson": "^2.2.0",
"@types/express": "^4.17.12",
Expand Down
2 changes: 1 addition & 1 deletion packages/ui-contexts/src/SettingsContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import type { SettingId, ISetting, GroupId, SectionName, TabId } from '@rocket.c
import { createContext } from 'react';

export type SettingsContextQuery = {
readonly _id?: SettingId[];
readonly _id?: SettingId[] | RegExp;
readonly group?: GroupId;
readonly section?: SectionName;
readonly tab?: TabId;
Expand Down
8 changes: 8 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -4075,6 +4075,7 @@ __metadata:
"@types/cookie": ^0.5.1
"@types/cookie-parser": ^1.4.2
"@types/cors": ^2.8.5
"@types/cssom": ^0.4.1
"@types/dompurify": ^2.2.2
"@types/ejson": ^2.2.0
"@types/express": ^4.17.12
Expand Down Expand Up @@ -7416,6 +7417,13 @@ __metadata:
languageName: node
linkType: hard

"@types/cssom@npm:^0.4.1":
version: 0.4.1
resolution: "@types/cssom@npm:0.4.1"
checksum: 0f44f5ff27f5dfadfb89c8bd00f8d588dc1aaa77ec05ffa3ab732929683aef842f55a6c52c9a75586a28987f009b45f6ea5f63dbc34660f6bb98650eea7f59e9
languageName: node
linkType: hard

"@types/dompurify@npm:^2.2.2":
version: 2.3.3
resolution: "@types/dompurify@npm:2.3.3"
Expand Down

0 comments on commit 79de11a

Please sign in to comment.