UnicodeBidiService.js.flow 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. /**
  2. * Copyright (c) 2013-present, Facebook, Inc.
  3. *
  4. * This source code is licensed under the MIT license found in the
  5. * LICENSE file in the root directory of this source tree.
  6. *
  7. * @providesModule UnicodeBidiService
  8. * @typechecks
  9. * @flow
  10. */
  11. /**
  12. * Stateful API for text direction detection
  13. *
  14. * This class can be used in applications where you need to detect the
  15. * direction of a sequence of text blocks, where each direction shall be used
  16. * as the fallback direction for the next one.
  17. *
  18. * NOTE: A default direction, if not provided, is set based on the global
  19. * direction, as defined by `UnicodeBidiDirection`.
  20. *
  21. * == Example ==
  22. * ```
  23. * var UnicodeBidiService = require('UnicodeBidiService');
  24. *
  25. * var bidiService = new UnicodeBidiService();
  26. *
  27. * ...
  28. *
  29. * bidiService.reset();
  30. * for (var para in paragraphs) {
  31. * var dir = bidiService.getDirection(para);
  32. * ...
  33. * }
  34. * ```
  35. *
  36. * Part of our implementation of Unicode Bidirectional Algorithm (UBA)
  37. * Unicode Standard Annex #9 (UAX9)
  38. * http://www.unicode.org/reports/tr9/
  39. */
  40. 'use strict';
  41. const UnicodeBidi = require('./UnicodeBidi');
  42. const UnicodeBidiDirection = require('./UnicodeBidiDirection');
  43. const invariant = require('./invariant');
  44. import type { BidiDirection } from './UnicodeBidiDirection';
  45. class UnicodeBidiService {
  46. _defaultDir: BidiDirection;
  47. _lastDir: BidiDirection;
  48. /**
  49. * Stateful class for paragraph direction detection
  50. *
  51. * @param defaultDir Default direction of the service
  52. */
  53. constructor(defaultDir: ?BidiDirection) {
  54. if (!defaultDir) {
  55. defaultDir = UnicodeBidiDirection.getGlobalDir();
  56. } else {
  57. invariant(UnicodeBidiDirection.isStrong(defaultDir), 'Default direction must be a strong direction (LTR or RTL)');
  58. }
  59. this._defaultDir = defaultDir;
  60. this.reset();
  61. }
  62. /**
  63. * Reset the internal state
  64. *
  65. * Instead of creating a new instance, you can just reset() your instance
  66. * everytime you start a new loop.
  67. */
  68. reset(): void {
  69. this._lastDir = this._defaultDir;
  70. }
  71. /**
  72. * Returns the direction of a block of text, and remembers it as the
  73. * fall-back direction for the next paragraph.
  74. *
  75. * @param str A text block, e.g. paragraph, table cell, tag
  76. * @return The resolved direction
  77. */
  78. getDirection(str: string): BidiDirection {
  79. this._lastDir = UnicodeBidi.getDirection(str, this._lastDir);
  80. return this._lastDir;
  81. }
  82. }
  83. module.exports = UnicodeBidiService;