Categories
discuss

How to change vue/vuetify text field color conditionally

I’d like to conditionally apply a text color class in a text field. The class I want is red--text, like this:

:class="{ red--text: myModel.someBool }"

…but that results in a parse error. The problem is related to the class name, I think, because this works:

<v-text-field
  v-model="myModel" label="My Text"
  :class="{ red: myModel.someBool }"
></v-text-field>

…but I want to color the text, not the whole field.

Enclosing the desired class name in quotes 'red--text' prevents the parse error, but has no effect on the color.

Is there a way to get what I want?

Answer

Create a custom scoped style that applies itself to the input (since the class of v-text-field is applied to a containing div).

<style scoped>
  .my-text-style >>> .v-text-field__slot input {
    color: red
  }
</style>

This style name can contain hyphens, as long as it is quoted in the class expression. Bind the class with v-bind…

<v-text-field
  v-model="myModel" label="My Text"
  :class="{ 'my-text-style': myModel.someBool }"
></v-text-field>
Categories
discuss

Select is not working onClick IconComponent(dropdown-arrow) in react material ui

Below is my code snippet. I am facing an issue, when I click on IconComponent(dropdown-arrow), Select component is not opening.

<Select
  IconComponent={() => (
    <ExpandMore className="dropdown-arrow" />
  )}
  onChange={this.handleSelectUpdate.bind(this)}
  value={this.state.somestate}
  inputProps={{
    name: "someprops1",
    id: "someprops1"
  }}
  disabled={this.props.someprops1.length === 1}
  className="dropdown"
>
  >
  {_.map(this.props.someprops2, (item, id) => {
    return (
      <MenuItem value={item.somekey} key={id}>
        {item.somekey}
      </MenuItem>
    );
  })}
</Select>

Answer

In SelectInput.js(which Select leverages) the icon is rendered as follows:

<IconComponent className={classes.icon} />

With the manner that you were customizing the icon, you were ignoring the className property that SelectInput passes which prevented it from behaving correctly.

Below are a couple examples of customizing the icon. The first case uses the icon directly (IconComponent={ExpandMoreIcon}) without wrapping it in another function. The second case shows something closer to what you are trying to do (supporting specifying your own class on it). Though className is the only property that SelectInput tries to specify currently, I think you would be best off to pass through all the props:

const iconStyles = {
  selectIcon: {
    color: "green"
  }
};
const CustomExpandMore = withStyles(iconStyles)(
  ({ className, classes, ...rest }) => {
    return (
      <ExpandMoreIcon
        {...rest}
        className={classNames(className, classes.selectIcon)}
      />
    );
  }
);

Here’s the full example:

import React from "react";
import PropTypes from "prop-types";
import { withStyles } from "@material-ui/core/styles";
import InputLabel from "@material-ui/core/InputLabel";
import MenuItem from "@material-ui/core/MenuItem";
import FormControl from "@material-ui/core/FormControl";
import Select from "@material-ui/core/Select";
import ExpandMoreIcon from "@material-ui/icons/ExpandMore";
import clsx from "clsx";

const styles = (theme) => ({
  root: {
    display: "flex",
    flexWrap: "wrap"
  },
  formControl: {
    margin: theme.spacing.unit,
    minWidth: 120
  },
  selectEmpty: {
    marginTop: theme.spacing.unit * 2
  }
});
const iconStyles = {
  selectIcon: {
    color: "green"
  }
};
const CustomExpandMore = withStyles(iconStyles)(
  ({ className, classes, ...rest }) => {
    return (
      <ExpandMoreIcon
        {...rest}
        className={clsx(className, classes.selectIcon)}
      />
    );
  }
);

class SimpleSelect extends React.Component {
  state = {
    age: "",
    name: "hai"
  };

  handleChange = (event) => {
    this.setState({ [event.target.name]: event.target.value });
  };

  render() {
    const { classes } = this.props;

    return (
      <form className={classes.root} autoComplete="off">
        <FormControl className={classes.formControl}>
          <InputLabel htmlFor="age-simple">Age</InputLabel>
          <Select
            value={this.state.age}
            onChange={this.handleChange}
            inputProps={{
              name: "age",
              id: "age-simple"
            }}
            IconComponent={ExpandMoreIcon}
          >
            <MenuItem value="">
              <em>None</em>
            </MenuItem>
            <MenuItem value={10}>Ten</MenuItem>
            <MenuItem value={20}>Twenty</MenuItem>
            <MenuItem value={30}>Thirty</MenuItem>
          </Select>
        </FormControl>
        <FormControl className={classes.formControl}>
          <InputLabel htmlFor="age-simple">Age</InputLabel>
          <Select
            value={this.state.age}
            onChange={this.handleChange}
            inputProps={{
              name: "age",
              id: "age-simple"
            }}
            IconComponent={CustomExpandMore}
          >
            <MenuItem value="">
              <em>None</em>
            </MenuItem>
            <MenuItem value={10}>Ten</MenuItem>
            <MenuItem value={20}>Twenty</MenuItem>
            <MenuItem value={30}>Thirty</MenuItem>
          </Select>
        </FormControl>
      </form>
    );
  }
}

SimpleSelect.propTypes = {
  classes: PropTypes.object.isRequired
};

export default withStyles(styles)(SimpleSelect);

Edit Select custom icon

