yshrsmz / unorm-dart

https://pub.dev/packages/unorm_dart
MIT License
11 stars 6 forks source link

[feature-request] use String.prototype.normalize() when compiled with dart2js #2

Open jonasfj opened 5 years ago

jonasfj commented 5 years ago

Dart supports conditional imports, when running in a browser environment it would be possible to simply use: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/normalize

This would not only be faster, but also reduce the size of compiled javascript code :)

olof-dev commented 2 years ago

Here's what I came up with for accessing this, using the official js-interop package. I don't know if it's the best way.

import 'package:js/js.dart';

@JS('String')
@staticInterop
class JsString {
  external JsString(String s);
}

extension JsStringExtension on JsString {
  external String normalize(String form);
}

extension StringExtensionHtml on String {
  String unicodeNormalize(String form) {
    // For now, this throws in debug mode, but it's fine in (web-)production
    final value = JsString(this);
    return value.normalize(form);
  }
}

If this is placed into a file normalizer_web.dart, one can do a conditional import from another file using

import 'normalizer_regular.dart' if (dart.library.html) 'normalizer_web.dart';

This way you can use the browser's normalize function (named unicodeNormalize above) on the web, and use something else on non-web.