"Experience a refreshing twist on Material Design Color Utilities when paired with Material Web Components for surprising

I have been working on a project where I am utilizing the Material Design Color Utilities package to generate a dynamic color theme based on a primary color. However, I have encountered an issue where the generated colors are not matching my expectations.

Below is the snippet of my current code:

import { argbFromHex, hexFromArgb, TonalPalette, themeFromSourceColor, applyTheme, Theme } from "@material/material-color-utilities";

const baseColors = {
  primary: '#000000',
  secondary: '#FCE800',
  tertiary: '#00BFFF',
  error: '#F00F3E',
  neutral: '#6F7B80',
  neutralVariant: '#7B7768'
};

const createTheme = (): Theme => {
  const primaryArgb = argbFromHex(baseColors['primary']);
  const secondaryArgb = argbFromHex(baseColors['secondary']);
  const tertiaryArgb = argbFromHex(baseColors['tertiary']);
  const errorArgb = argbFromHex(baseColors['error']);
  const neutralArgb = argbFromHex(baseColors['neutral']);
  const neutralVariantArgb = argbFromHex(baseColors['neutralVariant']);

  const theme = themeFromSourceColor(primaryArgb);

  return {
    source: primaryArgb,
    schemes: theme.schemes,
    palettes: {
      primary: TonalPalette.fromInt(primaryArgb),
      secondary: TonalPalette.fromInt(secondaryArgb),
      tertiary: TonalPalette.fromInt(tertiaryArgb),
      neutral: TonalPalette.fromInt(neutralArgb),
      neutralVariant: TonalPalette.fromInt(neutralVariantArgb),
      error: TonalPalette.fromInt(errorArgb),
    },
    customColors: [],
  };
};
/*Overwrite mui system colors*/
const applyThemeVars = (root: HTMLElement, isDarkMode: boolean, theme: any) => {
  const style = root.style;
  const colors = isDarkMode ? theme.schemes.dark : theme.schemes.light;
  Object.entries(colors.props).forEach(([key, value]) => {
    const hexColor = hexFromArgb(value as number);
    style.setProperty(`--md-sys-color-${key}`, hexColor);
  });
};

const applyCustomTheme = (isDarkMode: boolean) => {
  const generatedTheme = createTheme();
  applyThemeVars(document.documentElement, isDarkMode, generatedTheme);
  applyTheme(generatedTheme, { target: document.documentElement, dark: isDarkMode });
};

export const ThemeHelper = () => {
  return {
    applyCustomTheme,
  };
};

const themeHelper = ThemeHelper();
export default themeHelper;

