diff --git a/example/README.md b/example/README.md deleted file mode 100644 index 05ddf8d9..00000000 --- a/example/README.md +++ /dev/null @@ -1,27 +0,0 @@ -# Examples - -> There are 3 examples that demonstrate a wide range of use cases fulfilled by this library. - -## HTTP - -- [Simple File Browser Client](http/simple_client) -- [Cross Origin Credentials](http/cross_origin_credentials) -- [Cross Origin Upload](http/cross_origin_file_transfer) - -## WebSocket - -- [Echo](web_socket/echo) - ---- - -To serve the examples: - -Dart 1: - -```bash -pub serve -``` - -Dart 2: TBD - -Then open [http://localhost:8080](http://localhost:8080) in Dartium or your browser of choice. diff --git a/example/common/global_example_menu.dart b/example/common/global_example_menu.dart deleted file mode 100644 index 1e00635a..00000000 --- a/example/common/global_example_menu.dart +++ /dev/null @@ -1,20 +0,0 @@ -import 'dart:html'; - -import 'package:over_react/components.dart' show ErrorBoundary; -import 'package:over_react/react_dom.dart' as react_dom; - -import './global_example_menu_component.dart'; - -void renderGlobalExampleMenu( - {bool nav = true, bool includeServerStatus = false}) { - // Insert a container div within which we will mount the global example menu. - final container = document.createElement('div'); - container.id = 'global-example-menu'; - document.body.insertBefore(container, document.body.firstChild); - - // Use react to render the menu. - final menu = (GlobalExampleMenu() - ..nav = nav - ..includeServerStatus = includeServerStatus)(); - react_dom.render(ErrorBoundary()(menu), container); -} diff --git a/example/common/global_example_menu_component.dart b/example/common/global_example_menu_component.dart deleted file mode 100644 index 8a4e3024..00000000 --- a/example/common/global_example_menu_component.dart +++ /dev/null @@ -1,161 +0,0 @@ -// Copyright 2015 Workiva Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import 'dart:async'; - -import 'package:over_react/over_react.dart'; -import 'package:w_transport/w_transport.dart'; - -// ignore: uri_has_not_been_generated -part 'global_example_menu_component.over_react.g.dart'; - -Future _ping(Uri uri) async { - try { - await Http.get(uri); - return true; - } on RequestException { - return false; - } -} - -Future _pingServer() async => - _ping(Uri.parse('http://localhost:8024/ping')); - -@Factory() -// ignore: undefined_identifier -UiFactory GlobalExampleMenu = - // ignore: undefined_identifier - _$GlobalExampleMenu; - -@Props() -class _$GlobalExampleMenuProps extends UiProps { - bool nav; - bool includeServerStatus; -} - -@State() -class _$GlobalExampleMenuState extends UiState { - bool serverOnline; -} - -@Component2() -class GlobalExampleMenuComponent extends UiStatefulComponent2< - GlobalExampleMenuProps, GlobalExampleMenuState> { - Timer serverPolling; - - @override - get defaultProps => (newProps() - ..nav = true - ..includeServerStatus = false); - - @override - get initialState => (newState()..serverOnline = false); - - @override - void componentDidMount() { - super.componentDidMount(); - - if (props.includeServerStatus) { - _pingServer().then(_updateOnlineStatus); - serverPolling = - Timer.periodic(const Duration(seconds: 4), (Timer timer) async { - final isOnline = await _pingServer(); - - _updateOnlineStatus(isOnline); - }); - } - } - - @override - void componentWillUnmount() { - super.componentWillUnmount(); - - serverPolling?.cancel(); - } - - void _updateOnlineStatus(bool isOnline) { - if (isOnline != state.serverOnline) { - setState(newState()..serverOnline = isOnline); - } - } - - ReactElement _renderServerStatusBanner() { - if (!props.includeServerStatus) return null; - - var classes = ClassNameBuilder() - ..add('server-status') - ..add('online', state.serverOnline); - - var statusDesc = state.serverOnline ? 'online' : 'offline'; - - return (Dom.div()..className = classes.toClassName())( - (Dom.div()..className = 'server-status-light')( - '\u2022', - ), - (Dom.div()..className = 'server-status-desc')( - 'Server $statusDesc', - ), - ); - } - - ReactElement _renderNav() { - if (!props.nav) return null; - - return (Dom.a()..href = '/')( - '\u2190 All Examples', - ); - } - - ReactElement _renderServerTip() { - if (!props.includeServerStatus || state.serverOnline) return null; - - return (Dom.div()..className = 'server-status-tip muted')( - Dom.span()('Run '), - Dom.code()('pub run dart_dev examples'), - Dom.span()(' to serve examples with the server.')); - } - - @override - dynamic render() { - var classes = forwardingClassNameBuilder()..add('global-example-menu'); - - return (Dom.div() - ..modifyProps(addUnconsumedDomProps) - ..className = classes.toClassName())( - (Dom.div()..className = 'container')( - _renderNav(), - _renderServerStatusBanner(), - _renderServerTip(), - ), - ); - } -} - -// AF-3369 This will be removed once the transition to Dart 2 is complete. -class GlobalExampleMenuProps extends _$GlobalExampleMenuProps - with - // ignore: mixin_of_non_class, undefined_class - _$GlobalExampleMenuPropsAccessorsMixin { - // ignore: undefined_identifier, undefined_class, const_initialized_with_non_constant_value - static const PropsMeta meta = _$metaForGlobalExampleMenuProps; -} - -// AF-3369 This will be removed once the transition to Dart 2 is complete. -class GlobalExampleMenuState extends _$GlobalExampleMenuState - with - // ignore: mixin_of_non_class, undefined_class - _$GlobalExampleMenuStateAccessorsMixin { - // ignore: undefined_identifier, undefined_class, const_initialized_with_non_constant_value - static const StateMeta meta = _$metaForGlobalExampleMenuState; -} diff --git a/example/common/loading_component.dart b/example/common/loading_component.dart deleted file mode 100644 index 3b852429..00000000 --- a/example/common/loading_component.dart +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright 2015 Workiva Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import 'dart:html'; - -void removeLoadingOverlay() { - querySelector('#loading-overlay').remove(); -} diff --git a/example/common/typedefs.dart b/example/common/typedefs.dart deleted file mode 100644 index 4fe22d0b..00000000 --- a/example/common/typedefs.dart +++ /dev/null @@ -1,3 +0,0 @@ -import '../http/cross_origin_file_transfer/services/file_transfer.dart'; - -typedef TransferDoneCallback = void Function(FileTransfer transfer); diff --git a/example/http/cross_origin_credentials/README.md b/example/http/cross_origin_credentials/README.md deleted file mode 100644 index 26d649c1..00000000 --- a/example/http/cross_origin_credentials/README.md +++ /dev/null @@ -1,7 +0,0 @@ -Example: Cross Origin Session & Requests with Credentials ---------------------------------------------------------- - -> Establishes a session with and makes requests (with and without credentials) to a cross-domain server that requires credentials. Demonstrates **cross-origin** requests and the usage of the XHR `withCredentials` flag. - - -[< All Examples](../..) \ No newline at end of file diff --git a/example/http/cross_origin_credentials/client.dart b/example/http/cross_origin_credentials/client.dart deleted file mode 100644 index c208e4b4..00000000 --- a/example/http/cross_origin_credentials/client.dart +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright 2015 Workiva Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import 'dart:async'; - -import 'package:w_transport/browser.dart' show configureWTransportForBrowser; - -import '../../common/global_example_menu.dart'; -import '../../common/loading_component.dart'; -import './dom.dart' as dom; -import './service.dart' as service; -import './status.dart' as status; - -/// Setup the example application. -Future main() async { - configureWTransportForBrowser(); - renderGlobalExampleMenu(includeServerStatus: true); - await dom.setupControlBindings(); - removeLoadingOverlay(); - - // Check auth status right away to see if valid session already exists - status.authenticated = await service.checkStatus(); - if (status.authenticated) { - dom.updateAuthenticationStatus(); - dom.updateToggleAuthButton(); - dom.display('Logged in.', isSuccessful: true); - } -} diff --git a/example/http/cross_origin_credentials/dom.dart b/example/http/cross_origin_credentials/dom.dart deleted file mode 100644 index 20fb19ab..00000000 --- a/example/http/cross_origin_credentials/dom.dart +++ /dev/null @@ -1,106 +0,0 @@ -// Copyright 2015 Workiva Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import 'dart:async'; -import 'dart:html'; - -import 'service.dart' as service; -import 'status.dart' as status; - -/// Update the authentication status in the DOM. -void updateAuthenticationStatus() { - final Element containerElement = querySelector('.status-container'); - final Element statusElement = querySelector('.status'); - - if (status.authenticated) { - containerElement.className = containerElement.className - .replaceFirst('unauthenticated', 'authenticated'); - statusElement.text = 'Authenticated'; - } else { - containerElement.className = containerElement.className - .replaceFirst('authenticated', 'unauthenticated'); - statusElement.text = 'Unauthenticated'; - } -} - -/// Toggle between "Login"/"Logout" button. -void updateToggleAuthButton() { - final ButtonElement toggleAuthButton = querySelector('#toggle-auth'); - if (status.authenticated) { - toggleAuthButton.text = 'Logout'; - } else { - toggleAuthButton.text = 'Login'; - } -} - -/// Display a message in the DOM. -void display(String message, {bool isSuccessful}) { - final className = isSuccessful ? 'success' : 'warning'; - final Element elem = querySelector('#response'); - elem.innerHtml = '

