Skip to content

Commit

Permalink
Implement actual decoding on web
Browse files Browse the repository at this point in the history
  • Loading branch information
amake committed Mar 4, 2024
1 parent 3d70b66 commit 4b66ee0
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 5 deletions.
16 changes: 11 additions & 5 deletions flutter_charset_detector_web/lib/flutter_charset_detector_web.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import 'package:flutter_charset_detector_platform_interface/decoding_result.dart
import 'package:flutter_charset_detector_platform_interface/flutter_charset_detector_platform_interface.dart';
import 'package:flutter_charset_detector_web/js_charset_detector.dart'
as jschardet;
import 'package:flutter_charset_detector_web/js_textdecoder.dart';
import 'package:flutter_web_plugins/flutter_web_plugins.dart';

class CharsetDetectorWeb extends CharsetDetectorPlatform {
Expand All @@ -19,13 +20,18 @@ class CharsetDetectorWeb extends CharsetDetectorPlatform {
/// Automatically detect the charset of [bytes] and decode to a string.
@override
Future<DecodingResult> autoDecode(Uint8List bytes) async {
String text = String.fromCharCodes(bytes);
final detectedMap = jschardet.detect(text, null);
final byteString = String.fromCharCodes(bytes);
final detectedMap = jschardet.detect(byteString, null);
final decoder = TextDecoder(detectedMap.encoding);
debugPrint(
'Detected result: encoding=${detectedMap.encoding}; confidence=${detectedMap.confidence}');
'Detected result; '
'encoding: ${detectedMap.encoding} (normalized to: ${decoder.encoding}), '
'confidence: ${detectedMap.confidence}',
);
final decodedString = decoder.decode(bytes);
return DecodingResult.fromJson({
'charset': detectedMap.encoding,
'string': text,
'charset': decoder.encoding,
'string': decodedString,
});
}
}
28 changes: 28 additions & 0 deletions flutter_charset_detector_web/lib/js_textdecoder.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
@JS()
library js_textdecoder;

import 'package:js/js.dart';

@JS()
class TextDecoder {
external TextDecoder([String label, TextDecoderOptions options]);
external String decode(dynamic data, [TextDecodeOptions options]);
external String get encoding;
external bool get fatal;
external bool get ignoreBOM;
}

@JS()
@anonymous
class TextDecoderOptions {
external bool get fatal;
external bool get ignoreBOM;
external factory TextDecoderOptions({bool fatal, bool ignoreBOM});
}

@JS()
@anonymous
class TextDecodeOptions {
external bool get stream;
external factory TextDecodeOptions({bool stream});
}

0 comments on commit 4b66ee0

Please sign in to comment.