Skip to content

Instantly share code, notes, and snippets.

@charypar
Created October 9, 2014 16:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save charypar/6675aedd5410a643d318 to your computer and use it in GitHub Desktop.
Save charypar/6675aedd5410a643d318 to your computer and use it in GitHub Desktop.
React.js editable list component
require! <[react immutable]>
dom = react.DOM
toolbar = require './list-toolbar.ls'
# helper functions
c-map = (f, vec-cursor) --> vec-cursor.map f .to-array!
interlace = (longer, shorter) -->
(flatten zip longer, shorter) ++ (drop shorter.length, longer)
# props:
# items - Vector cursor: Items to render
# class-name - class-name to add to the container
# toolbar - Array of objects
# label - String, button label
# action - "(list component, item index) ->", gets called when the add action
# button is clicked with the list component and the item index
# component - (item) -> component: Function returning a component for item rendering
module.exports = react.create-class do
# Public API
insert-item: (index, item) -->
console.log "Inserting item at index #index", item.toJS!
@props.items.update ~>
it.splice index, 0, item .to-vector!
remove-item: (index) ->
console.log "Removing item at index #index"
@props.items.update ->
it.splice index, 1 .to-vector!
# Internal API
trigger-action: (index) ->
(action) ~> # curry manually, for correct scoping
console.log "Triggering action for item #index"
action this, index
render: ->
dom.div do
class-name: "list #{@props.class-name}"
interlace do
[0 to @props.items.count!] |> map ~>
toolbar do
actions: @props.toolbar
trigger: @trigger-action it
@props.items |> c-map id |> zip [0 til @props.items.count!] |> map ([idx, it]) ~>
dom.div do
class-name: 'item'
dom.span do
class-name: 'item-tools'
dom.button class-name: 'remove', on-click: (~> @remove-item idx), "⨉"
@props.component it
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment