New version of context

(supersedes #1)
A proposal for a new version of context addressing existing limitations.
Rendered
Corresponding React PR: https://github.com/facebook/react/pull/11818
TODO:

[ ] Implementation notes
[ ] High-priority version of context, for animations. (May submit this separately.)
[ ] Add snippet showing how the displayName transform would work (https://github.com/reactjs/rfcs/pull/2#discussion_r155430494).
[ ] Add section about using narrow context types for maximum performance

@mjackson compareValues is a good idea. What's the default comparison in RB? ===?

@jaredpalmer What's the purpose of compareValues? I don't see one except to make mutation easier, which we're specifically aiming to discourage.

@jaredpalmer Yep. === is the default.
@acdlite There's a difference between discouraging mutability and making it impossible to use, IMO. Seems like exactly what defaultProps are for: by default we'd prefer you don't mutate stuff. But if you need to, just override compareValues. AFAICT immutability isn't actually enforced anywhere else in React. One use case is passing around location objects from the current history API, which is mutable.

@mjackson Mutation is not impossible with this proposal, it's just slightly less convenient. You can mutate one level down, just not the outermost container. Same as setState API.

Just giving an escape hatch to fallback to. I can see why this should be discouraged. However, mutation did come up in Formik the other day where I wanted to alter something within context if a certain declarative component existed in the subtree. More specifically, I wanted to change the implementation of formik.context.setFieldValue to support arrays in a more plugin-like manner:
const DeepFormik = (props) =>
 <Formik render={p =>
       <DeclarativePluginThatAltersCtx>
          {render(p)}
      </DeclarativePluginThatAltersCtx>
}/>

Historically we have tried to be as forgiving of mutation as possible. When we introduce async rendering (this proposal is designed with async in mind), we may need to be a bit more restrictive.
However, there are cases where React already privileges immutability. setState is one. Another is that we bail out on React elements if the props objects are strictly equal (===). Often that isn't the case, because props objects are created in the render method as part of JSX / React.createElement. But it is the case for components that render this.props.children. If the component re-renders, but the parent didn't, the child elements will bail out on the unchanged props.

We didn't use context that much and decided to use Redux instead.
To provide some inputs, I scanned one module. If it helps:

out of our 19 redux-connected components, we have 12 components that have only one value selected from the state, aka one selector. Mostly, isLogged, isLoading or isOnline. This proposal totally covers this case elegantly.
The remaining 7 components have an average of 4 selectors, to a max of 6. Reading the code, they all seem legitimate to me but we may have got it wrong: isLogged, isOnline, isLoading, getItemsPage, getTotalOfItems, getTheme.
The new context still sounds laborious in that case.

To be clear even if you use Redux, React Redux still uses context under the hood. The problem is it has to reimplement a tree-aware subscription mechanism. And that won’t work very well with React async mode. The proposal is both about making context friendlier for direct use and to make it better for libraries built on top (such as React Redux).

(Copied from previous PR).
I think a life-cycle hook in regards to context changes should be discussed. Relying on a child function for detecting this isn't exactly feasible for all situations. Perhaps another prop on the consumer?
<Consumer onChange={this.handleChange} />

@milesj brings up a good point. It took me a bit to parse his question but I think he's getting at this: what if you need the context value in any of the lifecycle hooks?
The problem with a render prop API is it makes that very difficult; I've run into this problem with other render prop-based APIs as well. Take AutoSizer which gives you the width/height. I needed to do something special with the width to figure out if I should render something or not, and that logic needs to be re-run when something else changes in a lifecycle, so I need the width there. Hope that makes sense, I can't remember the details of the problem.
Is the suggested pattern to pull out all the lifecycle code that needs to depend on it into a sub-component, and pass the value down as a prop to it? I think that works but seems a bit ceremonious.

@jlongster

Is the suggested pattern to pull out all the lifecycle code that needs to depend on it into a sub-component, and pass the value down as a prop to it? I think that works but seems a bit ceremonious.

Yes, this is the main problem with render prop APIs. I think this is mostly an educational challenge, though, because there's always the option to wrap it in an HOC:
function provide(Context) {
  return Component => {
    return function Provider({value, ...props}) {
      return (
        <Context.Provider value={value}>
          <Component {...props} />
        </Context.Provider>
      );
    }
  }
}

Usually my objection to wrapping in an HOC, versus using an HOC from the start, is it requires two extra components instead of one. But in this case, we want the extra Consumer component because they're faster to scan for.

Faster to scan in what case? Is that benefit enough to warrant a HOC in the default API?
(Thanks for explaining!)

Faster to scan for Consumer components. By adding another node into our internal tree, with a special type that is distinct from class components, we can quickly skip over non-consumer nodes.
To be clear, we could still implement it this way with an HOC-first API. I was just rebutting own devil's advocate point about adding extra nodes to the tree :D

I'm working on adding a high-level description of the implementation, will try to publish later today or tomorrow.

Will the new API support provider nesting like we can do it today? One use case example is nested theme.

@oliviertassinari Yes

@jlongster That's half of the question. But basically, I think the new context would need to hit these points:

New life-cycle event(s) for when the context changes (componentWillReceiveContext)? Passing the context prop to a component, in which that component needs to componentWillReceiveProps, adds another layer of abstraction and feels very tedious/contrived. My rudimentary solution above was simply a prop handler for when the context changes, instead of a new life-cycle method.
Checking the context value in existing life-cycle events. Theoretically this can be achieved by accessing the context prop.

It might be nice for React to ship an "official" HOC for consuming Context in the lifecycle, so that it can be treated differently in React DevTools (different color or etc). It's already inconvenient to dig through a ton of layers of components when using context-based APIs; needing to add another layer to get context in lifecycle methods will exacerbate the issue.

What's the suggested story for when a library consumes a context that is created and provided by an application? No particular usecase in mind yet, but previously this was possible via naming convention because there was a single context object.

@sompylasar I guess you'd pass the context consumer into the library?
import makeButton from "button-lib";

const Theme = React.createContext("light");

const Button = makeButton({ themeConsumer: Theme.Consumer });

<Theme.Provider value="dark">
  <Button />
</Theme.Provider>

@sompylasar , one idea that comes to mind is that the library could only accept props, and then create its own context as needed.
// In your app
<AppComponent>
  <SomeContext.Consumer>
    {val => (<SomeLib val={val})}
  </SomeContext>
</AppComponent>

// In SomeLib
export default SomeLib({ val }) {
  return (
    <LibContext.Provider val={val}>
      <InternalLibStuff/>
    <LibContext/>
  );
}

(Or you could pass it as a prop instead of the HOC approach, etc)

Sometimes, when I read a value that stored in context I also need handler(s) to update this value. E.g.:
getChildContext = () => ({
  locale: this.state.locale,
  updateLocale: this.updateLocale,
});

/* application */
<LocaleProvider>
  {({ locale, updateLocale }) => ... }
</LocaleProvider>

AFAIU from this RFC Consumer serves only value so handlers still must be passed all the way down?

@alexfedoseev Nothing stops you to pass handlers via context
<Provider value={{ locale, updateLocale }}>
  <App />
</Provider>

/* application */
<Consumer>
  {({ locale, updateLocale }) => ... }
</Consumer>

@suchipi @jmeas Right, thanks, these are both the options I thought about, too. I thought maybe there's something that we're missing.

@TrySound Right, my bad! I was confused by value name lol. It's probably more like interface or something. Thanks for clarification!

About the render-prop vs function-as-child discussion; I tried writing some nested consumers in both formats, then plop them in Prettier.
I think the function-as-child approach is preferable; it results in less indentation and less lines.

The above is actually why I would like to see an HOC interface that comes from React and uses the render prop interface under the hood - both of those seem very difficult to parse at a glance.
Also, I'm but a wee babe of a programmer but I imagine refugees from JQuery might have their PTSD triggered by having to deal with so many nested callbacks. Didn't Promises get added to JS almost entirely so people could stop seeing the Pyramid of Doom? (Kidding, you don't need to explain the value of promises to me. Probably.)

I wonder if making context easier to use will cause people to use it all over the place instead of prop passing because it’s less code. I wonder at which point, it ever, this actually becomes slower than prop passing and re-rendering everything.

@JNaftali you're absolutely right that both nested versions are not things of beauty, haha 😄
I would imagine some sort of consumer merging utility to make it a little prettier, such as:
const CompositeConsumer = mergeContextConsumers({
  consumer1Value: Consumer1,
  consumer2Value: Consumer2,
  consumer3Value: Consumer3
})

const App = () => (
  <CompositeConsumer>
    {({ consumer1Value, consumer2Value, consumer3Value }) =>

        {consumer1Value} {consumer2Value} {consumer3Value}

    }
  </CompositeConsumer>
)

@gaearon

I wonder if making context easier to use will cause people to use it all over the place instead of prop passing because it’s less code

One thing we've need to emphasize in the documentation is not to create overly broad context types. To keep the types simple. Like having separate ThemeContext and LocaleContext, instead of just one <GenericContext> that contains a record all your stuff.
By the way, this includes Redux. Having a single ReduxContext isn't ideal. It should be fine, maybe even faster than React Redux today. But for maximum performance, the best practice is going to be scoped providers. Generally, the narrower the scope, the faster we can update. It may take a while for library authors to catch up to this recommendation, but I'm not too worried about it.

I was thinking about how render props aren't that pleasant to read and write in JSX. I raised the possibility of changing JSX somehow to make it nicer.
@trueadm has a better idea: we don't use JSX.
render() {
    return ThemeContext.consume(theme => (

        {this.props.children}

    ));
}

I really like this. It also neatly avoids the named prop versus children prop debate. I'll add it to the proposal.

To be super clear it would work anywhere in the tree, not just at top level.

  {ThemeContext.consume(theme => (

      {this.props.children}

  ))}

I love @trueadm's idea because it allows us to solve our multicontext component issue quite elegantly:

  {compose(ThemeContext, AccessibilityContext).consume(
      (theme, accessibility) => (

            {this.props.children}

  ))}

Regarding the name: should it just be read maybe?

@baptistemanson FWIW you could build an API like that on top of JSX render props, too.

Personally I think it would be nice for there to be a consistent style across React projects for how to do render props. I hadn't even though about not using JSX, and I like it, but now I'm wondering if many other components that use render props should do that as well. I don't think it sidesteps the debate - it adds a 3rd style!
It adds some ambiguity - it's not as clear that it is injecting a new component into the tree, instead of other methods which usually don't (think array mapping).
But it's not a huge deal. I'd like to teach people about render functions as children, and that would be clearer to people who already use it, but I get why you'd want to avoid "blessing" a certain style.

Warning: I have a crazy idea...
Define context:
const theme = React.createContext('theme', {
  color: 'black',
  background: 'white',
})

(optional) You can define "derivations" out of context values (with memoization and so on possibly):
const color = theme.select(theme => theme.color)

Usage site (new syntax):
<Button color=${color} />

This will be transpiled to:
// React.createElement : (type, props, reactiveProps, ...children) => React.Element<props & reactiveProps>
React.createElement(Button, {}, {color: color})

The idea is to make React subscribe on values in reactiveProps bag and re-render corresponding components on changes.
I think the API React expects from reactiveProps-values could be generic enough not only for context but for other sources too.
New syntax is needed so that React don't need to traverse props to find reactive values, they are being put into a separate bag instead. Also it's kinda nice to have a visual cue for the places wherte subscriptions are going to appear.

@gaearon

I wonder if making context easier to use will cause people to use it all over the place instead of prop passing because it’s less code

I can already see people (ab)using this and making a app-level store that's just an object with a simple api like update() which will replace state managers and end up re-rendering the whole tree.
I agree with Andrew, that this (re-rendering of all consumers) should be emphasised in the documentation and a greater emmphasis placed on scoped providers - ala Redux provider scoped to specific reducer.

I don't mind the non-JSX render prop-ish thing a whole lot, but it would be nice to have some consistency on how this stuff works (rather than having 3 ways to do similar things). If we want the community to move to a regular function call then that could work but it makes the pattern more challenging to implement if you'd like to use lifecycle hooks.
So whether it's the children prop or the render prop, I don't mind as much, but I'd prefer to stick with JSX.

In similar maker I'd prefer to be consistent with existing portals api and split "tools" from components. In my opinion it would be nice to think how api will look without jsx since part of the community may prefer vanilla js syntax.

@TrySound I wrote React without JSX for years and found that children as a render function are automatically even better with vanilla js syntax. I don't think there's any problem there:
// With JSX

<Context.Consumer>
  {value =>
{value}
}
</Context.Consumer>;

// Without JSX

Context.Consumer({}, value => div({}, value));

In vein of "consistent with existing portals api" (React.createPortal):
const valueContext = React.createContext('value');

const AppRoot = () => {
  return React.createContextProvider(valueContext, <App />);
}

const NeedsValue = () => {
  return React.createContextConsumer(valueContext, (value) => (
{value}
));
}

Doesn't look as type-sound as the original valueContext.Provider / valueContext.Consumer approach because the types of provider and consumer elements aren't co-located.

@jlongster Not quite.
createElement(Context.Customer, null, value =>
  createElement('div', null, value))

I wouldn't like to use context wrapper of hyperscript. And again there's nice createPortal api.

I wasn't assuming hyperscript, but the standard createFactory provided by React which is how you use React without JSX. That verbosity is not the fault of this API but with the createElement API. (But we can respectfully move on, this is sidetracking into a different discussion!)

It adds some ambiguity - it's not as clear that it is injecting a new component into the tree, instead of other methods which usually don't (think array mapping).

Nested arrays are another example of something that creates a new node (fiber) internally without looking like it does. We omit those from the DevTools. We could do the same for context.

@acdlite Do we want to though? Seeing the consumer boundaries seems like valuable information, but maybe you expose that information in another special way? (I was devtools being talked about before and maybe that's already been discussed, haven't read everything)

maybe you expose that information in another special way?

Right, this is what I meant

Published a polyfill package for the proposed API: https://github.com/thejameskyle/create-react-context
Happy to transfer this repo/npm package to the React team and/or add collaborators.

@thejameskyle Great start but this suffers from the problem of not re-rendering if shouldComponentUpdate returns false at some point in the tree. You'll need to use a broadcast channel or an event emitter.

Can you chain providers? I have a case where we used the context to build a breadcrumb of sorts... Where at route points we have providers that also consume... and they append and forward the context down.
What about multiple values per provider?

@milesj Yeah, I just added an event emitter

I really like the idea of keeping the consumer (or "injector" if you want to phrase it in terms of dependency injection) out of JSX. There are already too many nested components when using context-based libraries, having yet another component would only make things worse.

Great proposal! Imho, Elegant, simple and good typing support. o

As I looked at this, it felt like render calls would get muddied-up if a component needed to consume multiple contexts.
I created a composing component to simplify the use of nested render props.
https://www.npmjs.com/package/react-context-composer

A few downsides to the Context.consume(value => <Child />) proposal in https://github.com/reactjs/rfcs/pull/2#issuecomment-350023244:

It looks like an imperative API that you could call from outside React. But it only works because it's rendered as a child.
If we want this thing to accept additional options (like allowDetached), we have to add additional arguments, or an options argument. Now it's like we're reinventing React.createElement.

On the other hand:

createPortal (also the experimental createCall / createReturn) is another API that already works like this. We should aim for consistency, one way or another.
We could warn if they are called outside render, with an helpful message explaining how they should be used.

Those downsides don't seem too problematic. I don't think most people would confuse trying to call Context.consume from outside React. Perhaps people new to React, but even so, that can be offset by good documentation and helpful warnings like you said, as well as community tutorials.
The benefit of consistency with other existing and experimental APIs definitely outweighs the downsides, IMO. And I don't think createContext being very similar to createElement would be a bad thing necessarily.

createPortal (also the experimental createCall / createReturn) is another API that already works like this. We should aim for consistency, one way or another.

I'd note that createPortal was made non-experimental at the last minute (since we realized it's more important as a migration path than it seemed). When I wrote the original unstable_createPortal I didn't give much thought to usability since I didn't intend it to be the final API. So I wouldn't care about consistency with it too much. (Same for the experimental ones.)
The original plan was to introduce a "proper" API when we figure out how to change portals to support SSR and cross-renderer jumps. At that point we might as well make it <React.Portal>.

Can reading the immediate context value outside render() be achieved? Something like this, similar to Redux store's getState():
// Artificial example.
class ThemeBackgroundCanvas extends React.Component {
  componentDidMount() {
    this._canvas.fillStyle = ( ThemeContext.getValue() === 'dark' ? 'black' : 'white' );
    this._canvas.fillRect(0, 0, this._canvas.width, this._canvas.height);
  }
  render() {
    return <canvas ref={(el) => { this._canvas = el; }} />;
  }
}

@sompylasar One of the design goals of the new API is to discourage accessing values outside of React's render cycle, to prevent tearing in asynchronous mode.

I read the document but can't find much about why the force-deep-update approach cannot be used.
The idea being that whenever a context object changes, every element in the tree is walked to see if it has that object in its contextTypes, and will be updated if so, completely bypassing shouldComponentUpdate.
(This only needs do be done for children whose ancestor returned false on shouldComponentUpdate)
Would this not be equally fast as the proposed API? IMHO this is not even a breaking change, more like a bugfix.

Not sure what you mean. This is pretty much what the implementation will be doing. But you can't do it with the existing API because there is no way to know when the context has changed and when it hasn't. We could've added setContext to get around this, but there are other problems with that (as mentioned in the proposal).

@wmertens https://github.com/reactjs/rfcs/pull/2#issuecomment-350450243
As Dan said, the API will have similar semantics as forceDeepUpdate (without the "force" part). We could do this with the existing API by doing a shallow comparison of the result of getChildContext to detect changes. But current API isn't very ergonomic, relies on propTypes and requires a whole new instance variable. We want an API that's easy to use, guides people to the best practices, and is as fast as possible by default.

@mjackson

One use case is passing around location objects from the current history API, which is mutable.

I'm kind of surprised by that, I would have thought that history creates a new location object every time the location changes.  There's no particular reason the location object has to be mutable, is there?

@jedwards1211 , I'm sure the answer is interesting, but we should probably keep this particular issue on the subject of the new context API. The history issue tracker is a better place to have that discussion.

@acdlite The documentation needs clarification on "Only one provider type per consumer"

The solution is to use compose consumers:

<FooConsumer>
  {foo => (
    <BarConsumer>
      {bar => (
        // Render using both foo and bar
        <Child foo={foo} bar={bar} />
      )}
    </BarConsumer>
  )}
</FooConsumer>;

Will the {bar => ...} function get called if foo context didn't change and bar context did change?
Why would it happen? Isn't {foo => ...} getting called only if foo context got changed?

@acdlite ignore that

@acdlite @gaearon How would one chain / replace context mid-graph with this approach?
See my previous question: https://github.com/reactjs/rfcs/pull/2#issuecomment-350180266
Basicly, we took advantage of a consumer also being a provider mid-graph to add/replace context values to the leave nodes. (at router nodes)  The mid-way consumer/provider would consume the incoming 'breadcrumb' and create a new breadcrumb and pass it down through context.

@jsg2021
type Breadcrumbs = Array<string>;
const BreadcrumbContext = React.createContext([]);

function Breadcrumb(props) {
  return (
    <BreadcrumbContext.Consumer>
      {breadcrumbs => (
        <BreadcrumbContext.Provider value={[...breadcrumbs, props.breadcrumb]}>
          {props.children}
        </BreadcrumbContext.Provider>
      )}
    </BreadcrumbContext.Consumer>
  );
}

Replacing subscription-based patterns in favor of context's built-in change propgation may require a larger effort. However, as a first step, developers can migrate to the new API without abandoning subscriptions.

I'm a bit concerned that the subscription use-case isn't a more central part of this proposal: a forced, deep update of the tree on every context change is equivalent to keeping application state as a single immutable data structure and passing that entire structure as a prop everywhere - any tiny change to the global state will cause a global re-render. The suggested approach (from comments) seems to be to scope context more narrowly:

Having a single ReduxContext isn't ideal. It should be fine, probably even faster than React Redux today. But for maximum performance, the best practice is going to be scoped providers

How would this be (more) efficient? Some applications can have (many) dozens of Flux stores/Redux reducers, for example when using a "best practice" of normalizing data into stores/reducers by their type (e.g. a user reducer, post reducer, etc). A one context per store/reducer approach would lead to an explosion of contexts and necessitate multiple consumers at each component (one for each reducer that it needs to access). If all Redux apps go from having ~one HOC per component to N, that will almost certainly not be performance-positive, as well as complicating debugging and configuration.
There is a fundamental tension in achieving efficient updates in React apps: in the general case application state is a cyclic object graph, while the UI is always a tree. Any change in the object graph could theoretically necessitate an update to any part of the tree (in the worst case, of the entire tree). This is an incredibly source of complexity and a critical aspect to "get right" for performance, but is left to the developer under the current context API and not addressed by this proposal. This leads to frameworks (such as Relay) that track data dependencies of components and efficiently map changes in the object graph to the minimal set of components that must update in response.
Note that representing an object graph with a persistent data structure is not sufficient to determine what parts of the UI need an update: a more complicated mapping is required and there are inevitable tradeoffs in the granularity of state/UI mapping. More fine-grained (ie object/recrd + field granularity) tracking achieves less wasted re-renders at the cost of greater book-keeping overhead, while coarse-grained (ie whole object/record granularity) tracking potentially re-renders more while using similar book-keeping (aside: the latter appears to be a good balance in practice).
In summary: I'd argue that the real complexity that is currently shifted to user space is about efficient mapping of state changes to UI updates, not the context API. It isn't clear how much value just changing the context API alone provides, and I'm especially concerned about the advice (more fine-grained context objects) as being counter-productive to the eventual goal of reducing subscriptions.

what if we want to consume  from two different contexts?
AContext.consume(
  BContext.consume(

  )
)

I suspect this adds some complexity

Here are the API variants proposed in this thread. I've implemented the same set of components in each to illustrate the trade-offs:
JSX render prop using children.
function MultiConsumer() {
  return (
    <FooContext.Consumer>
      {foo => (
        <BarContext.Consumer>
          {bar => <Child foo={foo} bar={bar} />}
        </BarContext.Consumer>
      )}
    </FooContext.Consumer>
  );
}

function Breadcrumb(props) {
  return (
    <BreadcrumbContext.Consumer>
      {breadcrumbs => {
        <BreadcrumbContext.Provider value={[...breadcrumbs, props.breadcrumb]}>
          {props.children}
        </BreadcrumbContext.Provider>;
      }}
    </BreadcrumbContext.Consumer>
  );
}

JSX render prop using render:
function MultiConsumer() {
  return (
    <FooContext.Consumer
      render={foo => (
        <BarContext.Consumer render={bar => <Child foo={foo} bar={bar} />} />
      )}
    />
  );
}

function Breadcrumb(props) {
  return (
    <BreadcrumbContext.Consumer
      render={breadcrumbs => (
        <BreadcrumbContext.Provider value={[...breadcrumbs, props.breadcrumb]}>
          {props.children}
        </BreadcrumbContext.Provider>
      )}
    />
  );
}

Non-JSX render prop:
function MultiConsumer() {
  return FooContext.consume(foo =>
    BarContext.consume(bar => <Child foo={foo} bar={bar} />),
  );
}

function Breadcrumb(props) {
  return BreadcrumbContext.consume(breadcrumbs =>
    BreadcrumbContext.provide(
      [...breadcrumbs, props.breadcrumb],
      breadcrumbs => props.children,
    ),
  );
}

Crazy idea... when decorators finalize, maybe we could use a context connection decorator :) and we could assign that context value to a propName...
@FooContext.consumeAs('foo')
class extends React.Component {
  static propTypes = {
    foo: PropTypes.object //passed as prop from connected HOC/decorator
  }
  ...
}

I think this would be a nice API for consuming multiple contexts:
const ThemeContext: Context<Theme> = React.createContext('light')
const ReduxContext: Context<State> = createReduxContext(store)

connectContext({
  theme: ThemeContext,
  state: ReduxContext,
})(
  ({theme, state}) => (
    ...
  )
)

Or
@connectContext({
  theme: ThemeContext,
  state: ReduxContext,
})
class MyComponent extends React.Component {
  static propTypes: {
    theme: PropTypes.string,
    state: PropTypes.object,
  }
}

Neither of those are likely to be the official React API since they can be implemented in user space on top of the render prop proposal.

@acdlite that's true, but wouldn't any implementation of connecting to N contexts have to nest N connector components one inside of another?  As long as the official API avoids an N+1 nesting problem in some way or another, then I'm happy with it.

@acdlite  😄 yeah, I know... decorators aren't final yet. That's why I said 'crazy idea' ;)

As already mentioned in the thread a few times, we are not going to consider APIs that inject props into components (which any HOC-like API does). The proposal explains why it’s a problem (polluting the props namespace), and why we went for another approach instead. You can still implement HOCs/decorators on top of it. Please let’s avoid further comments suggesting this, as we already had this argument a few times, and are now just going in circles.

wouldn't any implementation of connecting to N contexts on top of the official API you've proposed have to nest N connector components one inside of another?

Yes, it would (and that would work fine). It is intentional so that comparisons stay fast when React finds the consumer components in the tree.
If you anticipate that you’ll often want to consume the same multiple contexts, you can abstract them away behind a single component. In fact if you scroll the thread up, you’ll find that somebody even wrote a library to do that 🙂 https://github.com/reactjs/rfcs/pull/2#issuecomment-350309935
Or you can unify several values that usually change together into a single value.

@gaearon I wasn't really proposing official api, I was thinking out loud to an idea of a way to make the 'nesting' complaints a little less visible...and allow to you to pick the propName...  sorry for the noise.

Will there be a way to keep something like <StaticContainer> working with this setup?
I'm aware that it doesn't 100% work right now, but it is convenient to fully freeze a subtree in cases where e.g. it's animating out.

@taion StaticContainer doesn't really work at all with context currently. Context doesn't update properly, so any provider/consumer pair that uses updating context uses a subscription model where the provider passes down some sort of observer, event system, or signal that lets the consumer listen for new values directly. This skips over the StaticContainer entirely.

