ADAMKDEAN

Scrollable Grid with React Native

Published Thursday, 25 August 2016

GridView.js

import React, { Component } from 'react'
import {
  AppRegistry,
  ListView,
  Image,
  StyleSheet,
  Text,
  TouchableHighlight,
  View
} from 'react-native'

export default class GridView extends Component {
  constructor(props) {
    super(props)
    const data = props.children || []
    const ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 })
    this.state = {
      dataSource: ds.cloneWithRows(data)
    }

    this._renderRow = this._renderRow.bind(this)
    this._selectItem = this._selectItem.bind(this)
  }

  render() {
    return (
      <View style={styles.mainView}>
        <ListView
          contentContainerStyle={styles.list}
          dataSource={this.state.dataSource}
          renderRow={this._renderRow}
          initialListSize={30}
        />
      </View>
    )
  }

  _renderRow (rowData, sectionId, rowId) {
    const imgSource = { uri: rowData.uri }
    console.log('imgSource', imgSource)
    return (
      <TouchableHighlight
        style={styles.row}
        onPress={() => this._selectItem(rowData)}
        underlayColor='rgba(0,0,0,0)'>
        <View>
          <Image style={styles.thumb} source={imgSource} />
        </View>
      </TouchableHighlight>
    )
  }

  _selectItem (item) {
    // do something with item
    console.log('item selected', item.id, item.uri)
  }
}

const styles = StyleSheet.create({
  mainView: {
    paddingTop: 22,
    flex: 1
  },
  list: {
    justifyContent: 'center',
    flexDirection: 'row',
    flexWrap: 'wrap',
    backgroundColor: '#eeeeee',
    paddingTop: 8,
  },
  row: {
    justifyContent: 'center',
    margin: 6,
    width: 64,
    height: 64,
    alignItems: 'center'
  },
  thumb: {
    width: 64,
    height: 64
  }
})

index.ios.js

'use strict'

import React, { Component } from 'react'
import { AppRegistry, StyleSheet, View, Text } from 'react-native'
import GridView from './GridView'

class ReactApp extends Component {
  constructor(props) {
    super(props)

    this.state = {
      data: []
    }

    for (let i = 0; i < 100; i++) {
      this.state.data.push({
        id: i,
        uri: 'https://facebook.github.io/react/img/logo_og.png'
      })
    }    
  }

  render() {
    return (
      <GridView>{this.state.data}</GridView>
    )
  }
}

AppRegistry.registerComponent('reactapp', () => ReactApp)

Simple navigation with React Native

Published Thursday, 25 August 2016

import React, { Component } from 'react'
import { AppRegistry, Navigator, Text, TouchableHighlight, View } from 'react-native'

class Home extends Component {
  render() {
    return (
      <View>
        <Text>This is HOME.</Text>
        <TouchableHighlight onPress={ () => { this._navigate() }}>
          <Text>Go To About</Text>
        </TouchableHighlight>
      </View>
    )
  }
  _navigate() {
    this.props.navigator.push({
      name: 'About'
    })
  }
}

class About extends Component {
  render() {
    return (
      <View>
        <Text>This is ABOUT.</Text>
        <TouchableHighlight onPress={ () => { this._navigate() }}>
          <Text>Go Back</Text>
        </TouchableHighlight>
      </View>
    )
  }
  _navigate() {
    this.props.navigator.pop()
  }
}

class ReactApp extends Component {
  render() {
    return (
      <Navigator
        style={{ flex: 1, paddingTop: 22  }}
        initialRoute={{ name: 'Home' }}
        renderScene={ this._renderScene } />
    )
  }

  _renderScene(route, navigator) {
    console.log(route)
    if(route.name === 'Home') return <Home navigator={navigator} {...route.passProps} />
    if(route.name === 'About') return <About navigator={navigator} {...route.passProps} />
  }
}

AppRegistry.registerComponent('reactapp', () => ReactApp)

What's in an image?

Published Saturday, 6 August 2016

