diff --git a/src/AddressTypeahead.component.js b/src/AddressTypeahead.component.js new file mode 100644 index 0000000..423556e --- /dev/null +++ b/src/AddressTypeahead.component.js @@ -0,0 +1,43 @@ +// @flow +import { compose, withState, withProps } from 'recompose'; +import React, { Component } from 'react'; + +import { resolveResultbyField } from './finder'; + +const Typeahead = require('react-typeahead').Typeahead; + +type AddressInputType = { + // local state + searchStr: string; + option: string[]; + + // external props + fieldType: string; +} +const AddressTypeaheadComponent = (props: AddressInputType) => { + const { searchStr, setSearchStr, fieldType, options } = props; + if (!fieldType) { + console.warn('No field type provide'); + return
; + } + return ( +
+ setSearchStr(e.target.value)} + /> + +
+ ); +}; + +const AddressTypeahead: Component = compose( + withState('searchStr', 'setSearchStr', ''), + withProps(({ searchStr, fieldType }) => ({ + options: resolveResultbyField(fieldType, searchStr), + })), +)(AddressTypeaheadComponent); + +export default AddressTypeahead; diff --git a/src/finder.js b/src/finder.js new file mode 100644 index 0000000..a9d55a9 --- /dev/null +++ b/src/finder.js @@ -0,0 +1,62 @@ +// @flow +const JQL = require('jqljs'); + +const fieldsEnum = { + DISTRICT: 'd', + AMPHOE: 'a', + PROVINCE: 'p', + ZIPCODE: 'z', +}; + + +/** + * From jquery.Thailand.js line 30 - 128 + * Search result by FieldsType + */ +const preprocess = (data) => { + if (!data[0].length) { + // non-compacted database + return data; + } +// compacted database in hierarchical form of: +// [["province",[["amphur",[["district",["zip"...]]...]]...]]...] + const expanded = []; + data.forEach((provinceEntry) => { + const province = provinceEntry[0]; + const amphurList = provinceEntry[1]; + amphurList.forEach((amphurEntry) => { + const amphur = amphurEntry[0]; + const districtList = amphurEntry[1]; + districtList.forEach((districtEntry) => { + const district = districtEntry[0]; + const zipCodeList = districtEntry[1]; + zipCodeList.forEach((zipCode) => { + expanded.push({ + d: district, + a: amphur, + p: province, + z: zipCode, + }); + }); + }); + }); + }); + return expanded; +}; +const DB = new JQL(preprocess(require('../jquery.Thailand.js/data.json'))); + +const resolveResultbyField = (type: string, searchStr: string) => { + let possibles = []; + try { + possibles = DB.select('*').where(type) + .match(`^${searchStr}`) + .orderBy(type) + .fetch(); + } catch (e) { + throw e; + } + return possibles; +}; + +exports.resolveResultbyField = resolveResultbyField; +exports.fieldsEnum = fieldsEnum; diff --git a/src/index.js b/src/index.js new file mode 100644 index 0000000..0f620d9 --- /dev/null +++ b/src/index.js @@ -0,0 +1,14 @@ +// @flow +import React from 'react'; +import { fieldsEnum, resolveResultbyField } from './finder'; +import AddressTypeahead from './AddressTypeahead.component'; + +export { + +}; + +export default () => ( +
+ +
+);