@dantman Yes – it's a bit unfortunate and I'm aware of this. In some cases it works right now and in some cases it doesn't. It'd be nice to have a more reliable way to handle these kinds of things.

@taion Since the approach was broken in the first place, I don't think addressing it in this proposal makes sense, but we'd be open to RFCs that attempt to solve that problem (deferring/freezing unmount tree) in some other way.

It's not exactly broken in the current case, though. For anyone using context in the "standard" way right now, it does in fact work. The interactions with the subscriber pattern aren't great, granted, but it works with the current out-of-the-box context feature.

Could you implement something like a StaticContainer as a provider?
class StaticProvider extends Component {
  shouldComponentUpdate(nextProps) {
    return !!nextProps.shouldUpdate
  }

  render() {
    return scopedContext.provide(this.props.value, () => this.props.children)
  }
}

class App extends Component {
  render() {
    return (
      {/* snip */}
      { globalContext.consume(
        value => <StaticProvider value={value} shouldUpdate={movingOut}><StuffIDontWantToUpdate /></StaticProvider>
      ) }
      {/* snip */}
    )
  }
}

The trick would be writing your app such that the components in StuffIDon'tWantToUpdate subscribe to the scopedContext instead of the globalContext. If you do that, then as long as shouldUpdate is false StaticProvider won't update the context.

For anyone using context in the "standard" way right now, it does in fact work.

It doesn't work in the sense that setState inside the "frozen" subtree causes it to update. I understand your point but I don't agree that "static container" really worked in the intuitive sense of "static".

For anyone using context in the "standard" way right now, it does in fact work

Sideways subscriptions broke it even if you don't use context. For example Flux stores.

Or, for example, if mounting the component triggered an API call that put the result into state and rendered the results when loaded.

The setState thing is interesting. That's not exactly what I was thinking of, though. I was thinking more in the sense of the current implementation of "block all updates coming from above".
So, sure, subscribers using setState would break this, but within the context of top-down information flow within React itself, things do in fact work right now – well enough for this to be used within Relay Classic, for example.

@acdlite I just submitted a PR to react-broadcast that more closely aligns our API with this proposal. Interestingly enough, I didn't actually need to use context at all to make it work 😅 And I avoided using componentWillMount and used componentDidUpdate instead, as you suggested. Would appreciate any feedback you may have!

Not much to add at this stage, but i did want to at least mention. The Consumer component thing is mildly awkward. I've rarely needed context in order to pass directly to a child (maybe theming is the best example of that usage?). Generally (relay, react-bootstrap, react-intl) context is consumed in event handlers and methods of the component. This api doesn't make that impossible but it does mean that a large amount of context usage will be via HOC's (like injectIntl).

Is that a reason to prefer an HOC as the consumer-facing API, and relegate <Consumer> to an implementation detail? If in practice most users will be using an HOC-style API, it then seems preferably to set the API surface area at that point.

Render props are strictly more powerful than HOCs. Everything you can do with a HOC, you can do with render props, but not the other way around. I believe this was already discussed a few times in this thread.

@gaearon

Everything you can do with a HOC, you can do with render props, but not the other way around.

What can you do with render props that you can’t do with an HOC?

@j-f1 Here's a good article on that. You can find more material searching "render props vs hoc" or similar.

Please search for "HOC" in this thread for past discussions.
Also, from the proposal text:

Notice how in the above example, the context value can be passed to any arbitrary prop on the child component. The advantage of the render prop API is that we avoid clobbering the prop namespace.

@gaearon
I understand your concerns about function namespace pollution, and they make a lot of sense to me.
Let me rephrase my concern in a way that touches on what I see as an issue with the current spec, rather than proposing a specific solution. It feels like, if I'm writing a library with a component that is designed to just use context, the DX seems subpar:
class ComponentRequiringContext extends React.Component {
  // ...
}

export default function ComponentRequiringContextContainer(props) {
  return (
    <MyContext.Consumer>
      {(myValue) => (
        <ComponentRequiringContext
          {...props}
          myValue={myValue}
        />
      )}
    </MyContext.Consumer>
  );
}

Obviously this works, but it's quite clunky, and involves a substantial amount of extra typing. It also requires two additional wrapper components, which is also not ideal.
While this isn't a deal-breaker, it'd be better if the first-class solution here had better DX for what might likely be the most common use case available.
So going off @josephsavona's comment from https://github.com/reactjs/rfcs/pull/2#issuecomment-351118665, I think we actually end up with two extra components per context consumer for this very common use case here, and that seems quite non-ideal!

@taion Even if the public API were an HOC, internally we'd likely use an extra node with a special type, anyway.

@acdlite That’s totally fine. My concern in the example above is the second container component. If my HoC creates a component that renders a consumer that then renders the actual component... well, that’s not ideal.

Nothing is ideal, yo

Lucky for us, @trueadm is working on a compiler that will compile away the levels of abstraction (no pressure, Dom)

By moving things into the render phase, it becomes far easier to compile them ahead-of-time. This is because the compiler actually evaluates the render phase as if it were rendering the component. It does this and builds up a picture of how everything works, then carries on rendering the tree of components. Upon completion, it then knows how to inline/fold components into one-another, removing indirection completely in some cases.

It feels like, if I'm writing a library with a component that is designed to just use context, the DX seems subpar

I don't understand this example. (Partly because the other component is just ...). Why do you need two components there? Which one is part of the library? Why are they split in two?

@gaearon The concern ultimately is that if I do want something like an HoC, this proposal unavoidably adds a second component in the tree.
@acdlite @trueadm Is the implication then, that if we move forward with this, there will be a regression in the near term for users of HoCs? That seems non-ideal. As a Relay user, the vast majority of our components use the Relay HoCs – adding yet another extra React component per each of our components really doesn't feel great.

@gaearon I think the component wants access to the context outside of the render prop. The only way to do this with the proposed API is to use a HOC.

@taion I personally feel the proposal is better than HoCs when it comes to DX as it's more explicit as to what is going on – whilst HoCs make you jump around files and the context changes doing so. In terms of performance, I don't see this being slow than HoCs at all – in fact, with the compiler, it should be faster.
I also want to note – when HoCs were first introduced, there was as much friction as there is to this proposal.

@trueadm
That's fair. In general I do think as a user-facing API, the render prop is nicer – though as a library developer I may often want to expose HoCs anyway.
Is the compiler expected to ship before this revised version of context drops?