I saw a post on Imgur the other day – Why do Pixar's movies look so good? – which highlights that Pixar use limited palettes for scenes in order to set the mood. That got me thinking, can colours alone set the mood of an image? Take out the context, and just have those colours, could that image still have a mood?

The post on Imgur gives scenes from various Pixar movies. It then shows a generalised palette beneath it. I've trimmed the palette so we're focusing directly on the scenes. From this scene from The Incredibles, you get a feeling of warmth, energy, heat.

A Before

But what happens if we reorder all the pixels of this image? Do we get the same feeling? Does the image retain it's mood?

A After

The image is still very warm. The limited, warm palette still gives a feeling of warmth, heat, and energy, and you can see that the colours are still evenly distributed. Let's take a look at another image, something a little more sullen.

B Before

We all know that feeling. The drab greys and blues of the office environment. What if we reorder the pixels?

B After

Lots of blue and black. You still get the feeling of it being dull and drab, but could this just as easily be a winters night? Let's see what we get if we process the following image:

Winter Before

Winter After

The blues are a little darker but there isn't much difference between the winter's night and the office environment. Perhaps that says something about office environments.

Next, I have a scene which I found quite interesting.

C Before

There are lots of blues and greens in this image. It reminds me of summer days of my childhood, and perhaps sports days out in the big fields. Strangely, it also reminds me of the colour trends of web design in 2007. Let's have a look at it pixel-a-la-pixel.

C After

Still feels quite fresh but now I'm thinking more of SEGA megadrive games. I'm not sure that this particular image has much moodiness to it. Maybe it's meant to feel fresh and carefree and not have moodiness? Perhaps because there are multiple, different colours in the palette?

Finally, I just want to try one more image.

Rain Before

This rainy picture makes me think of an early autumn shower, maybe around 4pm, dark skies and probably a good time for a cup of tea. What do it's colours say?

Rain After

Interestingly, mostly dark greys, then light grey tones, followed by some shadows and browns. The colours remind me of a city on a Monday.

What do you think? Can colours alone give off a mood?

P.S. You can find the source for this little experiment here.

Invalidate require cache

Published Friday, 1 July 2016

CommonJS, the module format that Node.js uses, caches modules the first time that you require them. In a sense, all required Node.js modules are singletons. Sometimes, this isn't so good. For example, an application library might reload a configuration file everytime it starts up. If you need to run tests, and perhaps change the configuration file each time, then you're going to need to be able to have a fresh require() for each test.

To do this, you need to delete the module from require.cache:

delete require.cache[require.resolve('./path/to/file')]

The following example will show this working:

date.js:

var date = new Date()

module.exports = exports = function (msg) {
  msg = msg || 'n/a'
  return `Generated on ${date.toString()} with: ${msg}`
}

index.js:

var date = require('./date')

console.log(date('first'))

setTimeout(function () {

  delete require.cache[require.resolve('./date.js')]

  date = require('./date')
  console.log(date('2 seconds later'))

}, 2000)

Output:

adam@macbook:test $ node index.js
Generated on Fri Jul 01 2016 15:49:11 GMT+0100 (BST) with: first
Generated on Fri Jul 01 2016 15:49:13 GMT+0100 (BST) with: 2 seconds later

Semantic commit messages

Published Friday, 1 July 2016

I have decided to adopt the following rules for semantic commit messages.

feat: add hat wobble  
^--^  ^------------^  
|     |  
|     +-> Summary in present tense.  
|  
+-------> Type: chore, docs, feat, fix, refactor, style, or test.

Although I sometimes only see chore, docs, feat, and fix, I do think refactor, style and test are useful too.

More examples on behalf of mutewinter:

chore: add Oyster build script  
docs: explain hat wobble  
feat: add beta sequence  
fix: remove broken confirmation message  
refactor: share logic between 4d3d3d3 and flarhgunnstow  
style: convert tabs to spaces  
test: ensure Tayne retains clothing

Code should be self-documenting, but commit messages should allow a developer to completely understand what that patch does. The developer should be able to implement the changes again without looking at the code, just from the commit message. fixed pesky bug doesn't quite cut it.

 
Showing posts 1-5 of 185