Git Product home page Git Product logo

k-ramel's People

Contributors

afaugeras avatar bpetetot avatar corinnekrych avatar emrysmyrddin avatar fabienjuif avatar greenkeeper[bot] avatar guillaumecrespel avatar okazari avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

k-ramel's Issues

API to add custom actions to state nodes

It could be useful to allow users to define their own custom actions along with the ones already generated by k-redux-factory.

The actions could be then decorated with dispatch function, allowing the user to easily call it from the store

const store = createStore({
  data: simpleObject({ 
    actions: {
      load: () => ({ type: 'REQUEST_DATA' }),
      loaded: (data) => ({ type: 'DATA_LOADED', payload: { data } }),
    },
  }),
})

store.data.loaded()
store.data.load({ hello: 'world' })

Since we want to push the use of the redux-saga like API, we want to be able to dispatch very simple action like simple events. For this, our library can also help the user by generating actions for him. You just give a type name for your action and it generate the action creator for you. The action creators can take an optional payload that will be aded to the action.

const store = createStore({
  data: simpleObject({
    actions: {
      load: 'REQUEST_DATA',
      loaded: 'REQUEST_DATA',
      // Also allows to give a custom action creator implementation
      custom: () => ({ type: 'CUSTOM_ACTION' })
    },
  }),
},{
  listeners: [
    when(store.data.load.type, (action, store) => store.data.loaded({ hello: 'world' }))
    // Dispatch { type: 'DATA_LOADED', payload: { hello: 'world' } }
  ]
})

I'm not entirely sure of the API. In particular, I'm not convinced by the store.data.load.type to get the type name of the action. Perhaps by adding a toString implementation to the function ? Allowing to just do when(store.data.loaded, (...) => ...) ?

Listener "take" with filters

add filters to take helpers

take( ...matches )( ...filters )( reaction )

Test to execute action : (matches1 OR matches2) AND (filter1 AND filter2)

OR

take( ...filters )( ...matches )( reaction )
const takeNoFilter = take()( ...matches )( reaction )
takeNoFilter( ...matches )( reaction )

reducer in first level

This doesn't work (reducer in first level):

    const store = createStore({
      config: { type: 'simpleObject' },
    })

    store.config.set('config me')
    expect({
      state: store.getState(),
      config: store.config.get(),
    }).toMatchSnapshot()

Set the parent action that cause new dispatch in reactions

So it is easier to debug.

{
  type: 'NEW_ACTION_FROM_REACTON', 
  payload: 'reaction payload',
  parent: {
    type: '@@krml/INIT'
  }
}
  • I can't use middlewares
  • I can't use my own dispatch middleware to set parent then run reactions, because of async reaction
  • So I have this in mind right know
  // 1. Attach { getState, dispatch } to each krf reducers
  // 2. krf reducers "toContext" use that instead of given store
  // 3. Have a function to set new { getState, dispatch } to each krf reducers
  // 4. Use this to set store the first time
  // 5. Have a function to clone the reducer tree (each krf) given a the store (clone the store)
  //      /!\ Take care, it should not clone the store (redux one)
  // 6. In listener middleware
  //   a. Clone the store (with all krf reducer cloned)
  //   b. Set the new { getState, dispatch } with enhanced dispatch
  //   c. Pass the new "store" to reactions
  /* const keys = [...Object.keys(reduxStore), 'listeners']
  const reducerTreeKeys = Object.keys(store).filter(key => !keys.includes(key))
  console.log(Object.keys(store.config)) */

takeWith

Context

this issue is about takeWith where currying is reversed from take

  • take: take(filter)(reaction)
  • takeWith: takeWith(reaction)(filter)

The approach is more convenient to write OR:
take version

take(filter1, andFilter2)(reactionImpl)
take(orFilter3)(reactionImpl)

takeWith version

const reaction = takeWith(reactionImpl)
// ...
takeWith(filter1, andFilter2)
takeWith(orFilter3)

So why this takeWith is not in the lib ?

Good question! This is because this example shows that we are not familiar with this pattern, since we can't find a propre name to complete fonction:

// todos.js
import { takeWith } from 'k-simple-state'
 
export const complete = takeWith(action, store) => {
  const { todos } = store.data 
  const todo = todos.get(action.payload)
  todos.set({ ...todos, completed: true })
}

// listeners.js
import { complete } from './todos' 

export default [
  // here it seems odd to me to call a fonction 'complete' passing an action type :)
  complete('@@ui/CLICKED_COMPLETE'),
]

What's next ?

When someone will find a proper naming convention we will write the takeWith and publish it in this lib.
As long as we can't find that we don't publish it 🙂

Source

#26

cc @bpetetot @EmrysMyrddin @guillaumecrespel

dispatch an action when provider HOC has loaded the store

Dispatch an INIT action when the provider has loaded the store to simplify implementations like that :

export default compose(
  provider(store),
  inject(st => ({ load: () => { st.dispatch({ type: '@@ui/APP_LOADED' }) } })),
  loader(),
)(App)