I don't think anyone is really against the API here, just noting that the ergonomics of it doesn't eliminate the HOC use case but does add another component to the hierarchy for each consumer, which if that's not a concern then no problem, it does make the Devtools even noiser tho.
a better example:
function injectIntl(Component) {
  return (props) => (
    <IntlConsumer render={ntl => <Component intl={intl} {...props}/>} />
  )
}

@taion The compiler is being baked into Prepack, which is an open source project, but it's still in development internally. I'll probably announce more details on in in the New Year. Feel free to reach out to me directly if you want to know more – I'd rather keep this PR on track.
@jquense We can easily make these components appear differently in dev tools, I don't think that's a big issue. We already do this for fragments.

One more time I’d encourage everyone to read the full discussion. All of these points (including DevTools and access to context in lifecycles) have already been discussed. It’s not productive to keep going in circles.

@taion

Is the implication then, that if we move forward with this, there will be a regression in the near term for users of HoCs?

No

How about this API? No pseudocomponents, no HOC:
// contexts.js
export const theme = React.createContextType('theme') // returns an opaque object

// button.js
import { theme } from './context'

const SFCButton = ({ label, onClick }, { theme }) =>
  <button className={theme === 'dark' && 'is-dark'} onClick={onClick}>{label}</button>
SFCButton.context = {
  theme
}

class ClassButton extends React.Component {
  static contexts = {
    theme
  }

  render() {
    return <button className={this.context.theme === 'dark' && 'is-dark'} onClick={this.props.onClick}>{this.props.label}</button>
  }
}

// app.js
import { theme } from './context'

class App extends React.Component {
  onThemeToggle = () => {
    this.setContext(theme, oldTheme => oldTheme === 'light' ? 'dark' : 'light')
  }
  render() {
    return <SFCButton label='toggle theme' onClick={this.onThemeToggle} />
  }
}

@acdlite
Oops, I missed that you already brought up this point in https://github.com/reactjs/rfcs/pull/2#issuecomment-349810750. My bad.
In that context, though, why can't the HOC's own component be the "special" component that you scan for? Does the implementation just preclude that.
Or, just to understand correctly, is the idea that Prepack will ship an optimizer that will optimize away the cost here prior to launch anyway, and the DevTools work is scheduled anyway, so this question of the extra component is entirely academic? In which case :+1: and thanks for your hard work on this.

@j-f1 The proposal has a section why on setContext: https://github.com/acdlite/rfcs/blob/new-version-of-context/text/0000-new-version-of-context.md#setcontext
I'm going to start deleting comments if they repeat points already discussed without adding any extra value. This is getting out of hand.

I've tried to summarize what's already been said in a gist, hopefully this helps everyone get on the same page.
https://gist.github.com/vcarl/2acbf070524ae1cf7a0664bedd7bf26d

From the gist:

setContext isn't necessary because React will rely on referential comparison to identify changes. There's no need for a setContext to notify React of changes.

… unless the way you change the value of the context is by using setContext. I feel like this doesn’t really address why my API proposed above won’t work.

So far, my main concern with the render props pattern is that it encourages writing inline functions in render(), which is highly discouraged by eslint/tslint jsx rules 🤔
Sure, you can always just point it to a bound instance method, but then you are spreading your rendering throughout the class due to API requirements.
On the other hand, there is no reasonable implementation of shouldComponentUpdate for Consumer, nor any need to invalidate the result of the previous call like with ref, so this is probably a smaller problem than I'm giving it credit for.

@j-f1 How about the next sentence?

[setContext] API would only be valuable when combined with mutation, which we're specifically aiming to discourage.

Are you trying to discourage changing the context value (theme changing from light to dark) or the mutation of objects passed as context values? If the latter, then I fail to see why a setContext-style API that uses reference equality to determine what to update would be a bad idea.

What is the point of setContext if it bails out on reference equality? What advantage does it have over using setState in the parent and passing prop? Please show a full example of the API you're proposing or else we'll just keep going in circles.

@acdlite
const theme = React.createContextType('theme') // returns an opaque object
// theme !== React.createContextType('theme')
// This allows multiple systems to interoperate
const somethingElse = React.createContextType('something else')

const Button = ({ label, onClick }, { currentTheme }) =>
  <button className={currentTheme === 'dark' && 'is-dark'} onClick={onClick}>{label}</button>
Button.context = {
  currentTheme: theme // the value of `context.currentTheme` comes from the `theme` context type
}

const Hero = ({ left, right, ctaLabel, onAction }) =>

{left}

{right}

      <Button label={ctaLabel} onClick={onAction} />

class App extends React.Component {
  static providedContext = [
    theme // children’s context variables are searched for `[foo]: theme`.
          // the value of `this.context[foo]` is set to the value provided
          // as the second argument to `this.setContext(theme, value)`
          // in a parent. Children running `setContext` override context
          // provided by parents, but only for their subtree.
  ]
  onThemeToggle = () => {
    // second parameter is a function taking the old value and returning the new value
    // or just the new value. To set a function, you have to do `() => (...args) => { ... }`.
    this.setContext(theme, oldTheme => oldTheme === 'light' ? 'dark' : 'light')
    // this.setContext(somethingElse, 2)
    // throws because `somethingElse` wasn’t provided in `App.providedContext`
  }
  render() {
    return
      <Button label='toggle theme' onClick={this.onThemeToggle} />
      <Hero
        left={

Buy Now!

...

        }
        right={

          some description
        }
        ctaLabel="Buy"
        ctaAction={deductFunds}
      />
      ...

  }
}

Basic router implementation
const currentRoute = React.createContextType('current route')
function routeMatches(route, currentRoute) { /* ... */ }

class Router extends React.Component {
  static providedContext = [
    currentRoute
  ]
  onHashChange = () => {
    this.setContext(currentRoute, location.hash.slice(1))
  }
  componentDidMount() {
    this.onHashChange()
  	window.addEventListener('hashchange', this.onHashChange)
  }
  componentWillUnmount() {
  	window.addEventListener('hashchange', this.onHashChange)
  }
  render() {
    return this.props.children
  }
}

class Route extends React.Component {
  static context = {
    currentRoute
  }

  render() {
    if (routeMatches(this.props.path)) {
      return this.props.children
    } else {
      return this.props.alt
    }
  }
}

const Link = ({ children, to, ...props }) =>

    {children}

// Usage:

<Router>

    <Route path="/foo">
      content here!
      <Link to="/">go home</Link>
    </Route>
    <Route path="/">
      <Link to="/foo">visit</Link>
    </Route>

</Router>

Current API Polyfill

function createContext(initialValue, { displayName }) {
  const value = React.createContextType(displayName)
  return {
    Provider: class extends React.Component {
      static providedContext = [value]
      componentWillReceiveProps(nextProps) {
        this.setContext(value, nextProps.value)
      }
      render() {
        return this.props.children
      }
    },
    Consumer: class extends React.Component {
      static context = { value }
      render() {
        return React.children.only(this.props.children)(this.context.value)
      }
    }
  }
}

@j-f1 Do you really think it's simple and nice API? It doesn't have any advantages over RFC. Moreover it introduces two new static fields and one method. Too much API.

A few things that jump out at me about @j-f1's suggestion (please correct inaccuracies aggressively if you can spare the time)

It's more similar to both the current setState api (with which everyone is familiar) and the current context API (with which many of the people who'll be using context are familiar) than the other proposals.

It keeps the size of the React.Component API the same (although it changes a lifecycle method to an imperative one), and adds one simple method to the React API (one which might not be necessary in the future - could just tell people to use a Symbol). The other options make the Component API smaller but the React API method they add is more complicated.

It doesn't involve adding additional components to the tree.

Using this API you could certainly build the render prop and HOC APIs pretty easily. I don't think you could build the other one, but I could be wrong.

In React there are two imperative instructions (I think, correct me if I'm wrong) - setState and forceUpdate. Adding a third doesn't feel like a 'React'y way to solve the problem.

Currently there is ONE thing that describes the state of your application - state, whether that state lives in a component or is passed down to it from above via props/context. This would make context into it's own entity.

Questions I have:

The default behavior for setState is to re-render the component in which it's called. Would the default behavior for setContext be to re-render every component that is consuming that context, including the one in which setContext was called?

Are you suggesting that more than one component could provide the same context? Because at that point it would just be global state (which is evil, hard to reason about, and would probably make it harder for React to efficiently diff/render/update stuff).

Would implementing this API be significantly more difficult than the others?

Closing note: as a wee Reactling I'm a bit wary of the amount I'm participating in this conversation. I'm sure lots of people care a lot about what's being discussed here and are a lot better informed than I am. If you think I'm adding too much noise to this conversation feel free to shoot me a message/tweet. Love me some feedback.

Thanks for your reply @JNaftali! Here are my responses to some of your points:

The default behavior for setState is to re-render the component in which it's called. Would the default behavior for setContext be to re-render every component that is consuming that context?

Yes. However, it should not be much of a penalty for components that don’t use the context in rendering, since if the rendered output doesn’t change, nothing will be rerendered.

including the one in which setContext was called?

No, because the component doesn’t have any way of accessing its current context (no getContext method), since you’re presumably computing context from state or props. (as an escape hatch, you can do this.setContext(key, value => { /* use value */; return value }))

If context is meant to be computed from state or props, why not leave it as a lifecycle method the way it is now? In that scenario there would be practically no API changes - the only thing about context that would change is changes propagating through componentShouldUpdate (and no longer requiring proptypes?). Everything else in your proposal could be accomplished by storing your context under a Symbol key:
const themeContext = Symbol('this string doesnt matter')

getChildContext() {
  return {
    [themeContext]: this.state.theme
  }
}

@JNaftali
As you noted above, it's less about "no API changes" than about dramatically cutting down the API surface area.
To your:

It keeps the size of the React.Component API the same (although it changes a lifecycle method to an imperative one), and adds one simple method to the React API (one which might not be necessary in the future - could just tell people to use a Symbol). The other options make the Component API smaller but the React API method they add is more complicated.

I think the point is that the API method is in some sense less complicated, since it's just this thing that sits on its own.
It's not an exceedingly onerous API for users, and in being a more "flat" API that just gives you a new component, is sort of extremely un-complicated because there aren't any new APIs to learn. It's just like having another provider.

The RFC has been finalized and implemented (with a functional children prop).


Update devDependencies

Since newer node.js versions should be running on the development systems, we can update the dependencies for developers. This has no effect on normal users of the package.

related to #15


problem with curry & Sequentials redux

This code is the same as https://github.com/ceylon/ceylon-js/issues/568, but with Sequential instead of List:
object seqUtils {
    shared [B*]([A*]) lift<A, B>(B(A) f)
        =>  shuffle(curry(map<A,B>))(f);

    shared [B*] map<A,B>([A*] list, B(A) f)
        =>  list.collect<B>(f);

    shared [Integer*] double([Integer*] list)
        =>  uncurry(Sequential<Integer>.collect<Integer>)(list,2.times);
}

shared void breakIt2() {
    value double = seqUtils.lift(2.times);
    print(double([1,2,3]));          // [2] (bad, should be [2, 4, 6])
    print(seqUtils.double([1,2,3])); // [2, 4, 6] (good)
}

have you updated your language module and compiler? I just tested and got [2,4,6]

Ok @chochos, here's a super reduced version of what still fails:
shared void run() {
    Anything echoX(Anything _, Anything x)
        =>  x;

    Anything(Anything) id
        =   curry(echoX)(null);

    print(id([1,2,3])); // prints "1"
}


docs: Fixed formatting to correctly surface the NavLink component in markdown

Before

After

fixed elsewhere, but thanks!


[New icon] Barcode

Something link this:
http://www.endlessicons.com/wp-content/uploads/2012/11/barcode-icon-614x460.png
https://cdn0.iconfinder.com/data/icons/shopping-and-e-commerce-2/400/Barcode_icon_-512.png

Hi, @carol91! I don't really see how this fit's into a payment method/operator font. What do you think about it?

Here in Brazil, we have a payment method called "Boleto", that uses a barcode to pay it on internet banking. Like this:

The icon which represents Boleto is the barcode. :)