$message

\n' + elem.innerHtml; -} - -/// Setup bindings for the controls. -Future setupControlBindings() async { - // Handle login/logout - querySelector('#toggle-auth').onClick.listen((_) async { - if (!status.authenticated) { - try { - if (await service.login()) { - status.authenticated = true; - updateAuthenticationStatus(); - updateToggleAuthButton(); - display('Logged in.', isSuccessful: true); - } else { - display('Failed to login.', isSuccessful: false); - } - } catch (error) { - display('Failed to login: $error', isSuccessful: false); - } - } else { - try { - if (await service.logout()) { - status.authenticated = false; - updateAuthenticationStatus(); - updateToggleAuthButton(); - display('Logged out.', isSuccessful: true); - } else { - display('Failed to logout.', isSuccessful: false); - } - } catch (error) { - display('Failed to logout: $error', isSuccessful: false); - } - } - }); - - // Send a request with credentials (will succeed if authenticated) - querySelector('#make-credentialed-request').onClick.listen((_) async { - try { - final response = await service.makeCredentialedRequest(); - display(response, isSuccessful: true); - } catch (e) { - display(e.toString(), isSuccessful: false); - } - }); - - // Send a request without credentials (will always fail) - querySelector('#make-uncredentialed-request').onClick.listen((_) async { - try { - final response = await service.makeUncredentialedRequest(); - display(response, isSuccessful: true); - } catch (e) { - display(e.toString(), isSuccessful: false); - } - }); -} diff --git a/example/http/cross_origin_credentials/index.html b/example/http/cross_origin_credentials/index.html deleted file mode 100644 index d035a018..00000000 --- a/example/http/cross_origin_credentials/index.html +++ /dev/null @@ -1,47 +0,0 @@ - - - - - - Cross Origin Credentialed Requests | HTTP Example - - - - -
Loading...
- -
-

Cross Origin Credentials

-
-

- Status: Unauthenticated -