provider could dispatch an actions names :

  • @@kst/STORE_PROVIDED,
  • or @@kst/STORE_LOADED ,
  • or @@kst/INIT

meta+poll / find a name to the lib

Rules:

  • Each comment is a name proposition, vote with 👍 or 👎
  • The name should not have redux in it, so we can change implementation in a near future if we'd like to
  • The name may have a k- in prefix but this is not mandatory
  • To comment a proposition
    • open a new thread that reference the comment
    • the new thread should have label name
  • I will close the thread when I feel we have a good name

Thank for your help everyone.

@delphinemillet @guillaumecrespel @bpetetot @frinyvonnick @EmrysMyrddin

Action required: Greenkeeper could not be activated 🚨

🚨 You need to enable Continuous Integration on all branches of this repository. 🚨

To enable Greenkeeper, you need to make sure that a commit status is reported on all branches. This is required by Greenkeeper because it uses your CI build statuses to figure out when to notify you about breaking changes.

Since we didn’t receive a CI status on the greenkeeper/initial branch, it’s possible that you don’t have CI set up yet. We recommend using Travis CI, but Greenkeeper will work with every other CI service as well.

If you have already set up a CI for this repository, you might need to check how it’s configured. Make sure it is set to run on all new branches. If you don’t want it to run on absolutely every branch, you can whitelist branches starting with greenkeeper/.

Once you have installed and configured CI on this repository correctly, you’ll need to re-trigger Greenkeeper’s initial pull request. To do this, please delete the greenkeeper/initial branch in this repository, and then remove and re-add this repository to the Greenkeeper App’s white list on Github. You'll find this list on your repo or organization’s settings page, under Installed GitHub Apps.

k-rex

#8 (comment)

Because the written code is shorter with this lib than with REduX, and it's more powerful than the T-REX ! And even if you don't use redux in the future, it's still more powerful than the T-REX !

And its a short name :)

Refactor driver interface / behaviour ?

Maybe we should refactor the driver so drivers returns this interface everytime:

  • getEnhancer: returns enhancer
  • getReducer: returns { path, reducer }
  • getDriver: returns driver

And we use them like that:

export default createStore(
  description,
  {
    drivers: [
      http(), 
      form(state => state.form),
      reduxLittleRouter(routes, state => state.router, routerImpl),
    ]
  }
)

And k-ramel use the returned interface to configurate the store where it needs to be, enhancer would be pushed the same order as driver declaration.

Question/discussion: optics.lens and other considerations

seeing the example here

https://github.com/alakarteio/k-simple-state#create-a-simple-store

wouldn't be a good idea to ditch the imperative api to on dispatching lense to the reducers ?

and using the same lense to select the data from the store so it can be used in map state to props etc. ?

Many other toughts store enhancer seems to be a better fit than wrapping a redux store, maybe all this can be achieved using a higher order reducer to and avoid creating a knowledge gap between mainstream redux api and tools (like connect).

having possibility to load the reducers dynamically

k-ramel already propose the ability to load listeners dynamically.

Do you think that it could also load some reducers dynamically in order to have a complete separation of some screens ?

For example, in my app, I have an admin page that managing all my application users. And I have specific reducers (users data, admin screens data) specific to that page. So I could have a container loading k-ramel reducers and listeners specific to it :

import { updateStore, when } from '@k-ramel/react'
import AdminPage from './AdminPage'

updateStore({
  data: { users: { type: 'keyValue', id: 'uid' } },
  ui: { admin: { type: 'simpleObject' } },
}, [
  when('MY_ADMIN_ACTION')(() => { /* do something */ })
]})(AdminPage)

And it could be a great optimisation for apps using code splitting (dynamic imports).

Handle an empty return from inject parameter

An error is thrown if the function given to inject return somehting else than an object.

The simplest example to reproduce :

inject(() => {})(Component)

Should this trhow an error ? A warning ? Nothing ?

name ... again

TODOs

  • Update @@kst actions prefix
  • Update github repo
  • Update link to coveralls
  • Update link to circleCI (should be automated)
  • Update link to greenkeeper
  • Update badges
  • Update documentation
  • Update todomvc (comments)

--

@delphinemillet @guillaumecrespel @bpetetot @frinyvonnick @EmrysMyrddin @AFaugeras @Taranys @Okazari

Hi !

I just changed the name on github.
But I am not fan of this once again.

@delphinemillet said it could be cool to have food name since the organisation is alakarte(io). An I think it's great.

What your tough about it ?
Should we find a name related to food or keep k-rex ?

Vote k-rex: ❤️
Or vote for food name: 👍
-> If you have food name idea feel free to respond to this thread.

Action required: Greenkeeper could not be activated 🚨

🚨 You need to enable Continuous Integration on all branches of this repository. 🚨

To enable Greenkeeper, you need to make sure that a commit status is reported on all branches. This is required by Greenkeeper because it uses your CI build statuses to figure out when to notify you about breaking changes.