+1 / Payment by the barcode (Boleto) is payment method more traditional here in Brazil.

+1 for boleto icon

+1 for boleto icon

Same as https://github.com/vendocrat/PaymentFont/issues/29

+1 for boleto icon

+1 for boleto icon


Exception: "Could not set Media Type. Device may be locked" when using Left IR + Right IR

Required Info

Camera Model
D400

Firmware Version
5.8.15

Operating System & Version
Win 10

SDK Version
2.8.3

Issue Description
I'm trying to access a real stream of the Right IR image.
According to this thread if I want to get the real Right IR stream and not a computed stream I need to get both the Left and Right IR streams and then select the right IR stream when I need to.
However if I do that I get an exception when calling rs2::pipeline::start():
"Could not set Media Type. Device may be locked"
Interestingly the same happens when I try the same in the RS Viewer (selecting both IR streams). In that case I get a little dialog box with the same Exception message. I'm using version 2.8.3.
Is this a bug that has been fixed in one of the more recent versions of librealsense?
At the end of the day I simply want to access the Right IR stream as it comes from the camera, just as I can access the Left IR stream.

This looks like an error that you'd get when trying to stream profiles that do not work together.
Which profiles are you trying to stream?

IR Left 1280x720 RGB8

IR Right 1280x720 Y8

I just found out that it works if I use Y8 for both streams.

Hi @xtrawurst,
The D415 offers the following stream combinations:

Depth
Left IR
Left RGB
Left IR + Right IR
Depth + Right IR
Depth + Left IR
Depth + Left RGB
Depth + Left IR + Right IR
Depth + Right IR

The hardware is incapable of producing both RGB and an IR stream from the stereo module.

@dorodnic
Ok, thanks for the clarification.


Cannot write to bitstream with dart package

I don't know if this is the right place to report this or not, but this is where the dart package links. I don't know if you actually created the dart package or someone just generated it from your repo or what. See https://pub.dev/packages/bitstream
None of this is probably an issue in your typescript and probably only applies to the dart generated code.
Anyway, you can't write to a Bitstream using the dart package because it increases the length property of the List, but that throws an exception in dart for types that are not nullable which would never be the case here. Additionally I'd just like to mention that the constructor is a little odd that it takes Uint8List which is fine for reading, but would never be writeable because Uint8Lists are not growable so it would probably be better if it just took a List which is what the member variable uses.

Hi Steve, thanks for using Bitstream.
My pub.dev profile linked to the wrong repository (I moved this one to bitstream-dart and created the Typescript one as bitstream, but forgot to change the links on Pub.dev!) I've now resolved this, it should be correctly pointing to this repo!
I'm not sure what you mean about writing to the Bitstream, do you have sample code which isn't working?
That's a good point about the constructor. The project I was working on when I designed this involved pulling in a load of binary data as a Uint8List which is why I did it this way, but when I get a chance I may have a look at modifying the constructor to be a little more helpful. Or feel free to make the changes yourself if you'd like!

I tested this with flutter 2.8.1 (dart 2.15.1).
Sample:
  var bs = BitStream();
  bs.write(0, bytes: 1);