-
-
-
-
-
-
-
-
- - - - - - - diff --git a/example/http/cross_origin_credentials/service.dart b/example/http/cross_origin_credentials/service.dart deleted file mode 100644 index 67f21805..00000000 --- a/example/http/cross_origin_credentials/service.dart +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright 2015 Workiva Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import 'dart:async'; - -import 'package:w_transport/w_transport.dart'; - -/// URLs for this cross origin credentials example. -final _authenticationServerUrl = Uri.parse('http://localhost:8024'); -const _pathPrefix = '/example/http/cross_origin_credentials'; -final _sessionUrl = - _authenticationServerUrl.replace(path: '$_pathPrefix/session'); -final _credentialedEndpointUrl = - _authenticationServerUrl.replace(path: '$_pathPrefix/credentialed'); - -/// Send a request to the /session endpoint to check authentication status. -/// Returns true if authenticated, false otherwise. -Future checkStatus() async { - final req = Request()..withCredentials = true; - - try { - final response = await req.get(uri: _sessionUrl); - return response.body.asJson()['authenticated']; - } catch (error) { - // Server probably isn't running - return false; - } -} - -/// Login by sending a POST request to the /session endpoint. -Future login() async { - final req = Request()..withCredentials = true; - Response response; - try { - response = await req.post(uri: _sessionUrl); - } catch (e) { - return false; - } - return response.status == 200 && response.body.asJson()['authenticated']; -} - -/// Logout by sending a request to the /logout endpoint. -Future logout() async { - final req = Request()..withCredentials = true; - Response response; - try { - response = await req.delete(uri: _sessionUrl); - } catch (e) { - return false; - } - return response.status == 200 && !response.body.asJson()['authenticated']; -} - -/// Attempt to make a request that requires credentials. -/// This request sets the `withCredentials` flag, which -/// means the session HTTP cookie (if set) will be included. -/// Thus, if authenticated, this request should succeed. -Future makeCredentialedRequest() async { - final req = Request()..withCredentials = true; - final response = await req.get(uri: _credentialedEndpointUrl); - return response.body.asString(); -} - -/// Attempt to make a request that requires credentials, -/// but without setting the `withCredentials` flag. -/// This request should fail regardless of authentication. -Future makeUncredentialedRequest() async { - // withCredentials is unset by default, so no need to do anything special here - final response = await Http.get(_credentialedEndpointUrl); - return response.body.asString(); -} diff --git a/example/http/cross_origin_credentials/status.dart b/example/http/cross_origin_credentials/status.dart deleted file mode 100644 index b21cd7f2..00000000 --- a/example/http/cross_origin_credentials/status.dart +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright 2015 Workiva Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -/// Whether or not the client is authenticated with the server. -bool authenticated = false; diff --git a/example/http/cross_origin_credentials/style.css b/example/http/cross_origin_credentials/style.css deleted file mode 100644 index 5cb9d674..00000000 --- a/example/http/cross_origin_credentials/style.css +++ /dev/null @@ -1,40 +0,0 @@ -/** - * Copyright 2015 Workiva Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -.actions { - float: left; - width: 300px; -} -.content { - margin-left: 320px; -} -.status-container { - padding: 10px; -} -.status-container.authenticated { - background-color: #c7f6ab; -} -.status-container.unauthenticated { - background-color: #e5e6e3; -} -#response { - width: 100%; - max-height: 500px; - padding: 8px; - font-size: 14px; - line-height: 18px; - overflow: auto; -} \ No newline at end of file diff --git a/example/http/cross_origin_file_transfer/README.md b/example/http/cross_origin_file_transfer/README.md deleted file mode 100644 index f06a4c81..00000000 --- a/example/http/cross_origin_file_transfer/README.md +++ /dev/null @@ -1,9 +0,0 @@ -Example: Cross Origin File Upload & Download --------------------------------------------- - -> This example demonstrates the transfer of files to and from a server via HTTP requests. Additionally, it has the option -to proxy requests through an intermediary server in order to demonstrate the usage of the server-side implementation of -w_transport's HTTP library. - - -[< All Examples](../..) \ No newline at end of file diff --git a/example/http/cross_origin_file_transfer/client.dart b/example/http/cross_origin_file_transfer/client.dart deleted file mode 100644 index f36ed32b..00000000 --- a/example/http/cross_origin_file_transfer/client.dart +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2015 Workiva Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import 'dart:html'; - -import 'package:over_react/components.dart' show ErrorBoundary; -import 'package:over_react/react_dom.dart' as react_dom; -import 'package:w_transport/browser.dart' show configureWTransportForBrowser; - -import '../../common/global_example_menu.dart'; -import '../../common/loading_component.dart'; -import './components/app_component.dart'; - -void main() { - // Setup and bootstrap the react app - configureWTransportForBrowser(); - renderGlobalExampleMenu(includeServerStatus: true); - Element container = querySelector('#app'); - react_dom.render(ErrorBoundary()(App()()), container); - removeLoadingOverlay(); -} diff --git a/example/http/cross_origin_file_transfer/components/app_component.dart b/example/http/cross_origin_file_transfer/components/app_component.dart deleted file mode 100644 index 67489a34..00000000 --- a/example/http/cross_origin_file_transfer/components/app_component.dart +++ /dev/null @@ -1,126 +0,0 @@ -// Copyright 2015 Workiva Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import 'dart:html'; - -import 'package:over_react/over_react.dart'; - -import '../services/proxy.dart' as proxy; -import 'download_page.dart'; -import 'upload_page.dart'; - -// ignore: uri_has_not_been_generated -part 'app_component.over_react.g.dart'; - -/// Main application component. -/// -/// Sets up the file drop zone, file upload, and file download components. -@Factory() -// ignore: undefined_identifier -UiFactory App = - // ignore: undefined_identifier - _$App; - -@Props() -class _$AppProps extends UiProps {} - -@State() -class _$AppState extends UiState { - AppPage page; - bool isProxyEnabled; -} - -@Component2() -class AppComponent extends UiStatefulComponent2 { - @override - get initialState => (newState() - ..page = AppPage.upload - ..isProxyEnabled = proxy.proxyEnabled); - - void _goToUploadPage(SyntheticMouseEvent event) { - event.preventDefault(); - - if (state.page != AppPage.upload) { - setState(newState()..page = AppPage.upload); - } - } - - void _goToDownloadPage(SyntheticMouseEvent event) { - event.preventDefault(); - - if (state.page != AppPage.download) { - setState(newState()..page = AppPage.download); - } - } - - void _toggleProxy(SyntheticFormEvent event) { - CheckboxInputElement target = event.target; - - setState(newState()..isProxyEnabled = target.checked, () { - proxy.toggleProxy(enabled: target.checked); - }); - } - - @override - dynamic render() { - return (Dom.div()..modifyProps(addUnconsumedDomProps))( - Dom.p()( - (Dom.label()..htmlFor = 'proxy')( - (Dom.input() - ..id = 'proxy' - ..type = 'checkbox' - ..checked = state.isProxyEnabled - ..onChange = _toggleProxy)(), - ' Use Proxy Server', - ), - ), - (Dom.div()..className = 'app-nav')( - (Dom.a() - ..href = '#' - ..className = state.page == AppPage.upload ? 'active' : null - ..onClick = _goToUploadPage)( - 'Upload', - ), - (Dom.a() - ..href = '#' - ..className = state.page == AppPage.download ? 'active' : null - ..onClick = _goToDownloadPage)( - 'Download', - ), - ), - (UploadPage()..isActive = state.page == AppPage.upload)(), - (DownloadPage()..isActive = state.page == AppPage.download)(), - ); - } -} - -/// The possible values for [AppState.page]. -enum AppPage { - upload, - download, -} - -// AF-3369 This will be removed once the transition to Dart 2 is complete. -// ignore: mixin_of_non_class, undefined_class -class AppProps extends _$AppProps with _$AppPropsAccessorsMixin { - // ignore: undefined_identifier, undefined_class, const_initialized_with_non_constant_value - static const PropsMeta meta = _$metaForAppProps; -} - -// AF-3369 This will be removed once the transition to Dart 2 is complete. -// ignore: mixin_of_non_class, undefined_class -class AppState extends _$AppState with _$AppStateAccessorsMixin { - // ignore: undefined_identifier, undefined_class, const_initialized_with_non_constant_value - static const StateMeta meta = _$metaForAppState; -} diff --git a/example/http/cross_origin_file_transfer/components/download_page.dart b/example/http/cross_origin_file_transfer/components/download_page.dart deleted file mode 100644 index 3ea87a53..00000000 --- a/example/http/cross_origin_file_transfer/components/download_page.dart +++ /dev/null @@ -1,244 +0,0 @@ -// Copyright 2015 Workiva Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import 'dart:async'; -import 'dart:math' as math; - -import 'package:collection/collection.dart'; -import 'package:over_react/over_react.dart'; -import 'package:w_transport/w_transport.dart'; - -import '../services/file_transfer.dart'; -import '../services/remote_files.dart'; -import 'file_transfer_list_component.dart'; - -// ignore: uri_has_not_been_generated -part 'download_page.over_react.g.dart'; - -final _gb = math.pow(2, 30); -final _mb = math.pow(2, 20); -final _kb = math.pow(2, 10); - -String _humanizeFileSize(int bytes) { - double size = bytes.toDouble(); - String unit = 'bytes'; - - // GB - if (bytes > _gb) { - size = bytes / _gb; - unit = 'GB'; - } - - // MB - else if (bytes > _mb) { - size = bytes / _mb; - unit = 'MB'; - } - - // KB - else if (bytes > _kb) { - size = bytes / _kb; - unit = 'KB'; - } - - return '${size.toStringAsFixed(1)} $unit'; -} - -@Factory() -// ignore: undefined_identifier -UiFactory DownloadPage = - // ignore: undefined_identifier - _$DownloadPage; - -@Props() -class _$DownloadPageProps extends UiProps { - bool isActive; -} - -@State() -class _$DownloadPageState extends UiState { - /// List of in-progress or completed downloads. - List downloads; - - /// Error (if any) when trying to communicate with the remote files server. - RequestException error; - - /// List of descriptions of files on the remote server. - List fileDescriptions; -} - -@Component2() -class DownloadPageComponent - extends UiStatefulComponent2 { - RemoteFiles remoteFiles; - StreamSubscription fileStreamSubscription; - StreamSubscription fileStreamErrorSubscription; - - @override - get defaultProps => (newProps()..isActive = false); - - @override - get initialState => (newState() - ..downloads = const [] - ..fileDescriptions = const []); - - @override - void componentDidMount() { - super.componentDidMount(); - - remoteFiles = RemoteFiles.connect(); - fileStreamSubscription = remoteFiles.stream - .listen((List fileDescriptions) { - var stateToSet = newState(); - - if (!const ListEquality() - .equals(fileDescriptions, state.fileDescriptions)) { - stateToSet.fileDescriptions = fileDescriptions; - } - - if (state.error != null) { - stateToSet.error = null; - } - - if (stateToSet != null) { - setState(stateToSet); - } - }); - fileStreamErrorSubscription = remoteFiles.errorStream.listen((error) { - if (state.error != error) { - setState(newState()..error = error); - } - }); - } - - @override - void componentWillUnmount() { - super.componentWillUnmount(); - - remoteFiles.close(); - fileStreamSubscription.cancel(); - fileStreamErrorSubscription.cancel(); - } - - Function _createDownloadFileCallback(RemoteFileDescription rfd) { - return (SyntheticMouseEvent event) { - event.preventDefault(); - _downloadFile(rfd); - }; - } - - void _deleteAllRemoteFiles(SyntheticMouseEvent event) { - event.preventDefault(); - RemoteFiles.deleteAll(); - } - - void _downloadFile(RemoteFileDescription rfd) { - final downloads = List.from(state.downloads); - downloads.add(Download.start(rfd)); - setState(newState()..downloads = downloads); - } - - /// Called when the file transfer list component is done with the transfer - /// and no longer needs to display it, meaning we can remove it - /// from memory. - void _removeDownload(FileTransfer transfer) { - final downloads = []; - downloads.addAll(state.downloads); - downloads.remove(transfer); - setState(newState()..downloads = downloads); - } - - @override - dynamic render() { - var classes = forwardingClassNameBuilder()..add('hidden', !props.isActive); - - return (Dom.div() - ..modifyProps(addUnconsumedDomProps) - ..className = classes.toClassName() - ..aria.hidden = !props.isActive)( - Dom.h2()('File Downloads'), - (Dom.p()..className = 'note')(''' - Note: Loading large files into memory will crash the browser tab. - For this reason, downloads will be canceled automatically if a - concurrent file transfer size of 75 MB is exceeded. - '''), - (FileTransferList() - ..transfers = state.downloads - ..onTransferDone = _removeDownload)(), - Dom.h3()('Remote Files'), - Dom.p()( - (Dom.span()..className = 'muted d-block')( - 'Click a file to download it. ', - ), - (Dom.a() - ..href = '#' - ..onClick = _deleteAllRemoteFiles)( - 'Click here to delete all remote files.', - ), - ), - _renderErrorMessage(), - (Dom.div()..className = 'files clear')( - _renderFileDescriptionLinks(), - ), - ); - } - - ReactElement _renderErrorMessage() { - if (state.error == null) return null; - - return (Dom.p()..className = 'error')( - 'Could not retrieve the remote file list from the server.', - ); - } - - List _renderFileDescriptionLinks() { - if (state.fileDescriptions.isEmpty) return null; - - final fileDescriptionLinks = []; - for (var fileDescription in state.fileDescriptions) { - fileDescriptionLinks.add((Dom.a() - ..key = fileDescription.name - ..className = 'file' - ..href = '#' - ..onClick = _createDownloadFileCallback(fileDescription))( - (Dom.div()..className = 'file-name')( - fileDescription.name, - ), - (Dom.div()..className = 'file-size')( - _humanizeFileSize(fileDescription.size), - ), - )); - } - - return fileDescriptionLinks; - } -} - -// AF-3369 This will be removed once the transition to Dart 2 is complete. -class DownloadPageProps extends _$DownloadPageProps - with - // ignore: mixin_of_non_class, undefined_class - _$DownloadPagePropsAccessorsMixin { - // ignore: undefined_identifier, undefined_class, const_initialized_with_non_constant_value - static const PropsMeta meta = _$metaForDownloadPageProps; -} - -// AF-3369 This will be removed once the transition to Dart 2 is complete. -class DownloadPageState extends _$DownloadPageState - with - // ignore: mixin_of_non_class, undefined_class - _$DownloadPageStateAccessorsMixin { - // ignore: undefined_identifier, undefined_class, const_initialized_with_non_constant_value - static const StateMeta meta = _$metaForDownloadPageState; -} diff --git a/example/http/cross_origin_file_transfer/components/drop_zone_component.dart b/example/http/cross_origin_file_transfer/components/drop_zone_component.dart deleted file mode 100644 index 86e8ed1e..00000000 --- a/example/http/cross_origin_file_transfer/components/drop_zone_component.dart +++ /dev/null @@ -1,212 +0,0 @@ -// Copyright 2015 Workiva Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import 'dart:async'; -import 'dart:html'; - -import 'package:over_react/over_react.dart'; - -import '../services/file_transfer.dart'; - -// ignore: uri_has_not_been_generated -part 'drop_zone_component.over_react.g.dart'; - -typedef NewUploadsCallback = dynamic Function(List uploads); -typedef DragEventCallback = dynamic Function(Event event); - -/// File drop zone. -/// -/// * Listens to drag and drop events and accepts one or many dropped files. -/// * Uploads each dropped file to a server via a POST request with a FormData payload. -@Factory() -// ignore: undefined_identifier -UiFactory DropZone = - // ignore: undefined_identifier - _$DropZone; - -@Props() -class _$DropZoneProps extends UiProps { - @requiredProp - NewUploadsCallback onNewUploads; - @requiredProp - DragEventCallback onNativeDragStart; - @requiredProp - DragEventCallback onNativeDragEnd; -} - -@State() -class _$DropZoneState extends UiState { - /// True when user is dragging something over the drop zone - bool overDropZone; - - /// True when user is dragging something onto the drop target - bool overDropTarget; -} - -@Component2() -class DropZoneComponent - extends UiStatefulComponent2 { - Timer _hideDropTargetTimer; - - @override - get initialState => (newState() - ..overDropZone = false - ..overDropTarget = false); - - @override - void componentDidMount() { - super.componentDidMount(); - - // Show the drop zone and drop target whenever a user - // drags something onto the document. - document.addEventListener('dragover', showDropTarget); - document.addEventListener('dragleave', hideDropTarget); - document.addEventListener('drop', preventNavigateOnDrop); - } - - @override - void componentWillUnmount() { - super.componentWillUnmount(); - - document.removeEventListener('dragover', showDropTarget); - document.removeEventListener('dragleave', hideDropTarget); - document.removeEventListener('drop', preventNavigateOnDrop); - } - - void showDropTarget(Event e) { - e.preventDefault(); - _hideDropTargetTimer?.cancel(); - props.onNativeDragStart(e); - - if (!state.overDropZone) { - setState(newState()..overDropZone = true); - } - } - - void hideDropTarget(Event e) { - // Delay this action slightly to allow it to be canceled. - // This helps prevent a flicker when moving from the drop zone - // to the drop target. - _hideDropTargetTimer = Timer(const Duration(milliseconds: 100), () { - props.onNativeDragEnd(e); - - if (state.overDropZone) { - setState(newState()..overDropZone = false); - } - }); - } - - void preventNavigateOnDrop(Event e) { - e.preventDefault(); - hideDropTarget(e); - } - - void enlargeDropTarget(SyntheticMouseEvent e) { - // Prevent default to allow the drop - e.preventDefault(); - - var stateToSet = newState(); - - if (!state.overDropTarget) { - stateToSet.overDropTarget = true; - } - - if (!state.overDropZone) { - stateToSet.overDropZone = true; - } - - if (stateToSet != null) { - setState(stateToSet); - } - } - - void shrinkDropTarget(_) { - var stateToSet = newState(); - - if (state.overDropTarget) { - stateToSet.overDropTarget = false; - } - - if (!state.overDropZone) { - stateToSet.overDropZone = true; - } - - if (stateToSet != null) { - setState(stateToSet); - } - } - - void uploadFiles(SyntheticMouseEvent e) { - // Prevent drop from propagating to the browser, - // which would normally navigate to the dropped file. - e.preventDefault(); - - // Start an upload for each dropped file - List newUploads = e.dataTransfer.files.map((file) { - return Upload.start(file); - }).toList(); - - // Notify parent of new uploads - props.onNewUploads(newUploads); - props.onNativeDragEnd(null); - - var stateToSet = newState(); - - if (state.overDropTarget) { - stateToSet.overDropTarget = false; - } - - if (state.overDropZone) { - stateToSet.overDropZone = false; - } - - if (stateToSet != null) { - setState(stateToSet); - } - } - - @override - dynamic render() { - var dropZoneClasses = forwardingClassNameBuilder() - ..add('drop-zone') - ..add('active', state.overDropZone || state.overDropTarget); - - var dropTargetClasses = ClassNameBuilder() - ..add('drop-target') - ..add('show', state.overDropZone || state.overDropTarget) - ..add('over', state.overDropTarget); - - return (Dom.div() - ..modifyProps(addUnconsumedDomProps) - ..className = dropZoneClasses.toClassName())((Dom.div() - ..className = dropTargetClasses.toClassName() - ..onDragOver = enlargeDropTarget - ..onDragLeave = shrinkDropTarget - ..onDrop = uploadFiles)('Drop Here to Upload')); - } -} - -// AF-3369 This will be removed once the transition to Dart 2 is complete. -// ignore: mixin_of_non_class, undefined_class -class DropZoneProps extends _$DropZoneProps with _$DropZonePropsAccessorsMixin { - // ignore: undefined_identifier, undefined_class, const_initialized_with_non_constant_value - static const PropsMeta meta = _$metaForDropZoneProps; -} - -// AF-3369 This will be removed once the transition to Dart 2 is complete. -// ignore: mixin_of_non_class, undefined_class -class DropZoneState extends _$DropZoneState with _$DropZoneStateAccessorsMixin { - // ignore: undefined_identifier, undefined_class, const_initialized_with_non_constant_value - static const StateMeta meta = _$metaForDropZoneState; -} diff --git a/example/http/cross_origin_file_transfer/components/file_transfer_list_component.dart b/example/http/cross_origin_file_transfer/components/file_transfer_list_component.dart deleted file mode 100644 index 077bfa08..00000000 --- a/example/http/cross_origin_file_transfer/components/file_transfer_list_component.dart +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright 2015 Workiva Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import 'package:over_react/over_react.dart'; - -import '../../../common/typedefs.dart'; -import '../services/file_transfer.dart'; -import 'file_transfer_list_item_component.dart'; - -// ignore: uri_has_not_been_generated -part 'file_transfer_list_component.over_react.g.dart'; - -/// List of all file uploads. -@Factory() -// ignore: undefined_identifier -UiFactory FileTransferList = - // ignore: undefined_identifier - _$FileTransferList; - -@Props() -class _$FileTransferListProps extends UiProps { - List transfers; - String noTransfersMessage; - bool hideChildrenFromPointerEvents; - @requiredProp - TransferDoneCallback onTransferDone; -} - -@Component2() -class FileTransferListComponent extends UiComponent2 { - @override - get defaultProps => (newProps() - ..transfers = const [] - ..noTransfersMessage = 'There are no pending transfers.' - ..hideChildrenFromPointerEvents = false); - - @override - dynamic render() { - if (props.transfers.isEmpty) { - return (Dom.p()..className = 'muted')(props.noTransfersMessage); - } - - var classes = forwardingClassNameBuilder() - ..add('transfers') - ..add('no-pointer-events', props.hideChildrenFromPointerEvents); - - return (Dom.ul() - ..modifyProps(addUnconsumedDomProps) - ..className = classes.toClassName())( - _renderFileTransferItems(), - ); - } - - List _renderFileTransferItems() { - return props.transfers.map((transfer) { - return (FileTransferListItem() - ..key = transfer.id - ..transfer = transfer - ..onTransferDone = props.onTransferDone)(); - }).toList(); - } -} - -// AF-3369 This will be removed once the transition to Dart 2 is complete. -class FileTransferListProps extends _$FileTransferListProps - with - // ignore: mixin_of_non_class, undefined_class - _$FileTransferListPropsAccessorsMixin { - // ignore: undefined_identifier, undefined_class, const_initialized_with_non_constant_value - static const PropsMeta meta = _$metaForFileTransferListProps; -} diff --git a/example/http/cross_origin_file_transfer/components/file_transfer_list_item_component.dart b/example/http/cross_origin_file_transfer/components/file_transfer_list_item_component.dart deleted file mode 100644 index 9d11d97c..00000000 --- a/example/http/cross_origin_file_transfer/components/file_transfer_list_item_component.dart +++ /dev/null @@ -1,184 +0,0 @@ -// Copyright 2015 Workiva Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import 'dart:async'; - -import 'package:over_react/over_react.dart'; - -import '../../../common/typedefs.dart'; -import '../services/file_transfer.dart'; - -// ignore: uri_has_not_been_generated -part 'file_transfer_list_item_component.over_react.g.dart'; - -const Duration _transferCompleteLingerDuration = Duration(seconds: 4); -const Duration _transferCompleteFadeoutDuration = Duration(seconds: 2); - -/// A single file upload or download. -/// -/// Contains the file name, a progressbar, and a control -/// that allows cancellation of the upload or download. -@Factory() -// ignore: undefined_identifier -UiFactory FileTransferListItem = - // ignore: undefined_identifier - _$FileTransferListItem; - -@Props() -class _$FileTransferListItemProps extends UiProps { - FileTransfer transfer; - @requiredProp - TransferDoneCallback onTransferDone; -} - -@State() -class _$FileTransferListItemState extends UiState { - FileTransferItemStatus status; -} - -@Component2() -class FileTransferListItemComponent extends UiStatefulComponent2< - FileTransferListItemProps, FileTransferListItemState> { - bool get fileTransferIsDone => - state.status == FileTransferItemStatus.doneSuccess || - state.status == FileTransferItemStatus.doneFailure; - - @override - get initialState => (newState()..status = FileTransferItemStatus.idle); - - @override - void componentDidMount() { - super.componentDidMount(); - - if (props.transfer != null) { - props.transfer.progressStream.listen((_) => forceUpdate()); - props.transfer.done - .then((_) => _transferSucceeded()) - .catchError((error, sT) => _transferFailed(error, sT)); - } - } - - /// Abort the file transfer (if it's still in progress) - void _cancelTransfer(SyntheticMouseEvent event) { - event.preventDefault(); - - if (props.transfer == null || fileTransferIsDone) return; - - props.transfer.cancel('User canceled the file transfer.'); - - setState(newState()..status = FileTransferItemStatus.doneFailure); - } - - void _transferSucceeded() { - if (state.status != FileTransferItemStatus.doneSuccess) { - setState(newState()..status = FileTransferItemStatus.doneSuccess); - } - - _fadeTransferOut().then((_) => _removeTransfer()); - } - - void _transferFailed(error, [StackTrace sT]) { - print('Transfer failed: $error'); - if (sT != null) { - print('$sT'); - } - - if (state.status != FileTransferItemStatus.doneFailure) { - setState(newState()..status = FileTransferItemStatus.doneFailure); - } - - _fadeTransferOut().then((_) => _removeTransfer()); - } - - Future _fadeTransferOut() async { - // wait a few seconds before beginning to fade the item out - await Future.delayed(_transferCompleteLingerDuration); - - setState(newState()..status = FileTransferItemStatus.willRemove); - - // wait for the css transition to complete - await Future.delayed(_transferCompleteFadeoutDuration); - } - - void _removeTransfer() { - props.onTransferDone(props.transfer); - } - - @override - dynamic render() { - if (props.transfer == null) return false; - - var classes = forwardingClassNameBuilder() - ..add('success done', state.status == FileTransferItemStatus.doneSuccess) - ..add('error done', state.status == FileTransferItemStatus.doneFailure) - ..add('hide', state.status == FileTransferItemStatus.willRemove); - - return (Dom.li() - ..modifyProps(addUnconsumedDomProps) - ..className = classes.toClassName())( - (Dom.div()..className = 'name')( - _renderTransferItemLabel(), - ), - (Dom.div()..className = 'progress')((Dom.div() - ..role = 'progress' - ..className = 'progress-bar' - ..style = {'width': '${props.transfer.percentComplete}%'} - ..aria.valuemin = 0 - ..aria.valuemax = 100 - ..aria.valuenow = props.transfer.percentComplete)()), - ); - } - - dynamic _renderTransferItemLabel() { - final label = [props.transfer.name]; - if (!fileTransferIsDone) { - label.addAll([ - ' (', - (Dom.a() - ..key = 'cancel-transfer-link' - ..href = '#' - ..onClick = _cancelTransfer)('cancel'), - ')', - ]); - } - - return label; - } -} - -/// The possible values for [FileTransferListItemState.status]. -enum FileTransferItemStatus { - idle, - doneSuccess, - doneFailure, - willRemove, -} - -// AF-3369 This will be removed once the transition to Dart 2 is complete. -class FileTransferListItemProps extends _$FileTransferListItemProps - with - // ignore: mixin_of_non_class, undefined_class - _$FileTransferListItemPropsAccessorsMixin { - // ignore: undefined_identifier, undefined_class, const_initialized_with_non_constant_value - static const PropsMeta meta = _$metaForFileTransferListItemProps; -} - -// AF-3369 This will be removed once the transition to Dart 2 is complete. -class FileTransferListItemState extends _$FileTransferListItemState - with - // ignore: mixin_of_non_class, undefined_class - _$FileTransferListItemStateAccessorsMixin { - // ignore: undefined_identifier, undefined_class, const_initialized_with_non_constant_value - static const StateMeta meta = _$metaForFileTransferListItemState; -} diff --git a/example/http/cross_origin_file_transfer/components/upload_page.dart b/example/http/cross_origin_file_transfer/components/upload_page.dart deleted file mode 100644 index 65992681..00000000 --- a/example/http/cross_origin_file_transfer/components/upload_page.dart +++ /dev/null @@ -1,121 +0,0 @@ -// Copyright 2015 Workiva Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import 'package:over_react/over_react.dart'; - -import '../services/file_transfer.dart'; -import 'drop_zone_component.dart'; -import 'file_transfer_list_component.dart'; - -// ignore: uri_has_not_been_generated -part 'upload_page.over_react.g.dart'; - -@Factory() -// ignore: undefined_identifier -UiFactory UploadPage = - // ignore: undefined_identifier - _$UploadPage; - -@Props() -class _$UploadPageProps extends UiProps { - bool isActive; -} - -@State() -class _$UploadPageState extends UiState { - bool isDragging; - List uploads; -} - -@Component2() -class UploadPageComponent - extends UiStatefulComponent2 { - @override - get defaultProps => (newProps()..isActive = true); - - @override - get initialState => (newState() - ..isDragging = false - ..uploads = const []); - - /// Listen for new file uploads and forward them to the file transfer list component. - void _newUploads(List newUploads) { - final uploads = []; - uploads.addAll(state.uploads); - uploads.addAll(newUploads); - setState(newState()..uploads = uploads); - } - - /// Called when the file transfer list component is done with the transfer - /// and no longer needs to display it, meaning we can remove it - /// from memory. - void _removeUpload(FileTransfer transfer) { - final uploads = []; - uploads.addAll(state.uploads); - uploads.remove(transfer); - setState(newState()..uploads = uploads); - } - - void _dragStart(_) { - if (state.isDragging) return; - - setState(newState()..isDragging = true); - } - - void _dragEnd(_) { - if (!state.isDragging) return; - - setState(newState()..isDragging = false); - } - - @override - dynamic render() { - var classes = forwardingClassNameBuilder()..add('hidden', !props.isActive); - - return (Dom.div() - ..modifyProps(addUnconsumedDomProps) - ..className = classes.toClassName() - ..aria.hidden = !props.isActive)( - Dom.h2()('File Uploads'), - (DropZone() - ..onNewUploads = _newUploads - ..onNativeDragStart = _dragStart - ..onNativeDragEnd = _dragEnd)(), - (FileTransferList() - ..transfers = state.uploads - ..onTransferDone = _removeUpload - ..hideChildrenFromPointerEvents = state.isDragging - ..noTransfersMessage = - 'There are no pending uploads. Drag and drop some files to upload them.')(), - ); - } -} - -// AF-3369 This will be removed once the transition to Dart 2 is complete. -class UploadPageProps extends _$UploadPageProps - with - // ignore: mixin_of_non_class, undefined_class - _$UploadPagePropsAccessorsMixin { - // ignore: undefined_identifier, undefined_class, const_initialized_with_non_constant_value - static const PropsMeta meta = _$metaForUploadPageProps; -} - -// AF-3369 This will be removed once the transition to Dart 2 is complete. -class UploadPageState extends _$UploadPageState - with - // ignore: mixin_of_non_class, undefined_class - _$UploadPageStateAccessorsMixin { - // ignore: undefined_identifier, undefined_class, const_initialized_with_non_constant_value - static const StateMeta meta = _$metaForUploadPageState; -} diff --git a/example/http/cross_origin_file_transfer/index.html b/example/http/cross_origin_file_transfer/index.html deleted file mode 100644 index 02998254..00000000 --- a/example/http/cross_origin_file_transfer/index.html +++ /dev/null @@ -1,44 +0,0 @@ - - - - - - Cross Origin File Transfer | HTTP Example - - - - -
Loading...
- -
-