Here is the styling that Material-UI adds to the icon (found in NativeSelect.js which exports its styles so that Select.js can reuse them):

  icon: {
    // We use a position absolute over a flexbox in order to forward the pointer events
    // to the input and to support wrapping tags..
    position: 'absolute',
    right: 0,
    top: 'calc(50% - 12px)', // Center vertically
    pointerEvents: 'none', // Don't block pointer events on the select under the icon.
    color: theme.palette.action.active,
    '&$disabled': {
      color: theme.palette.action.disabled,
    },
  },
  /* Styles applied to the icon component if the popup is open. */
  iconOpen: {
    transform: 'rotate(180deg)',
  },
  /* Styles applied to the icon component if `variant="filled"`. */
  iconFilled: {
    right: 7,
  },
  /* Styles applied to the icon component if `variant="outlined"`. */
  iconOutlined: {
    right: 7,
  },

The absolute positioning keeps the icon within the clickable area of the Select. Without the absolute positioning, the icon will cause the different elements making up the Select to shift. Clicking in the place where the icon should be continues to work, but the way elements get shifted causes the overall layout of the Select to no longer make sense.

Categories
discuss

Refresh the backstack Activities after Night Mode has changed

I have seen a lot of questions and answers about recreating the current activity after changing the application’s Night Mode, but I have seen nothing on how to refresh the back stack Activities.

Say I have the backstack A > B > C. Activity C allows to change the night mode by calling AppCompatDelegate.setDefaultNightMode(). After this call, the current Activity (C), can refresh its theme with delegate.applyDayNight() or recreate().

However, when the user navigates back to B or A, the activities are still using the “old” mode, either day or night.

I tried to add something like that to the Activities:

override fun onResume() {
  super.onResume()
  delegate.applyDayNight()
}

But it does not seem to work.

I did multiple attempts to fix this:

One idea would be to recreate the backstack completely like suggested here or here, but since the backstack is not static, it’s not doable for me.

Another idea would be to have a class that handles the night mode change and provides a LiveData. Each Activity would listen to the LiveData for a mode change and call recreate(). However, we are stuck in an infinite loop because the Activity would recreate directly after starting to listen to the LiveData.

I find it hard to believe that I am the first one trying to refresh the Activities from the backstack after changing the night mode. What did I miss?

Thanks!

Answer

If you can detect when the day/night mode has changed, you can simply recreate an activity that is resumed when the back stack is popped.

In the following demo, there are three activities: A, B and C. A creates B and B creates C. Activity C can change the day/night mode. When C is popped, activity B sees the change in the day/night mode and calls reCreate() to recreate the activity. The same happens in activity A when activity B is popped.

The video below shows the effect. The light-colored background is the “day” mode and the dark is “night” mode.

I have created a GitHub project for this demo app. If this works as a solution, I can incorporate more text into the answer from the project.

enter image description here

Categories
discuss

Getting status code 0 angular HttpClient?

I have a strange problem using the angular 4’s HttpClient get method.

There are some custom error messages returned from the backend which I should handle and display to the user. However I get HttpErrorResponse in the console

HttpErrorResponse:
error: ProgressEvent {isTrusted: true, lengthComputable: false, loaded: 0, 
total: 0, type: "error", …}
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, headers: 
Map(0)}
message: "Http failure response for (unknown url): 0 Unknown Error"
name: "HttpErrorResponse"
ok: false
status: 0
statusText: "Unknown Error"
url: null

I read about the problem here but none of the solutions helped me. In the network tab of the browser I’m able to observe the real response from the server:

"{"StatusCode":400,
  "ExceptionMessage":"Internal Server Error",
  "Error":"Internal Server Error",
  "Errors": 
  [{"Code":"ValidationError","Message":"Custom message here."}]}"

The request seems like this in the network tab:

General: 
Request URL: https://asdfhost:port/5c77a77101ae8643aeeb61e9
Request Method: GET
Status Code: 400 
Remote Address: address
Referrer Policy: no-referrer-when-downgrade

Response Headers:
cache-control: no-cache
content-type: application/json
date: Thu, 28 Feb 2019 09:42:22 GMT
expires: -1
pragma: no-cache
server: Kestrel
status: 400

Request Headers: 
x-correlation-id: 6if123
Provisional headers are shown
Accept: application/json, text/plain, */*
Authorization: Bearer asdfasdftoken
Origin: http://origin
Referer: http://origin/somewhere
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 
(KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36

Is there a chance the custom errors to break the xhr request ? Any help will be highly appreciated. 🙂

Answer

Indeed it was a CORS problem. When an error occurred the back-end didn’t set the Allow Origin header.

Categories
discuss

What are the advantages and disadvantages of connecting Puppeteer over pipe instead of a websocket

Puppeteer supports connection to the browser either using a websocket (default) or using a pipe.

puppeteer.launch({ pipe: true });

What are the advantages of either of those approaches? Why would I choose one over the other? What are their disadvantages?

Answer

pipes should be your default if you run everything (puppeteer and chromium) in the same server. They are even considering making that the default. The pro is that’s a private connection between puppeteer and chromium. You are not opening a WebSocket to “the world”. The con is that you can’t re-use the chromium instance with another puppeteer process.

I think you can infer the pros and cons of WebSockets from the previous paragraphs. You would use WebSocket if you need to share a chromium instance across many puppeteer processes or from a different computer.

There are no big differences in performance though.

Source: stackoverflow
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Privacy Policy, and Copyright Policy. Content is available under CC BY-SA 3.0 unless otherwise noted. The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 © No Copyrights, All Questions are retrived from public domain..