My challenge lies in using themeFromSourceColor where the generated primary color appears as dark violet (#984061) instead of black (#000000) as intended.

Packages: https://github.com/material-components/material-web#readme https://github.com/material-foundation/material-color-utilities

Question: Why does themeFromSourceColor produce a dark violet shade instead of black? How can I ensure that the generated primary color matches my specified color precisely?

Answer №1

Your question raises several important points

  • It is noted that you are utilizing the "source colour" (#000000) without a designated "primary color" for theme creation.
  • It is crucial to understand that it is not guaranteed that the primary color generated will precisely match your specified color, so expectations should be managed accordingly.

In response to your initial query:

  1. Following various calculations, the library establishes a TonalPalette based on the source color.
  2. The palette then selects the tone(50) color from light themes as the primary color.
  3. To delve deeper into this process, refer to the source code at https://github.com/material-foundation/material-color-utilities/blob/main/typescript/utils/theme_utils.ts#L77

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Deactivate certain days in Material UI calendar component within a React application

Currently, my DatePicker component in React js is utilizing material-ui v0.20.0. <Field name='appointmentDate' label="Select Date" component={this.renderDatePicker} /> renderDatePicker = ({ input, label, meta: { touched, error ...

A custom data structure that supports both individual properties and arrays of properties, ideally containing only primitive values

I need to create a custom type that is a partial of a generic type, but also allows an array as a property of the corresponding type. For example, if we have the following interface: interface DataModel { type: string; count: number; } The resolved ty ...

Clear form values in react-hook-form upon form closure

Featuring the given component: import { yupResolver } from '@hookform/resolvers/yup'; import { useForm } from 'react-hook-form'; import * as yup from 'yup'; import { useToggle } from '../shared/hooks'; import { Su ...

What is the correct way to implement strong typing for a reactive array consisting of interface Class objects in TypeScript?

My goal is to develop a dynamic array that can store data fetched from a database through an HTTP request using a SQL query. Since I lack direct access to the database, my only option is to submit a query to retrieve the required information. The retrieved ...

How do you eliminate row highlighting on the <TableRow> component within Material-UI's <Table> using ReactJS?

I am facing an issue with a table and row highlighting in my code. Even after clicking on a row, it remains highlighted. I attempted to use the <TableRow disableTouchRipple={true}> but it didn't work as expected. What can I do to remove the high ...

Time grid - powered by momentjs and typescript

https://i.sstatic.net/Xzggb.png Welcome! If you're looking to add a day picker in a calendar, keep reading for my solution. ...

Create an asynchronous method within an object-oriented programming (OOP) class

Presenting my Activity class. export class Activity { _name: string _goIn: boolean constructor(name: string) { this._name = name; this._goIn = false; } isGoIn() { return this._goIn; } setGoIn() { // instructions to asyn ...

Having trouble opening a JPEG file that was generated using the Writefile Api in Ionic-Cordova

Currently, I am using the writeFile API to create a JPEG image. The process is successful and the image is stored in the directory as expected. However, when I try to open the file manually from the directory, I encounter an error message saying "Oops! Cou ...

Exporting constants using abstract classes in TypeScript files

In my Typescript files, I've been exporting constant variables like this: export const VALIDATION = { AMOUNT_MAX_VALUE: 100_000_000, AMOUNT_MIN_VALUE: 0, DESCRIPTION_MAX_LENGTH: 50, }; My constant files only contain this one export without any ...

Categorize items based on their defined attributes using Typescript

[origin object array and expect object array ][1] origin object array: 0: amount: 100000000000000000000 feeTier: 0.3 price: 00000 priceDecimal: 0000 status: "unknown" tokenXAddr: "0x*********" tokenXSymbol: "USDC" tokenYAddr: ...

Invoke a function within the <img> tag to specify the source path

I have been attempting to achieve something similar to the following: <img id="icon" class="cercle icon" src="getIcon({{item.status}})" alt=""> This is my function: getIcon(status){ switch (status) { case 'Ongoing': ret ...

Import necessary styles into the shadow DOM

Embracing the concept of shadow dom styles encapsulation is exciting, but I wish to incorporate base styles into each shadow dom as well (reset, typography, etc). <head> <link rel="stylesheet" href="core.css"> ... </h ...

Disabling eslint does not prevent errors from occurring for the unicorn/filename-case rule

I have a file called payment-shipping.tsx and eslint is throwing an error Filename is not in camel case. Rename it to 'paymentShipping.tsx' unicorn/filename-case However, the file needs to be in kebab case since it's a next.js page that s ...

The Angular framework's structure is loaded in a combination of synchronous and asynchronous ways once the primeng tableModule

Encountered this error while trying to load the TableModule from primeng into my components module file and running 'npm run packagr': Maximum call stack size exceeded To address this, I switched my primeng version from primeng12 to primeng11.4. ...

How can I subscribe to nested JSON objects in Angular?

I am seeking advice on working with a nested JSON object. Within our server, there is an object located at "/dev/api/sportstypes/2" structured like this; { "NBA": { "link": "https://www.nba.com/", "ticketPrice": 50 }, "UEFA": { ...

The Angular2 application is experiencing technical difficulties

Hello, I am encountering an issue with my small Angular (2.1.1) application that consists of a module and a component. Everything was functioning correctly until this error occurred: error_handler.js:53 TypeError: jit_selectOrCreateRenderHostElement5 is n ...

When using TypeORM's findOneBy method, if the search result

In order for the entity to have both identifiers, I require it to possess the Id and the _id export class ScriptSequencesExecutionEntity { @PrimaryGeneratedColumn({ name: 'id' }) _id!: string; @ObjectIdColumn() id: number; @AutoMap() ...

Passing an object to createMuiTheme in Typescript and Material UI

Struggling with TypeScript and Material UI integration, I'm puzzled by the issue of passing an object to createMuiTheme. This code snippet works perfectly: const themeConfig = createMuiTheme({ palette: { primary: green, secondary: purple, ...

Guide on incorporating globalizejs into an Angular 2 project

Can anyone share a sample of integrating globalizejs library with Angular and how to use it? I'm currently working on an Angular 4 project using Angular-cli and devextreme. The information on utilizing globalizejs with Angular is not very clear in t ...

Sticky List Items Overlap in React with Material-UI

I'm trying to create a material-ui list item with sticky subheaders. I've managed to make the subheader stick, but when scrolling, it overlaps with the items: https://i.sstatic.net/kOgfZ.png Does anyone know how to prevent this from happening? ...