Cross Origin File Transfer

-

- Drag and drop files to upload them to a server via HTTP. Once files have been uploaded, they can be downloaded to the client. - This example uses the client-side implementation of WRequest and WResponse to transfer files to and from the server. - If you choose to enable the proxy server, all requests will go through the proxy instead of directly to the file server. - This effectively tests the server-side implementation of WRequest and WStreamedResponse since the - proxy server uses it to communicate with the file server. -

-
-
- - - - - - - diff --git a/example/http/cross_origin_file_transfer/services/file_transfer.dart b/example/http/cross_origin_file_transfer/services/file_transfer.dart deleted file mode 100644 index d7b9b7b1..00000000 --- a/example/http/cross_origin_file_transfer/services/file_transfer.dart +++ /dev/null @@ -1,158 +0,0 @@ -// Copyright 2015 Workiva Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import 'dart:async'; -import 'dart:html'; -import 'dart:math' as math; - -import 'package:w_transport/w_transport.dart'; - -import 'proxy.dart'; -import 'remote_files.dart'; - -// Counter used to create unique upload IDs. -int _transferNum = 0; - -// Current number of bytes in memory from concurrent file transfers. -int _concurrentFileTransferSize = 0; - -// Maximum number of bytes from concurrent file transfers that can be -// loaded into memory before potentially crashing the browser tab. -final int _concurrentFileTransferSizeLimit = math.pow(2, 20) * 75; // 75 MB - -/// Encapsulates the file upload to or file download from the server. -class FileTransfer { - BaseRequest _request; - bool _canceled; - - FileTransfer(this.name) - : id = 'fileTransfer${_transferNum++}', - _canceled = false, - _doneCompleter = Completer(), - _percentComplete = 0.0; - - /// Unique file transfer identifier. - final String id; - - /// Name of the file being transferred. - final String name; - - /// Stream of ProgressEvents that may be used to monitor upload progress. - Stream get progressStream => _progressStream; - Stream _progressStream; - - /// Current completion percentage. - double get percentComplete => _percentComplete; - double _percentComplete; - - /// Whether or not the request has finished. - Future get done => _doneCompleter.future; - Completer _doneCompleter; - - /// Cancel the request (will do nothing if the request has already finished). - void cancel(String reason) { - _canceled = true; - _request.abort(reason != null ? Exception(reason) : null); - } - - void _progressListener(RequestProgress progress) { - if (_canceled) return; - _percentComplete = progress.percent; - } -} - -/// Encapsulates the upload of a file from the client to the server. -class Upload extends FileTransfer { - /// Construct a new file upload. - Upload._fromFile(File file) : super(file.name) { - // Prepare the upload request. - _request = MultipartRequest() - ..uri = getUploadEndpointUrl() - ..fields['datetime'] = DateTime.now().toIso8601String() - ..files['file'] = file; - - // Convert the progress stream into a broadcast stream to - // allow multiple listeners. - _progressStream = _request.uploadProgress.asBroadcastStream(); - _progressStream.listen(_progressListener); - - // Send the request. - _request - .post() - .then((_) => _doneCompleter.complete()) - .catchError((error, sT) => _doneCompleter.completeError(error, sT)); - } - - /// Start a new file upload. This will begin the upload to the server immediately. - static Upload start(File file) { - return Upload._fromFile(file); - } -} - -class Download extends FileTransfer { - int _bytesLoaded; - - /// Construct a new file download. - Download._ofRemoteFile(RemoteFileDescription rfd) : super(rfd.name) { - _bytesLoaded = 0; - - // Prepare the download request. - _request = Request()..uri = getDownloadEndpointUrl(rfd.name); - - // Convert the progress stream into a broadcast stream to - // allow multiple listeners. - _progressStream = _request.downloadProgress.asBroadcastStream(); - _progressStream.listen(_progressListener); - - _progressStream.listen((RequestProgress progress) { - if (_canceled) return; - - if (progress.lengthComputable) { - int delta = progress.loaded - _bytesLoaded; - _concurrentFileTransferSize += delta; - - // When dealing with large (or many) files, it's possible that - // we can run out of memory. Cancel requests after a certain threshold. - if (_concurrentFileTransferSize > _concurrentFileTransferSizeLimit) { - cancel( - 'Maximum concurrent file transfer size exceeded. Large files cannot be loaded into memory.'); - } - - _bytesLoaded = progress.loaded; - } - }); - - // Send the request. - _request.get().then((Response response) { - _doneCompleter.complete(); - }, onError: (error) { - _doneCompleter.completeError(error); - }); - - done.then((_) { - _concurrentFileTransferSize -= _bytesLoaded; - }, onError: (_) { - _concurrentFileTransferSize -= _bytesLoaded; - }); - } - - /// File being downloaded. - File get file => _file; - File _file; - - /// Start a new file download. This will begin the download from the server immediately. - static Download start(RemoteFileDescription rfd) { - return Download._ofRemoteFile(rfd); - } -} diff --git a/example/http/cross_origin_file_transfer/services/proxy.dart b/example/http/cross_origin_file_transfer/services/proxy.dart deleted file mode 100644 index f9ecfa27..00000000 --- a/example/http/cross_origin_file_transfer/services/proxy.dart +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright 2015 Workiva Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Whether or not to route requests through a proxy server. -bool proxyEnabled = false; - -void toggleProxy({bool enabled = false}) { - proxyEnabled = enabled; -} - -String getServerUrl() { - final base = - proxyEnabled ? 'http://localhost:8024/proxy' : 'http://localhost:8024'; - return '$base/example/http/cross_origin_file_transfer'; -} - -Uri getDownloadEndpointUrl(String name) { - return Uri.parse('${getServerUrl()}/download?file=$name'); -} - -Uri getFilesEndpointUrl() { - return Uri.parse('${getServerUrl()}/files/'); -} - -Uri getUploadEndpointUrl() { - return Uri.parse('${getServerUrl()}/upload'); -} diff --git a/example/http/cross_origin_file_transfer/services/remote_files.dart b/example/http/cross_origin_file_transfer/services/remote_files.dart deleted file mode 100644 index 3ae17919..00000000 --- a/example/http/cross_origin_file_transfer/services/remote_files.dart +++ /dev/null @@ -1,107 +0,0 @@ -// Copyright 2015 Workiva Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import 'dart:async'; - -import 'package:w_transport/w_transport.dart'; - -import './proxy.dart'; - -int _remoteFilePollingInterval = 10; // 10 seconds - -class RemoteFiles { - bool _connected; - StreamController _errorStreamController; - Stream _errorStream; - StreamController> _fileStreamController; - Stream> _fileStream; - Timer _pollingTimer; - - /// Construct a RemoteFiles instance and connect to the proxy server - /// via HTTP polling. - RemoteFiles._() { - _connected = true; - _errorStreamController = StreamController(); - _errorStream = _errorStreamController.stream.asBroadcastStream(); - _fileStreamController = StreamController>(); - _fileStream = _fileStreamController.stream.asBroadcastStream(); - _startPolling(); - } - - /// Stream that updates with the latest list of remote files. - Stream> get stream => _fileStream; - - /// Stream of errors that may occur when trying to communicate with the proxy file server. - Stream get errorStream => _errorStream; - - /// Establish a connection with the remote files server. - static RemoteFiles connect() { - return RemoteFiles._(); - } - - static void deleteAll() { - Http.delete(getFilesEndpointUrl()); - } - - /// Close the connection with the remote files server. - void close() { - _connected = false; - _errorStreamController.close(); - _fileStreamController.close(); - _endPolling(); - } - - /// Send polling requests 2 seconds apart. - void _startPolling() { - if (!_connected) return; - _poll().then((_) { - _pollingTimer = - Timer(Duration(seconds: _remoteFilePollingInterval), _startPolling); - }); - } - - /// Send the HTTP polling request. - Future _poll() async { - if (!_connected) return; - try { - final response = await Http.get(getFilesEndpointUrl()); - - // Parse the file list from the response - List results = response.body.asJson()['results']; - List files = results - .map((file) => RemoteFileDescription(file['name'], file['size'])) - .toList(); - - // Send the updated file list to listeners - _fileStreamController.add(files); - } catch (e, stackTrace) { - // Send the error to listeners - _errorStreamController.add(e); - print(e); - print(stackTrace); - } - } - - /// Cancel polling. - void _endPolling() { - _pollingTimer?.cancel(); - } -} - -class RemoteFileDescription { - final String name; - final int size; - - RemoteFileDescription(this.name, this.size); -} diff --git a/example/http/cross_origin_file_transfer/style.css b/example/http/cross_origin_file_transfer/style.css deleted file mode 100644 index f1b05d2b..00000000 --- a/example/http/cross_origin_file_transfer/style.css +++ /dev/null @@ -1,151 +0,0 @@ -/** - * Copyright 2015 Workiva Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -.hidden { - display: none; -} -.app-nav { - width: 100%; - background-color: #e6e6e6; -} -.app-nav > a { - display: inline-block; - padding: 15px 30px; - font-size: 18px; - color: #009bff; - text-decoration: none; -} -.app-nav > a:hover { - text-decoration: underline; -} -.app-nav > a.active { - font-weight: bold; -} -.no-pointer-events { - pointer-events: none; -} -.drop-zone { - visibility: hidden; - position: fixed; - width: 100%; - top: 48px; - right: 0; - bottom: 0; - left: 0; - background-color: rgba(255, 255, 255, 0.5); -} -.drop-zone.active { - visibility: visible; -} -.drop-target { - visibility: hidden; - position: fixed; - z-index: 1000; - top: 100px; - left: 50%; - margin-left: -150px; - width: 300px; - height: 300px; - line-height: 300px; - text-align: center; - font-size: 20px; - color: #333333; - border-radius: 50%; - background-color: #e6e6e6; - transition: width .5s, height .5s, top .5s, margin-left .5s, line-height .5s; -} -.drop-target.show { - visibility: visible; -} -.drop-target.over { - top: 80px; - margin-left: -170px; - width: 340px; - height: 340px; - line-height: 340px; - color: #fff; - background-color: #1499d3; -} -.transfers { - margin-left: 0; - padding-left: 0; - list-style: none; -} -.transfers > li { - display: block; - width: 100%; - padding: 8px 10px; - margin-bottom: 10px; - background-color: #eff0ed; - opacity: 1; - transition: background-color 0.5s ease, opacity 2s ease; -} -.transfers > li > .name { - float: left; - width: 400px; - height: 25px; - line-height: 25px; - padding: 0 20px; -} -.transfers > li > .progress { - margin-left: 420px; - height: 25px; - background-color: #cbcbcb; - opacity: 1; - transition: opacity 0.5s ease; -} -.transfers > li > .progress > .progress-bar { - height: 25px; - background-color: #66cc00; - transition: width 0.5s ease; -} -.transfers > li.done > .progress { - opacity: 0; -} -.transfers > li.success { - background-color: #e5efd9; -} -.transfers > li.error { - background-color: #ffa29b; -} -.transfers > li.hide { - opacity: 0; -} -.file { - float: left; - width: 31%; - margin-right: 2%; - margin-bottom: 15px; - padding: 15px; - background-color: #ecf6f9; - border: 1px solid #ecf6f9; -} -.file:hover { - border-color: #b9c4cb; -} -.file > .file-name { - display: inline-block; - text-overflow: ellipsis; - width: 80%; - color: #333; -} -.file > .file-size { - display: inline-block; - width: 20%; - text-align: right; - color: #8a8a8a; - font-size: 14px; -} \ No newline at end of file diff --git a/example/http/simple_client/README.md b/example/http/simple_client/README.md deleted file mode 100644 index f28eb6ec..00000000 --- a/example/http/simple_client/README.md +++ /dev/null @@ -1,7 +0,0 @@ -Example: Simple HTTP File Browser Client ----------------------------------------- - -> This example mimics a file browser. Clicking on any of the file names will send a GET request to retrieve the file contents, displaying them in a content pane. - - -[< All Examples](../..) \ No newline at end of file diff --git a/example/http/simple_client/client.dart b/example/http/simple_client/client.dart deleted file mode 100644 index 16cb050a..00000000 --- a/example/http/simple_client/client.dart +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright 2015 Workiva Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import 'dart:async'; -import 'dart:html'; - -import 'package:w_transport/w_transport.dart'; -import 'package:w_transport/browser.dart' show configureWTransportForBrowser; - -import '../../common/global_example_menu.dart'; -import '../../common/loading_component.dart'; - -/// Handle clicks on file names. -/// Sends a GET request to retrieve the file contents, -/// then displays the contents in the response pane. -Future handleFileClick(MouseEvent event) async { - // Prevent link navigation - event.preventDefault(); - - // Grab file path from anchor element - final AnchorElement anchor = event.target; - final filePath = anchor.href; - - // Send GET request instead - try { - showFileContents(await requestFile(filePath)); - } on RequestException catch (error) { - showFileContents(error.message); - } -} - -/// Requests the contents of a file using WRequest. -Future requestFile(String filePath) async { - final response = await Http.get(Uri.parse(filePath)); - return response.body.asString(); -} - -/// Displays the file contents in the response pane. -void showFileContents(String contents) { - querySelector('#response').text = contents; -} - -void main() { - configureWTransportForBrowser(); - - renderGlobalExampleMenu(); - - // Wire all anchors up to the file click handler - for (Element elem in querySelectorAll('a.file')) { - elem.onClick.listen(handleFileClick); - } - - // Remove the loading overlay - removeLoadingOverlay(); -} diff --git a/example/http/simple_client/data/family.json b/example/http/simple_client/data/family.json deleted file mode 100644 index cb4598d2..00000000 --- a/example/http/simple_client/data/family.json +++ /dev/null @@ -1,37 +0,0 @@ -[ - { - "name": "George Bluth Sr.", - "employment": "Incarcerated" - }, - - { - "name": "Michael Bluth", - "employment": "President" - }, - - { - "name": "GOB", - "employment": "Magician" - }, - - { - "name": "George Michael", - "employment": "Banana Stand Manager" - }, - - { - "name": "Tobias Fünke", - "employment": "Actor (unemployed)" - }, - - { - "name": "Lindsey Fünke", - "employment": "Activist" - }, - - { - "name": "Maeby Fünke", - "employment": "Student" - } - -] \ No newline at end of file diff --git a/example/http/simple_client/data/motto.txt b/example/http/simple_client/data/motto.txt deleted file mode 100644 index b6d2325b..00000000 --- a/example/http/simple_client/data/motto.txt +++ /dev/null @@ -1 +0,0 @@ -Family first. \ No newline at end of file diff --git a/example/http/simple_client/index.html b/example/http/simple_client/index.html deleted file mode 100644 index 9b9c5860..00000000 --- a/example/http/simple_client/index.html +++ /dev/null @@ -1,54 +0,0 @@ - - - - - - Simple Client | HTTP Example - - - - -
Loading...
- -
-