Since we didn’t receive a CI status on the greenkeeper/initial branch, it’s possible that you don’t have CI set up yet. We recommend using Travis CI, but Greenkeeper will work with every other CI service as well.

If you have already set up a CI for this repository, you might need to check how it’s configured. Make sure it is set to run on all new branches. If you don’t want it to run on absolutely every branch, you can whitelist branches starting with greenkeeper/.

Once you have installed and configured CI on this repository correctly, you’ll need to re-trigger Greenkeeper’s initial pull request. To do this, please delete the greenkeeper/initial branch in this repository, and then remove and re-add this repository to the Greenkeeper App’s white list on Github. You'll find this list on your repo or organization’s settings page, under Installed GitHub Apps.

Add a reset store function

In different use cases, sometimes, I need to reset the store or a part of the store.

For example, when I switch from a connected user to another I need to reset a huge part of the store and its quite exhaustive to do. Because I have to call each reset() methods of my reducers, or create RESET actions to my custom reducers. And, in the future, if I have to add a new reducer, I dont must forget to reset it when needed.

I was thinking about a method :

  • store.reset() : apply the initial state to the entire store
  • store.reset('path') : apply the initial state from the given path

README.md

  • More examples
    • simpleObject
    • raw reducer
  • Listeners
  • Drivers
  • Dispatch a string
  • INIT event

add redux-form driver

Waiting for #69 so the lib are not requiring redux-form everytime... for everycases.

driver

import { setSubmitSucceeded, getFormValues, setSubmitFailed, startSubmit, stopSubmit, isSubmitting } from 'redux-form'

const asyncSubmit = (name, dispatch, getState) => async (callback, ...options) => {
  dispatch(startSubmit(name))
  await callback(...options)
  if (isSubmitting(name)(getState())) dispatch(stopSubmit)
}

export default ({ dispatch, getState }) => name => ({
  getFormValues: () => getFormValues(name, state => state.ui.form)(getState()),
  setSubmitFailed: (...fields) => dispatch(setSubmitFailed(name, ...fields)),
  setSubmitSucceeded: () => dispatch(setSubmitSucceeded(name)),
  startSubmit: () => dispatch(startSubmit(name)),
  stopSubmit: errors => dispatch(stopSubmit(name, errors)),
  asyncSubmit: (callback, ...options) => asyncSubmit(name, dispatch, getState)(callback, ...options),
})

Example usage in a reaction (plugued to a listener)

export const login = reaction((action, store, { http, form }) => {
  // retrieve credentials from redux
  const signin = form('signin')
  const values = signin.getFormValues()
  // submit
  signin.asyncSubmit(http('AUTH').post, '/api/login')
})

own listen middleware

Something with this API:

import { createStore, take } from 'k-simple-state' 

const store = createStore({
  config: { type: 'simpleObject' },
  save: { type: 'simpleObject' }, 
}, {
  listen: [
    take(/SET_CONFIG$/g, (action, store) => {
      console.log({ action })
      store.save.set('saved')
    }
  ],
})

provide helpers

import { createStore, keyValue, simpleObject } from 'k-simple-state'
 
const store = createStore({
  data: {
    todos: { type: 'keyValue', key: 'id' } // or keyValue({ key: 'id' })
  },
  ui: {
    screens: {
      login,
    },
  },
}, {
  middlewares: [reduxThunk, logger, devtools],
})

handle compose AND applyMiddleware

  • Better understand this in redux
  • Find a way to abstract this ?

This is about this in redux:

const store = createStore(
  reducers,
  initState,
  compose(
    enhancer,
    applyMiddleware(sagaMiddleware, middleware),
    /* eslint-env browser */
    window.devToolsExtension ? window.devToolsExtension() : f => f,
  ),
)

shouldComponentUpdate in inject() must ignore functions

shouldComponentUpdate in inject() must ignore functions.

import { inject } from "k-simple-state/react";

import App from "./app";

const mapProps = ({ getState, dispatch }) => ({
  count: getState().count,
  increment: () => dispatch({ type: "INCREMENT" }),
  decrement: () => dispatch({ type: "DECREMENT" })
});

export default inject(mapProps)(App);

Today shouldComponentUpdate will aways be true due to functions increment and decrement.

Handle an empty parameter for inject

The inject function throws a cryptic error when no parameter is given :

import { inject } from 'k-ramel/react'
import Component from './Component'

export default inject()(Component)

image

krf-hasKey

Add hasKey selector from k-redux-factory.

Wait for #30 to do this

What do you think having drivers available in inject callback ?

I have opened a question, because I don't know if it's the philosophy of the library, but I think it could be useful in some cases.

Simple example :

import { inject } from '@k-ramel/react'
import MyComponent from './myComponent'

inject((store, props, { router }) => ({
   id: router.getParam('id'),
   onClick: () => router.push('/mypath')
}))(MyComponent)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.