Error:
[ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: type 'Null' is not a subtype of type 'int' in type cast
#0      List.length= (dart:core-patch/growable_array.dart:246:12)
#1      BitStream.write
package:bitstream/bitstream.dart:50

This happens because you can't do this (perhaps you could in older dart versions?):
      _stream.length = thisByte + 1;

Length setter code:
  void set length(int new_length) {
    if (new_length > length) {
      // Verify that element type is nullable.
      null as T; // Fails here because for List<int> int is not nullable
      if (new_length > _capacity) {
        _grow(new_length);
      }
      _setLength(new_length);
      return;
    }

So I really just don't see any possible way bitstream writing could even work right now because it can never extend the list to write anything to it.


Wording: Avoid using contacts word due to their absence

[ ] Onboarding Send: Transfer to contacts and subaccounts. Receive by sharing your address.,
[ ] Desktop Send: Paste the recipient address below. Or send to subaccounts, contacts or scan QR code.

Transfer to accounts and subaccounts. Receive by sharing your address.
Paste the recipient address below, scan QR code or send to subaccounts.


Remove Files Previews in Details, Tiles, Small and Column Layouts

What's the Problem?
Showing file previews for images and video makes no sense in Details, Tiles, Small, and Column Layout view. The Previews are so small and are very much helping.
Solution/Idea
Just the icons would look much better as they are in the Windows File Explorer.  Disabling this feature within the code will add much performance to the Files App. The previews should be available for Medium and Large Layouts configuration.
Alternatives
Not something on my mind.
Priorities
This is a Should be implemented feature
Files Version
2.1.13
Windows Version
Windows 11
Comments
No response

I personally find the preiews useful and it helps differentiate between images.


feature(ElementHandle)

Still Work in progress, this is my first contribution to puppeteer.

Just want to tell you guys this project does benefit tons of developers, great job 😎

Description
Add $eval to ElementHandle and also refactor the frame.$eval with elementHandle.$eval.
Fixes #2401.
Progress

[x] feature implmentation
[ ] code review
[x] $eval:

[x] lint: npm run lint

[x] eslint
[x] doc lint

[x] API guidelines
[x] Unit test

[x] $$eval:

[x] lint: npm run lint

[x] eslint
[x] doc lint

[ ] API guidelines
[x] Unit test

@abalone0204 the code is good. Do you plan to do $$eval as a part of this PR?

@aslushnikov Thank you. Glad to hear that.
Yes, I'm working on it now.

@abalone0204 Someone marked checkboxes for "$$eval" for this PR; however, I don't see any code related to this. Some kind of error?

@abalone0204 do you need help here? another option is to add $eval and leave $$eval for another PR


Fixed issue with static files not being part of the package

Updated Microsoft.AspNetCore.Components & Microsoft.AspNetCore.Components.Web to version 3.0.0
Included the wwwroot folder
Changed the output directory of tsc to wwwroot
Updated README.md with instruction for both Blazor Server and Blazor WebAssembly

@aleksandar-smilevski Thanks for this fix. It sorted the issue I was having the same as #11.


Make code clippy-clean

A critical infrastructure crate such as this should leverage Rust's
static analysis tools to the greatest extent possible, I think.

I think adding documentation to the API would be beneficial as well

Thanks for the addition!


Use alternative protocol to upload to STM32

I recently got the @armstrap, which is a STM32F407VET6 with a built-in JTAG powered by a @blacksphere Black Magic. To test it out quickly with platformio, I used the disco_f407vg since it is also a f407. However, the configuration looks for ST-Link and fails. I'm not too familiar with the Black Magic, so I'm not positive what it needs.
That said, how do I specify another means to upload? I found the upload_protocol field, but the possible values aren't documented.
Thanks!

---
Want to back this issue? **[Post a bounty on it!](https://www.bountysource.com/issues/11126887-use-alternative-protocol-to-upload-to-stm32?utm_campaign=plugin&utm_content=tracker%2F2014790&utm_medium=issues&utm_source=github)** We accept bounties via [Bountysource](https://www.bountysource.com/?utm_campaign=plugin&utm_content=tracker%2F2014790&utm_medium=issues&utm_source=github).

The way I upload my code (via the CLI)

arm-none-eabi-gdb testprogram.elf
target extended-remote /dev/ttyACM0
monitor swdp_scan
attach 1
load   <----- Flashes your STM32F4 chip with binary testprogram.elf
run

Note:  /dev/ttyACM0 is Ubuntu specific

Got it. @ivankravets any idea how to specify gdb?

@valeros, please show @beriberikix how to create own platform using our stm32 platform as "base frame" and extend functionality. More details are in http://docs.platformio.org/en/latest/platforms/creating_platform.html

Hello @beriberikix! I'll try to help you.
First step is create new platform:
You need to create new folder platforms in platformio home dir ~/.platformio or %HOMEPATH%\.platformio (on Windows) and copy there two files (ststm32gdb.py, ststm32gdb-builder.py) from this gist: https://gist.github.com/valeros/ef7b632c5bcc4541c670
Now, you can install new platform with command platformio install ststm32gdb.
Second step is add new board:
You need to create new folder boards in platformio home dir ~/.platformio or %HOMEPATH%\.platformio (on Windows) and create there new file armstrap.json with board specification content:
{
    "armstrap_eagle": {
        "build": {
            "core": "stm32",
            "extra_flags": "-DSTM32F40_41xxx",
            "f_cpu": "168000000L",
            "ldscript": "armstrap_stm32_flash.ld",
            "cpu": "cortex-m4",
            "mcu": "stm32f407vet6",
            "variant": "stm32f4"
        },
        "frameworks": ["cmsis", "spl", "libopencm3", "mbed"],
        "name": "Armstrap Eagle",
        "platform": "ststm32gdb",
        "upload": {
            "maximum_ram_size": 196608,
            "maximum_size": 524288
        },
        "url": "http://docs.armstrap.org/en/latest/hardware-overview.html",
        "vendor": "Armstrap"
    }
}

Third step is add a new ldscript for armstrap board to this package ~/.platformio/packages/ldscripts. You can get it from this gist:
https://gist.github.com/valeros/88c89c3573e78df70579
After these steps, you can try to upload your firmware with next command:
platformio run -t upload --upload-port  /dev/ttyACM0
Unfortunately, I don't have board to check this aproach, but in theory it should work.
That's all, please tell us about your results.

Thanks for the detailed steps! When I tried installing the platform, I get an error (see below.) It appears as if the directory is not being discovered on my Mac. Do I need to add anything in addition to my $PATH?
$ platformio --version
PlatformIO, version 1.4.0
$ ls ~/.platformio/platforms/
ststm32gdb-builder.py	ststm32gdb.py
$ platformio search
atmelavr (available packages: ldscripts, framework-libopencm3, toolchain-gccarmnoneeabi, tool-lm4flash, framework-energiativa)
--------
Atmel AVR 8- and 32-bit MCUs deliver a unique combination of performance, power efficiency and design flexibility. Optimized to speed time to market-and easily adapt to new ones-they are based on the industrys most code-efficient architecture for C and assembly programming.

atmelsam (available packages: ldscripts, framework-libopencm3, toolchain-gccarmnoneeabi, tool-lm4flash, framework-energiativa)
--------
Atmel | SMART offers Flash- based ARM products based on the ARM Cortex-M0+, Cortex-M3 and Cortex-M4 architectures, ranging from 8KB to 2MB of Flash including a rich peripheral and feature mix.

espressif (available packages: ldscripts, framework-libopencm3, toolchain-gccarmnoneeabi, tool-lm4flash, framework-energiativa)
---------
Espressif Systems is a privately held fabless semiconductor company. They provide wireless communications and Wi-Fi chips which are widely used in mobile devices and the Internet of Things applications.

freescalekinetis (available packages: ldscripts, framework-libopencm3, toolchain-gccarmnoneeabi, tool-lm4flash, framework-energiativa)
----------------
Freescale Kinetis Microcontrollers is family of multiple hardware- and software-compatible ARM Cortex-M0+, Cortex-M4 and Cortex-M7-based MCU series. Kinetis MCUs offer exceptional low-power performance, scalability and feature integration.

nordicnrf51 (available packages: ldscripts, framework-libopencm3, toolchain-gccarmnoneeabi, tool-lm4flash, framework-energiativa)
-----------
The Nordic nRF51 Series is a family of highly flexible, multi-protocol, system-on-chip (SoC) devices for ultra-low power wireless applications. nRF51 Series devices support a range of protocol stacks including Bluetooth Smart (previously called Bluetooth low energy), ANT and proprietary 2.4GHz protocols such as Gazell.

nxplpc (available packages: ldscripts, framework-libopencm3, toolchain-gccarmnoneeabi, tool-lm4flash, framework-energiativa)
------
The NXP LPC is a family of 32-bit microcontroller integrated circuits by NXP Semiconductors. The LPC chips are grouped into related series that are based around the same 32-bit ARM processor core, such as the Cortex-M4F, Cortex-M3, Cortex-M0+, or Cortex-M0. Internally, each microcontroller consists of the processor core, static RAM memory, flash memory, debugging interface, and various peripherals.

ststm32 (available packages: ldscripts, framework-libopencm3, toolchain-gccarmnoneeabi, tool-lm4flash, framework-energiativa)
-------
The STM32 family of 32-bit Flash MCUs based on the ARM Cortex-M processor is designed to offer new degrees of freedom to MCU users. It offers a 32-bit product range that combines very high performance, real-time capabilities, digital signal processing, and low-power, low-voltage operation, while maintaining full integration and ease of development.

teensy (available packages: ldscripts, framework-libopencm3, toolchain-gccarmnoneeabi, tool-lm4flash, framework-energiativa)
------
Teensy is a complete USB-based microcontroller development system, in a very small footprint, capable of implementing many types of projects. All programming is done via the USB port. No special programmer is needed, only a standard "Mini-B" USB cable and a PC or Macintosh with a USB port.

timsp430 (available packages: ldscripts, framework-libopencm3, toolchain-gccarmnoneeabi, tool-lm4flash, framework-energiativa)
--------
MSP430 microcontrollers (MCUs) from Texas Instruments (TI) are 16-bit, RISC-based, mixed-signal processors designed for ultra-low power. These MCUs offer the lowest power consumption and the perfect mix of integrated peripherals for thousands of applications.

titiva (available packages: ldscripts, framework-libopencm3, toolchain-gccarmnoneeabi, tool-lm4flash, framework-energiativa)
------
Texas Instruments TM4C12x MCUs offer the industrys most popular ARM Cortex-M4 core with scalable memory and package options, unparalleled connectivity peripherals, advanced application functions, industry-leading analog integration, and extensive software solutions.

$ platformio install ststm32gdb
Error: Unknown platform 'ststm32gdb'

This bug fixed in platformio2_0 branch.
In stable 1.4.0, you need to modify one single line in the file ststm32gdb.py:
Please. replace line, class Ststm32gdbPlatform(Ststm32Platform): to
class Ststm32GdbPlatform(Ststm32Platform):

It installs! I'm so close, but I have 1 issue left (might be a general PlatformIO question.)
Using the Blinky sample from Armstrap, I get a compile error that it cannot find the periperhal import, whether I place it in the libs folder or directly in the src (see below.) Suggestions? I didn't see an include section mentioned in the platform.ini docs. Also, maybe this is a n00b question but should installing a platform also download the peripherals?
$ platformio run -t upload --upload-port /dev/cu.usbmodem7B4097C1
[Wed Apr 22 06:26:32 2015] Processing autogen_armstrap_eagle (targets: upload, platform: ststm32gdb, board: armstrap_eagle, framework: cmsis)
arm-none-eabi-gcc -o .pioenvs/autogen_armstrap_eagle/src/main.o -c -g -Os -ffunction-sections -fdata-sections -Wall -mthumb -mcpu=cortex-m4 -nostdlib -MMD -DF_CPU=168000000L -DSTM32F4 -DSTM32F40_41xxx -DPLATFORMIO=010400 -I.pioenvs/autogen_armstrap_eagle/CMSIS -I.pioenvs/autogen_armstrap_eagle/STM32F4xx -I.pioenvs/autogen_armstrap_eagle/FrameworkCMSIS -I.pioenvs/autogen_armstrap_eagle/FrameworkCMSISVariant .pioenvs/autogen_armstrap_eagle/src/main.c
In file included from .pioenvs/autogen_armstrap_eagle/src/main.c:1:0:
.pioenvs/autogen_armstrap_eagle/src/main.h:2:28: fatal error: stm32f4xx_gpio.h: No such file or directory
#include "stm32f4xx_gpio.h"
^
compilation terminated.
scons: *** [.pioenvs/autogen_armstrap_eagle/src/main.o] Error 1
========================= [ ERROR ] Took 0.78 seconds =========================

Try this platformio.ini:
platform = ststm32gdb
framework = cmsis,spl
board = armstrap_eagle

Ah, makes sense! Got the success message. I will try uploading it tonight when I get home from work.
Thanks again.

Is this an SCons error?
$ platformio run -t upload --upload-port /dev/cu.usbmodem7B4097C1
[Wed Apr 22 21:03:25 2015] Processing autogen_armstrap_eagle (platform: ststm32gdb, board: armstrap_eagle, framework: cmsis,spl)
--------------------------------------------------------------------------------
BeforeUpload(["upload"], [".pioenvs/autogen_armstrap_eagle/firmware.elf"])
scons: *** [upload] TypeError : execv() arg 2 must contain only strings
Traceback (most recent call last):
File "/usr/local/lib/scons-2.3.4/SCons/Action.py", line 1065, in execute
result = self.execfunction(target=target, source=rsources, env=env)
File "/Users/jberi/.platformio/platforms/ststm32gdb-builder.py", line 19, in BeforeUpload
stdout=PIPE, stdin=PIPE, stderr=STDOUT
File "/usr/local/Cellar/python/2.7.9/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 710, in __init__
errread, errwrite)
File "/usr/local/Cellar/python/2.7.9/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 1335, in _execute_child
raise child_exception
TypeError: execv() arg 2 must contain only strings
========================= [ ERROR ] Took 0.95 seconds =========================

Please, try updated version ststm32dgb-builder.py:
https://gist.github.com/valeros/28d84a7a8f78825e6956

That did the trick @valeros! I know have BLINKENLICHTEN :low_brightness: :high_brightness: :low_brightness:
As an aside, the executable hangs until I forcibly quit  (see ^C in output below) and the firmware doesn't re-run when I power cycle the unit. I was having the same problem when I was using my Makefile, so I can take that issue back to the @armstrap Forum.
$ platformio run -t upload --upload-port /dev/cu.usbmodem7B4097C1
[Thu Apr 23 06:14:37 2015] Processing autogen_armstrap_eagle (platform: ststm32gdb, board: armstrap_eagle, framework: cmsis,spl)
--------------------------------------------------------------------------------
BeforeUpload(["upload"], [".pioenvs/autogen_armstrap_eagle/firmware.elf"])

^CGNU gdb (GNU Tools for ARM Embedded Processors) <IP_ADDRESS>40228-cvs
Copyright (C) 2013 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "--host=x86_64-apple-darwin10 --target=arm-none-eabi".
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>...
Reading symbols from /Users/me/Downloads/blinky-pio-armstrap/.pioenvs/autogen_armstrap_eagle/firmware.elf...done.
(gdb) Remote debugging using /dev/cu.usbmodem7B4097C1
(gdb) Target voltage: 4.9V
scons: *** [upload] Build interrupted.Available Targets:
No. Att Driver
1      STM32F4xx

(gdb) Attaching to program: /Users/me/Downloads/blinky-pio-armstrap/.pioenvs/autogen_armstrap_eagle/firmware.elf, Remote target
0x08000218 in SystemInit ()
at .pioenvs/autogen_armstrap_eagle/src/system_stm32f4xx.c:226
226	  RCC->PLLCFGR = 0x24003010;
(gdb) Loading section .isr_vector, size 0x188 lma 0x8000000
Loading section .text, size 0x264 lma 0x8000188
Start address 0x80002e8, load size 1004
Transfer rate: 2 KB/sec, 502 bytes/write.
(gdb) The program being debugged has been started already.
Start it from the beginning? (y or n) [answered Y; input not from terminal]
Starting program: /Users/me/Downloads/blinky-pio-armstrap/.pioenvs/autogen_armstrap_eagle/firmware.elf

Program received signal SIGINT, Interrupt.
0x080001c6 in delay (ms=550905, ms@entry=250)
at .pioenvs/autogen_armstrap_eagle/src/main.c:48
48	    while(ms--) {
(gdb) quit
A debugging session is active.

Inferior 1 [Remote target] will be killed.

Quit anyway? (y or n) [answered Y; input not from terminal]

Error: Aborted by user

Nice!
I made a small correction in ststm32dgb-builder.py:
https://gist.github.com/valeros/28d84a7a8f78825e6956
Can you test it?

Ah, that makes sense. @ work but will try again tonight!

No luck.
$ cat ~/.platformio/platforms/ststm32gdb-builder.py
# Copyright (C) Ivan Kravets<EMAIL_ADDRESS># See LICENSE for details.

"""
    Builder for ST STM32 Series ARM microcontrollers with GDB upload.
"""

import subprocess
from subprocess import PIPE, STDOUT
from os.path import join

from SCons.Script import (COMMAND_LINE_TARGETS, AlwaysBuild, Default,
                          DefaultEnvironment, Exit, SConscript)

def BeforeUpload(target, source, env):  # pylint: disable=W0613,W0621
    p = subprocess.Popen(
        [env.subst("$UPLOADER"), env.subst(source)[0]],
        stdout=PIPE, stdin=PIPE, stderr=STDOUT
    )
    result = p.communicate(
        input=b'''target extended-remote %s\nmonitor swdp_scan\nattach 1\nload\nrun\nkill\nquit''' % env.subst("$UPLOAD_PORT"))[0]
    print(result.decode())
    p.kill()
    if "error" in result.decode().lower():
        Exit("Error: Can't upload firmware with GDB")

env = DefaultEnvironment()

SConscript(env.subst(join("$PIOBUILDER_DIR", "scripts", "basearm.py")))

env.Replace(
    UPLOADER=join(
        "$PIOPACKAGES_DIR", "toolchain-gccarmnoneeabi",
        "bin", "arm-none-eabi-gdb"
    )
)

env.Append(
    CPPDEFINES=[
        "${BOARD_OPTIONS['build']['variant'].upper()}"
    ],

    LINKFLAGS=[
        "-nostartfiles",
        "-nostdlib"
    ]
)

#
# Target: Build executable and linkable firmware
#

target_elf = env.BuildFirmware()

#
# Target: Build the .bin file
#

if "uploadlazy" in COMMAND_LINE_TARGETS:
    target_firm = join("$BUILD_DIR", "firmware.bin")
else:
    target_firm = env.ElfToBin(join("$BUILD_DIR", "firmware"), target_elf)

#
# Target: Print binary size
#

target_size = env.Alias("size", target_elf, "$SIZEPRINTCMD")
AlwaysBuild(target_size)

#
# Target: Upload by default .bin file
#

upload = env.Alias(
    ["upload", "uploadlazy"], target_elf, BeforeUpload)
AlwaysBuild(upload)

#
# Target: Define targets
#

Default([target_firm, target_size])
$ platformio run -t upload --upload-port /dev/cu.usbmodem7B4097C1
[Thu Apr 23 19:58:12 2015] Processing autogen_armstrap_eagle (platform: ststm32gdb, board: armstrap_eagle, framework: cmsis,spl)
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
BeforeUpload(["upload"], [".pioenvs/autogen_armstrap_eagle/firmware.elf"])
^CGNU gdb (GNU Tools for ARM Embedded Processors) <IP_ADDRESS>40228-cvs
Copyright (C) 2013 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "--host=x86_64-apple-darwin10 --target=arm-none-eabi".
For bug reporting instructions, please see:scons: *** [upload] Build interrupted.

<http://www.gnu.org/software/gdb/bugs/>...
Reading symbols from /Users/me/Downloads/blinky-pio-armstrap/.pioenvs/autogen_armstrap_eagle/firmware.elf...done.
(gdb) Remote debugging using /dev/cu.usbmodem7B4097C1
(gdb) Target voltage: 4.9V
Available Targets:
No. Att Driver
1      STM32F4xx
(gdb) Attaching to program: /Users/me/Downloads/blinky-pio-armstrap/.pioenvs/autogen_armstrap_eagle/firmware.elf, Remote target
delay (ms=7521484, ms@entry=2500) at .pioenvs/autogen_armstrap_eagle/src/main.c:49
49	        __NOP();
(gdb) Loading section .isr_vector, size 0x188 lma 0x8000000
Loading section .text, size 0x264 lma 0x8000188
Start address 0x80002e8, load size 1004
Transfer rate: 2 KB/sec, 502 bytes/write.
(gdb) The program being debugged has been started already.
Start it from the beginning? (y or n) [answered Y; input not from terminal]
Starting program: /Users/me/Downloads/blinky-pio-armstrap/.pioenvs/autogen_armstrap_eagle/firmware.elf

Program received signal SIGINT, Interrupt.
delay (ms=4995101, ms@entry=2500) at .pioenvs/autogen_armstrap_eagle/src/main.c:49
49	        __NOP();
(gdb) Kill the program being debugged? (y or n) [answered Y; input not from terminal]
(gdb)
Error: Aborted by user

About firmware re-run:
Can you try change the order of commands kill and run (at first kill debug session and than run program)?
input=b"target extended-remote %s\nmonitor swdp_scan\nattach 1\nload\nkill\nrun\nquit" % env.subst("$UPLOAD_PORT"))[0]

Just replace that in ststm32gdb-builder.py, right? Question - to update this file all I'm doing is deleting the *.pyc and re-runinng platformio install ststm32gdb. Is that right?
$ cat ~/.platformio/platforms/ststm32gdb-builder.py
# Copyright (C) Ivan Kravets<EMAIL_ADDRESS># See LICENSE for details.

"""
    Builder for ST STM32 Series ARM microcontrollers with GDB upload.
"""

import subprocess
from subprocess import PIPE, STDOUT
from os.path import join

from SCons.Script import (COMMAND_LINE_TARGETS, AlwaysBuild, Default,
                          DefaultEnvironment, Exit, SConscript)

def BeforeUpload(target, source, env):  # pylint: disable=W0613,W0621
    p = subprocess.Popen(
        [env.subst("$UPLOADER"), env.subst(source)[0]],
        stdout=PIPE, stdin=PIPE, stderr=STDOUT
    )
    result = p.communicate(
        input=b"target extended-remote %s\nmonitor swdp_scan\nattach 1\nload\nkill\nrun\nquit" % env.subst("$UPLOAD_PORT"))[0]
    print(result.decode())
    p.kill()
    if "error" in result.decode().lower():
        Exit("Error: Can't upload firmware with GDB")

env = DefaultEnvironment()

SConscript(env.subst(join("$PIOBUILDER_DIR", "scripts", "basearm.py")))

env.Replace(
    UPLOADER=join(
        "$PIOPACKAGES_DIR", "toolchain-gccarmnoneeabi",
        "bin", "arm-none-eabi-gdb"
    )
)

env.Append(
    CPPDEFINES=[
        "${BOARD_OPTIONS['build']['variant'].upper()}"
    ],

    LINKFLAGS=[
        "-nostartfiles",
        "-nostdlib"
    ]
)

#
# Target: Build executable and linkable firmware
#

target_elf = env.BuildFirmware()

#
# Target: Build the .bin file
#

if "uploadlazy" in COMMAND_LINE_TARGETS:
    target_firm = join("$BUILD_DIR", "firmware.bin")
else:
    target_firm = env.ElfToBin(join("$BUILD_DIR", "firmware"), target_elf)

#
# Target: Print binary size
#

target_size = env.Alias("size", target_elf, "$SIZEPRINTCMD")
AlwaysBuild(target_size)

#
# Target: Upload by default .bin file
#

upload = env.Alias(
    ["upload", "uploadlazy"], target_elf, BeforeUpload)
AlwaysBuild(upload)

#
# Target: Define targets
#

Default([target_firm, target_size])

Yes, just replace that line in ststm32gdb-builder.py
There is no need to delete .pyc files and reinstall platform.

Same results as before.
$ platformio run -t upload --upload-port /dev/cu.usbmodem7B4097C1
[Fri Apr 24 04:32:00 2015] Processing autogen_armstrap_eagle (platform: ststm32gdb, board: armstrap_eagle, framework: cmsis,spl)
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
BeforeUpload(["upload"], [".pioenvs/autogen_armstrap_eagle/firmware.elf"])
^CGNU gdb (GNU Tools for ARM Embedded Processors) <IP_ADDRESS>40228-cvs
Copyright (C) 2013 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "--host=x86_64-apple-darwin10 --target=arm-none-eabi".
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>...
scons: *** [upload] Build interrupted.Reading symbols from /Users/me/Downloads/blinky-pio-armstrap/.pioenvs/autogen_armstrap_eagle/firmware.elf...done.

(gdb) Remote debugging using /dev/cu.usbmodem7B4097C1
(gdb) Target voltage: 4.9V
Available Targets:
No. Att Driver
1      STM32F4xx
(gdb) Attaching to program: /Users/me/Downloads/blinky-pio-armstrap/.pioenvs/autogen_armstrap_eagle/firmware.elf, Remote target
delay (ms=8127453, ms@entry=2500) at .pioenvs/autogen_armstrap_eagle/src/main.c:48
48	    while(ms--) {
(gdb) Loading section .isr_vector, size 0x188 lma 0x8000000
Loading section .text, size 0x264 lma 0x8000188
Start address 0x80002e8, load size 1004
Transfer rate: 2 KB/sec, 502 bytes/write.
(gdb) Kill the program being debugged? (y or n) [answered Y; input not from terminal]
(gdb) Starting program: /Users/me/Downloads/blinky-pio-armstrap/.pioenvs/autogen_armstrap_eagle/firmware.elf

Program received signal SIGINT, Interrupt.
delay (ms=4700663, ms@entry=2500) at .pioenvs/autogen_armstrap_eagle/src/main.c:48
48	    while(ms--) {
(gdb) A debugging session is active.

Inferior 1 [Remote target] will be killed.

Quit anyway? (y or n) [answered Y; input not from terminal]

Error: Aborted by user

Let's try different approach.

/Users/me/Downloads/blinky-pio-armstrap/upload.gdb:6: Error in sourced command file:
The program is not being run.
======================================================================================= [ ERROR ] Took 1.70 seconds =======================================================================================

When I run the arm-none-eabi-gdb from the command line,  arm-none-eabi-gdb asks me after the upload whether I want to "Start it from the beginning?".  Do you think this prompt is what it's hanging on?  See output below...

arm-none-eabi-gdb armstrap_eagle_testprogram.elf
GNU gdb (GNU Tools for ARM Embedded Processors) <IP_ADDRESS>31129-cvs
Copyright (C) 2013 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later http://gnu.org/licenses/gpl.html
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "--host=i686-linux-gnu --target=arm-none-eabi".
For bug reporting instructions, please see:
http://www.gnu.org/software/gdb/bugs/...
Reading symbols from armstrap_eagle_testprogram.elf...done.
(gdb) target extended-remote /dev/ttyACM0
Remote debugging using /dev/ttyACM0
(gdb) monitor swdp_scan
Target voltage: 4.9V
Available Targets:
No. Att Driver
1      STM32F4xx
(gdb) attach 1
Attaching to program: armstrap_eagle_testprogram.elf, Remote target
0x080013ae in main () at ../source/main.cpp:51
51		};
(gdb) load
Loading section .isr_vector, size 0x188 lma 0x8000000
Loading section .text, size 0x1ccc lma 0x8000188
Loading section .data, size 0x864 lma 0x8001e54
Start address 0x8001334, load size 9912
Transfer rate: 17 KB/sec, 826 bytes/write.
(gdb) run
The program being debugged has been started already.
Start it from the beginning? (y or n) y   <----------------  USER PROMPT
Starting program: armstrap_eagle_testprogram.elf

Let's try upload with minimum set of commands:
target extended-remote /dev/cu.usbmodem7B4097C1
monitor swdp_scan
attach 1
load
quit

No errors this time, but no blinking. @armstrap I'm using the standard sample - shouldn't the USER LED be toggling? After I flash it the LED just stays solid, no matter what value I pass into delay().
$ platformio run
[Sat Apr 25 11:49:04 2015] Processing autogen_armstrap_eagle (targets: upload, platform: ststm32gdb, board: armstrap_eagle, framework: cmsis,spl)
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
/Users/me/.platformio/packages/toolchain-gccarmnoneeabi/bin/arm-none-eabi-gdb /Users/me/Downloads/blinky-pio-armstrap/.pioenvs/autogen_armstrap_eagle/firmware.elf -batch -x /Users/me/Downloads/blinky-pio-armstrap/upload.gdb
Target voltage: 4.9V
Available Targets:
No. Att Driver
1      STM32F4xx
delay (ms=133394, ms@entry=250) at .pioenvs/autogen_armstrap_eagle/src/main.c:48
48	    while(ms--) {
Loading section .isr_vector, size 0x188 lma 0x8000000
Loading section .text, size 0x264 lma 0x8000188
Start address 0x80002e8, load size 1004
Transfer rate: 2 KB/sec, 502 bytes/write.
A debugging session is active.

Inferior 1 [Remote target] will be detached.

Quit anyway? (y or n) [answered Y; input not from terminal]
======================================================================================= [SUCCESS] Took 1.46 seconds =======================================================================================

The board should be blinking.
I tried last upload.gdb with my discovery board and it works fine.
@armstrap
We run GDB in batch mode (without prompts), but it still hangs on run command execution.

@valeros Wouldn't the upload with minimum set of commands also include the confirmation to disconnect from the target?

target extended-remote /dev/ttyACM0
monitor swdp_scan
attach 1
load
quit
yes

Here is my output:

$ arm-none-eabi-gdb armstrap_eagle_testprogram.elf
GNU gdb (GNU Tools for ARM Embedded Processors) <IP_ADDRESS>31129-cvs
Copyright (C) 2013 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later http://gnu.org/licenses/gpl.html
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "--host=i686-linux-gnu --target=arm-none-eabi".
For bug reporting instructions, please see:
http://www.gnu.org/software/gdb/bugs/...
Reading symbols from armstrap_eagle_testprogram.elf...done.
(gdb) target extended-remote /dev/ttyACM0
Remote debugging using /dev/ttyACM0
(gdb) monitor swdp_scan
Target voltage: 4.9V
Available Targets:
No. Att Driver
1      STM32F4xx
(gdb) attach 1
Attaching to program: armstrap_eagle_testprogram.elf, Remote target
0x0800161a in delay (ms=121411) at ../source/main.cpp:71
71	    while(ms--) {
(gdb) load
Loading section .isr_vector, size 0x188 lma 0x8000000
Loading section .text, size 0x1ccc lma 0x8000188
Loading section .data, size 0x864 lma 0x8001e54
Start address 0x8001334, load size 9912
Transfer rate: 17 KB/sec, 826 bytes/write.
(gdb) quit
A debugging session is active.
.
Inferior 1 [Remote target] will be detached.
.
Quit anyway? (y or n) y
Detaching from program: armstrap_eagle_testprogram.elf, Remote target
$

@beriberikix Where did you find the link to that example hosted on my s3 account?  It's really old and buggy.  Please consider replacing it with the one in the github repo.   Or at a minimum, change
void loop()
{
    uint32_t counter = 0;
    while (1) {
        counter++;
        GPIO_ResetBits(GPIOC, LEDS);
        GPIO_SetBits(GPIOC, LED[counter % 2]); // ERROR 'LED' array out of bounds referencing
        delay(250);
    };
}

to
void loop()
{
    uint32_t counter = 0;
    while (1) {
        counter++;
        GPIO_ToggleBits(GPIOC, GPIO_Pin_1);
        delay(250);
    };
}

to avoid the out-of-range error you are probably seeing.

GDB does not require confirmations in batch mode.
Here is my log:
Reading symbols from disco_l152rb\firmware.elf...done.
Reset_Handler () at .pioenvs\disco_l152rb\FrameworkCMSISVariant/startup_stm32l1xx_md.S:73
73        movs r1, #0
Loading section .isr_vector, size 0x10c lma 0x8000000
Loading section .text, size 0x288 lma 0x800010c
Start address 0x8000230, load size 916
Transfer rate: 4 KB/sec, 458 bytes/write.
A debugging session is active.
        Inferior 1 [Remote target] will be killed.
Quit anyway? (y or n) [answered Y; input not from terminal]

@valeros You are correct!  Sorry about that.  I had to remove the kill command but running from the cli seems to upload (from an Ubuntu machine) on my end.  Do you have one of the armstrap boards to test?
>$ cat upload.gdb
target extended-remote /dev/ttyACM0
monitor swdp_scan
attach 1
load
detach
quit

>$ arm-none-eabi-gdb armstrap_eagle_testprogram.elf --batch -x upload.gdb
Target voltage: 4.9V
Available Targets:
No. Att Driver
 1      STM32F4xx
0x0800160a in delay (ms=388154) at ../source/main.cpp:71
71	    while(ms--) {
Loading section .isr_vector, size 0x188 lma 0x8000000
Loading section .text, size 0x1ccc lma 0x8000188
Loading section .data, size 0x864 lma 0x8001e54
Start address 0x8001334, load size 9912
Transfer rate: 17 KB/sec, 826 bytes/write.
>$

Here is the output when I have the gdb kill command.  The upload was not success in this case (see below).
>$ cat upload.gdb
target extended-remote /dev/ttyACM0
monitor swdp_scan
attach 1
load
detach
kill
quit

>$ arm-none-eabi-gdb armstrap_eagle_testprogram.elf --batch -x upload.gdb
Target voltage: 4.9V
Available Targets:
No. Att Driver
 1      STM32F4xx
0x08001614 in delay (ms=1332313) at ../source/main.cpp:71
71	    while(ms--) {
Loading section .isr_vector, size 0x188 lma 0x8000000
Loading section .text, size 0x1ccc lma 0x8000188
Loading section .data, size 0x864 lma 0x8001e54
Start address 0x8001334, load size 9912
Transfer rate: 17 KB/sec, 826 bytes/write.
upload.gdb:6: Error in sourced command file:
The program is not being run.
>$

@armstrap Unfortunately, I don't have any armstrap board, maybe @beriberikix can test it.

@armstrap using togglebits fixed it! I originally downloaded it from the Getting Started guide
So to recap:

I'm using the ststm32gdb.py, armstrap.json& armstrap_stm32_flash.ld from 94838565
ststm32gdb-builder.py from 95949898
upload.gdb from 96258195
Modified version of Armstrap blinky examples with the loop() from 96307906

Thanks for the help! Is it possible to roll the gdb commands back into the builder script for future users?


Greatest Common Divisor (Euclidian Algorithm) in Dart

Greatest Common Divisor (Euclidian Algorithm) in Dart
I have written the comments to give a explanation and a proof for the Euclidian algorithm that states that the remainder a' of a/b is also divisible by the GCD of a and b (i.e. d) This single fact is used in the algorithm. The Statement might be confusing but my proof for that will make it easy to understand
My examples explanations illustrates how Time Complexity is O(logn) 😎
Hope you ll like it 😁
review link https://replit.com/@AshutoshKhandua/SaneOrderlyForm
closes #6300

@ankitaggarwal23 should i still delete the test case?
Both are important and serve as an example for my explanation i gave for the algorithm


GUI - Focus - Manual controls increment beyond current SW limit of 12,000 microns.

When the Z-axis reaches its upper limit of travel, the manual "UP" controls can advance the Z-stage beyond its SW set limit of 12,000 microns. Also, set the the stage limit to 14,000 microns.
The 12,000 micron limit was chosen earlier as a hardware-safety precaution.

*

Complete.


On a first launch try to store data on SD or prompt a User to store data on SD card

Users report unexpected data size growth. This is mostly due to the cached attachments.
We need to use SD card for data storage, if possible.
I tend to think that Data storage on SD should be default setting.
@sebasfc I guess 175 of 177 Megabytes are cached images. Do one or more from the below:

You should move data to SD Card: AndStatus settings - Storage...
Decrease Storage - History time
Turn off "Display attached images"
--
andstatus
URL: http://status.vinilox.eu/notice/3126079

Fixed in the latest commit


Versioning

Heyo,
do you have any plans on implementing versioning of documents? Like being able to go back in time. This could be used in one of our ecommerce projects. Versions could enable us to keep the current version in cart while being able to change the product without changing the version that's in the cart.
Have a great day!

Hey, no I'm not planning on implementing versioning


[bug] fremennik medium diary skips brine rat kill step

When doing the brine rat step in the diary helper, it directs to dig by the tree, which is correct. However, immediately after entering the cave, it tells you to exit, instead of killing the brine rat. The helper needs to add the step of actually killing the brine rat in between.

Fixed in https://github.com/Zoinkwiz/quest-helper/commit/cfed4db9847d4e6936280fdf2234ce53c0c3c428


Feature/teeolu/make editor width resizeable

Type of pull request
Specify the type of pull request.

[ ] Bug fix
[x] New feature
[ ] Refactoring

The issue
Decribe (in details) the purpose of the pull request
This PR makes the editor width resizeable so that user can have the screen controlled to whatever width that suites him

The Solution
Describe (in details) your implementation (how you solved the issue)
Add necessary event listeners and anchor elements for the user to be able to achieve this.

Screenshots (if there are changes of UI)

If any changes affect UI or an image will add more context to the solution, please attach a before/after screenshots below.

Task Ticket(s)
Reference link to the issue if any
https://github.com/gbenga504/javico/issues/38

Developer (PR owner) Checklist

[x] Tested changes.
[x] Double-checked target branch

Reviewer Checklist

[x] I understand why and how.

@teeolu, this is not working as it should.


The links  of overview of SkyWalking module [call flow] and [hierarchy]  cannot be openned

The links referenced in the document cannot be opened.
pls click the document url and search keyword: call flow or hierarchy,  then click it
it will show the below error info.

HTTP Status 500 – Internal Server Error
Type Exception Report
Message Servlet execution threw an exception
Description The server encountered an unexpected condition that prevented it from fulfilling the request.
Exception
javax.servlet.ServletException: Servlet execution threw an exception
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
com.gotapi.ca.plain.server.MyFilter.doFilter(MyFilter.java:79)
Root Cause
java.lang.Error: Project 'github:skywalking' has not been compiled yet
com.gotapi.ca.plain.server.ProjectCache.getProject(ProjectCache.java:40)
com.gotapi.ca.plain.server.GithubServlet.doGet(GithubServlet.java:189)
javax.servlet.http.HttpServlet.service(HttpServlet.java:635)
javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
com.gotapi.ca.plain.server.MyFilter.doFilter(MyFilter.java:79)
Note The full stack trace of the root cause is available in the server logs.

Thanks for reporting this, will take a look

@alexkarezin can you please take a look since you added these?

@kezhenxu94 looking at it, will reply in a bit


Support for data-attributes

Hey there,
instead of defining options via javascript it would be awesome to be able to define options via html data-attributes, e.g.

...

May I suggest you check out "data-slick"? This has been added in version 1.5. I.e.:
...

Ah right, thank you. But why didn't you seperated the options in own attributes?