Simple Client File Browser

-

This example mimics a file browser. Clicking on any of the file names will send a GET request to retrieve the file contents, displaying them in the content pane on the right.

- - - -
-

-        
-
- - - - - - - diff --git a/example/http/simple_client/style.css b/example/http/simple_client/style.css deleted file mode 100644 index 1994bbcc..00000000 --- a/example/http/simple_client/style.css +++ /dev/null @@ -1,33 +0,0 @@ -/** - * Copyright 2015 Workiva Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -.files { - float: left; - width: 200px; -} -.content { - margin-left: 220px; -} -#response { - width: 100%; - padding: 10px; - min-height: 400px; - border: 1px solid #aaa; - font-family: "Courier New", Courier, monospace; - font-size: 14px; - line-height: 18px; - overflow: auto; -} \ No newline at end of file diff --git a/example/index.dart b/example/index.dart deleted file mode 100644 index 668427c4..00000000 --- a/example/index.dart +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright 2015 Workiva Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import 'package:w_transport/browser.dart' show configureWTransportForBrowser; - -import './common/global_example_menu.dart'; -import './common/loading_component.dart'; - -void main() { - configureWTransportForBrowser(); - renderGlobalExampleMenu(nav: false, includeServerStatus: true); - removeLoadingOverlay(); -} diff --git a/example/index.html b/example/index.html deleted file mode 100644 index a94fae93..00000000 --- a/example/index.html +++ /dev/null @@ -1,52 +0,0 @@ - - - - - - Examples | w_transport - - - -
Loading...
- -
-

w_transport Examples

- -

- Most of the examples require a server component, and some offer the option to proxy requests through an intermediary proxy server. - The menu/status bar at the top displays the status of this server. -

- -

HTTP

- - -

WebSocket

- -
- - - - - - - diff --git a/example/style.css b/example/style.css deleted file mode 100644 index 7c8730ae..00000000 --- a/example/style.css +++ /dev/null @@ -1,160 +0,0 @@ -/** - * Copyright 2015 Workiva Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -@import url(http://fonts.googleapis.com/css?family=Open+Sans:400,700,300); - -* { - box-sizing: border-box; -} - -body { - font-family: 'Open Sans', sans-serif; - font-size: 16px; - font-weight: 400; - color: #444; - margin: 0; - padding: 40px 0 0; -} - -.d-block { display: block; } - -p { - font-size: 18px; - font-weight: 300; - line-height: 24px; -} - -p.note { - padding: 4px 10px; - border-left: 3px solid #979797; - background-color: #f3f3f3; - font-size: 14px; - color: #666; -} - -p.success { - padding: 4px 10px; - border-left: 3px solid #0f7f40; - background-color: #e5efd9; - font-size: 14px; - color: #333; -} - -p.warning { - padding: 4px 10px; - border-left: 3px solid #fbad17; - background-color: #f9efc7; - font-size: 14px; - color: #333; -} - -p.error { - padding: 4px 10px; - border-left: 3px solid #a71b19; - background-color: #ff5547; - font-size: 14px; - font-weight: bold; - color: #fff; -} - -.muted { - font-size: 16px; - color: #979797; -} - -.clear:after { - content: ""; - display: table; - clear: both; -} - -.container { - width: 90%; - margin: 15px auto 0; -} - -.loading { - position: absolute; - top: 0; - left: 0; - right: 0; - bottom: 0; - padding-top: 100px; - background-color: #fff; - color: #999; - text-align: center; - font-style: italic; -} - -.loading.done { - display: none; -} - -.global-example-menu { - position: fixed; - left: 0; - top: 0; - right: 0; - width: 100%; - height: 40px; - background-color: #f2f2f2; - border-bottom: 1px solid #dbdbdb; -} - -.global-example-menu > .container { - margin-top: 0; -} - -.global-example-menu a { - float: left; - margin-right: 50px; - font-size: 16px; - line-height: 40px; - color: #888; - text-decoration: none; -} - -.global-example-menu a:hover { - color: #009bff; - text-decoration: underline; -} - -.global-example-menu .server-status { - float: left; - margin-right: 35px; - color: #ee2724; - font-size: 16px; -} - -.global-example-menu .server-status.online { - color: #66cc00; -} - -.global-example-menu .server-status > .server-status-light { - float: left; - margin-right: 6px; - font-size: 46px; - line-height: 40px; -} - -.global-example-menu .server-status > .server-status-desc { - float: left; - line-height: 40px; -} - -.global-example-menu .server-status-tip { - line-height: 40px; -} diff --git a/example/web_socket/echo/README.md b/example/web_socket/echo/README.md deleted file mode 100644 index dce6b828..00000000 --- a/example/web_socket/echo/README.md +++ /dev/null @@ -1,7 +0,0 @@ -Example: WebSocket Echo ------------------------ - -> This example is a simple WebSocket connection that echos every message. - - -[< All Examples](../..) \ No newline at end of file diff --git a/example/web_socket/echo/client.dart b/example/web_socket/echo/client.dart deleted file mode 100644 index e146b7f0..00000000 --- a/example/web_socket/echo/client.dart +++ /dev/null @@ -1,107 +0,0 @@ -// Copyright 2015 Workiva Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import 'dart:async'; -import 'dart:convert'; -import 'dart:html'; - -import 'package:w_transport/w_transport.dart'; -import 'package:w_transport/browser.dart' show configureWTransportForBrowser; - -import '../../common/global_example_menu.dart'; -import '../../common/loading_component.dart'; - -final _wsServer = Uri.parse('ws://localhost:8024/example/ws/echo'); -final _sockJSServer = Uri.parse('ws://localhost:8026/example/ws/echo'); - -String _echo(String message) => - json.encode({'action': 'echo', 'message': message}); -String _unecho(String response) => json.decode(response)['message']; - -ButtonElement _connect = querySelector('#connect'); -FormElement _form = querySelector('#prompt-form'); -TextInputElement _prompt = querySelector('#prompt'); -PreElement _logs = querySelector('#logs'); -NumberInputElement _sockJSTimeout = querySelector('#sockjs-timeout'); -CheckboxInputElement _sockJSWebSocket = querySelector('#sockjs-ws'); -CheckboxInputElement _sockJSXhrStreaming = - querySelector('#sockjs-xhr-streaming'); -CheckboxInputElement _sockJSXhrPolling = querySelector('#sockjs-xhr-polling'); -CheckboxInputElement _useSockJS = querySelector('#sockjs'); - -Future main() async { - configureWTransportForBrowser(); - - renderGlobalExampleMenu(includeServerStatus: true); - - // ignore: close_sinks,deprecated_member_use_from_same_package - WSocket webSocket; - - // Connect (or reconnect) when the connect button is clicked. - _connect.onClick.listen((e) async { - _logs.appendText('Connecting...\n'); - - final sockjs = _useSockJS.checked; - final timeout = _sockJSTimeout.value.isEmpty - ? null - : Duration(milliseconds: _sockJSTimeout.valueAsNumber); - final protocols = []; - if (_sockJSWebSocket.checked) { - protocols.add('websocket'); - } - if (_sockJSXhrStreaming.checked) { - protocols.add('xhr-streaming'); - } - if (_sockJSXhrPolling.checked) { - protocols.add('xhr-polling'); - } - final uri = sockjs ? _sockJSServer : _wsServer; - - try { - // ignore: deprecated_member_use_from_same_package - webSocket = await WSocket.connect(uri, - // ignore: deprecated_member_use_from_same_package - useSockJS: sockjs, - // ignore: deprecated_member_use_from_same_package - sockJSTimeout: timeout, - // ignore: deprecated_member_use_from_same_package - sockJSProtocolsWhitelist: protocols); - - // Display messages from web socket - webSocket.listen((message) { - _logs.appendText('${_unecho(message)}\n'); - }); - - _logs.appendText('Connected.\n'); - } on WebSocketException catch (e, stackTrace) { - _logs.appendText( - '> ERROR: Could not connect to web socket on $_wsServer\n'); - print('Could not connect to web socket.\n$e\n$stackTrace'); - } - }); - - // Send message upon form submit. - _form.onSubmit.listen((e) { - e.preventDefault(); - - if (webSocket == null) return; - - final message = _prompt.value; - _logs.appendText('> $message\n'); - webSocket.add(_echo(message)); - }); - - // Remove the loading overlay - removeLoadingOverlay(); -} diff --git a/example/web_socket/echo/index.html b/example/web_socket/echo/index.html deleted file mode 100644 index bbb51af5..00000000 --- a/example/web_socket/echo/index.html +++ /dev/null @@ -1,84 +0,0 @@ - - - - - - Echo | WebSocket Example - - - - -
Loading...
- -
-

Echo

-

Connect to a WebSocket and send messages that will be echoed.

- -
- - -
- - - -
- - - -
- - - -
- - - - -

- - - -

- - - - -
- -

-
- - - - - - - - - diff --git a/example/web_socket/echo/style.css b/example/web_socket/echo/style.css deleted file mode 100644 index 6829be47..00000000 --- a/example/web_socket/echo/style.css +++ /dev/null @@ -1,21 +0,0 @@ -/** - * Copyright 2015 Workiva Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#logs { - margin: 10px 0 0; - min-height: 300px; - border: 1px solid #888; -} \ No newline at end of file diff --git a/pubspec.yaml b/pubspec.yaml index 6a66de06..27d8f8db 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -8,14 +8,23 @@ environment: dependencies: fluri: ^1.2.6 - http_parser: ^3.1.3 + http_parser: ^4.0.0 meta: ^1.1.8 mime: ^0.9.6+3 sockjs_client: git: url: git://github.com/Workiva/sockjs-dart-client.git ref: 0.3.5 - sockjs_client_wrapper: ^1.0.14 + sockjs_client_wrapper: + git: + url: https://github.com/zmeggyesi/sockjs_client_wrapper.git + +dependency_overrides: + logging: ^1.0.1 + glob: ^2.0.1 + args: ^2.0.0 + watcher: ^1.0.0 + package_config: ^2.0.0 dev_dependencies: build_runner: ^1.7.1 @@ -24,10 +33,9 @@ dev_dependencies: collection: ^1.14.6 dart_dev: ^3.3.1 dart_style: ^1.3.1 - dependency_validator: ^1.4.1 +# dependency_validator: ^2.0.1 http_server: ^0.9.8+3 mockito: ^4.1.1 - over_react: ">=3.12.0 <5.0.0" test: ^1.15.2 - uuid: ^2.0.4 + uuid: ^3.0.3 workiva_analysis_options: ^1.0.2