Files: 9e1760cdb440b581390169946efdd4c5aadefd34 / App.js
2492 bytesRaw
1 | import React, { Component } from 'react'; |
2 | import { |
3 | Button, |
4 | Text, |
5 | TextInput, |
6 | View, |
7 | WebView |
8 | } from 'react-native'; |
9 | import nodejs from 'nodejs-mobile-react-native'; |
10 | import RNFS from 'react-native-fs'; |
11 | |
12 | const BASE_URI = 'http://localhost'; |
13 | |
14 | export default class App extends Component { |
15 | constructor (props) { |
16 | super(props); |
17 | |
18 | this.receiveMessage = this.receiveMessage.bind(this); |
19 | this.request = this.request.bind(this); |
20 | } |
21 | |
22 | state = { |
23 | port: null, |
24 | inputValue: '' |
25 | } |
26 | |
27 | componentWillMount () { |
28 | |
29 | // Start node server |
30 | nodejs.start('main.js'); |
31 | |
32 | // When receive the message from the node, set App path |
33 | nodejs.channel.addListener('message', this.receiveMessage, this); |
34 | } |
35 | |
36 | /** |
37 | * @function receiveMessage |
38 | * @description Receives a message and executes the respective action |
39 | * @param {String} msg JSON stringed message |
40 | */ |
41 | receiveMessage (msg) { |
42 | const { type, data } = JSON.parse(msg); |
43 | |
44 | switch (type) { |
45 | case 'ok': // Send path to the server |
46 | |
47 | const message = JSON.stringify({ |
48 | type: 'path', |
49 | data: RNFS.DocumentDirectoryPath |
50 | }); |
51 | |
52 | nodejs.channel.send(message); |
53 | break; |
54 | |
55 | case 'port': // Received server port to execute requests |
56 | return this.setState({ |
57 | port: data |
58 | }); |
59 | |
60 | case 'error': |
61 | alert(`ERROR: ${JSON.stringify(data)}`); |
62 | break; |
63 | } |
64 | } |
65 | |
66 | /** |
67 | * @function request |
68 | * @description Executes request to the server to load the Dat |
69 | */ |
70 | request () { |
71 | |
72 | // Server port |
73 | const { port, inputValue } = this.state; |
74 | |
75 | if (!port) { |
76 | return alert('Server error.'); |
77 | } |
78 | |
79 | // Uri from the UI |
80 | const uri = `${BASE_URI}:${port}/${inputValue}`; |
81 | |
82 | // Update state to load the Dat |
83 | return this.setState({ uri }); |
84 | } |
85 | |
86 | render() { |
87 | const { inputValue } = this.state; |
88 | |
89 | return ( |
90 | <View style={{ |
91 | paddingTop: 40, |
92 | paddingLeft: 20, |
93 | paddingRight: 20, |
94 | flex: 1, |
95 | justifyContent: 'center' |
96 | }}> |
97 | <TextInput |
98 | defaultValue={ inputValue } |
99 | onChangeText={ value => this.setState({ inputValue: value }) } |
100 | style={{ |
101 | height: 40, |
102 | borderColor: 'gray', |
103 | borderWidth: 1 |
104 | }} /> |
105 | <Button title="Download" |
106 | onPress={ () => this.request() } /> |
107 | |
108 | <WebView style={{ |
109 | flex: 1, |
110 | height: 300 |
111 | }} source={{ uri: this.state.uri }} /> |
112 | </View> |
113 | ); |
114 | } |
115 | } |
Built with git-ssb-web