Namespaced and TypeScript Enums (#1285)

Summary:
Pull Request resolved: https://github.com/facebook/yoga/pull/1285

Enums are currently exposed to the JS package as constants (e.g. `import {ERRATA_NONE} from 'yoga-layout'`).

This exports enums in the form of `import {Errata} from 'yoga-layout'` then `Errata.None`.

It would be more ergonomic for these to be string union based enums instead, but right now it is a pretty thin wrapper around the native API, we need ordinal values to do things with bit masks, and folks have wanted to serialize them before.

Reviewed By: yungsters

Differential Revision: D45570417

fbshipit-source-id: dbfd330e939051d0c16460a4d2a996f88f98875c
This commit is contained in:
Nick Gerleman
2023-05-09 22:21:01 -07:00
committed by Facebook GitHub Bot
parent aa812d0e48
commit 104646d8ca
7 changed files with 265 additions and 548 deletions

126
enums.py Normal file → Executable file
View File

@@ -1,13 +1,11 @@
#!/usr/bin/env python3
# Copyright (c) Meta Platforms, Inc. and affiliates. # Copyright (c) Meta Platforms, Inc. and affiliates.
# #
# This source code is licensed under the MIT license found in the # This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree. # LICENSE file in the root directory of this source tree.
from __future__ import absolute_import, division, print_function, unicode_literals
import os import os
ENUMS = { ENUMS = {
"Direction": ["Inherit", "LTR", "RTL"], "Direction": ["Inherit", "LTR", "RTL"],
"Unit": ["Undefined", "Point", "Percent", "Auto"], "Unit": ["Undefined", "Point", "Percent", "Auto"],
@@ -78,50 +76,44 @@ ENUMS = {
], ],
} }
# Generated Java enums used to emit @DoNotStrip, but D17519844 removed them
# manually from all but YogaLogLevel. TODO: Is it safe to remove from it as
# well?
DO_NOT_STRIP = ["LogLevel"] DO_NOT_STRIP = ["LogLevel"]
BITSET_ENUMS = ["PrintOptions", "Errata"] BITSET_ENUMS = ["PrintOptions", "Errata"]
def get_license(ext): def get_license(ext):
prologue = "/**" if ext == "js" else "/*" return f"""{"/**" if ext == "js" else "/*"}
return """{}
* Copyright (c) Meta Platforms, Inc. and affiliates. * Copyright (c) Meta Platforms, Inc. and affiliates.
* *
* This source code is licensed under the MIT license found in the * This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree. * LICENSE file in the root directory of this source tree.
*/ */
// @{} by enums.py // @{"generated"} by enums.py
""".format( """
prologue, "generated"
)
def _format_name(symbol, delimiter=None, transform=None):
symbol = str(symbol)
out = ""
for i in range(0, len(symbol)):
c = symbol[i]
if str.istitle(c) and i != 0 and not str.istitle(symbol[i - 1]):
out += delimiter or ""
if transform is None:
out += c
else:
out += getattr(c, transform)()
return out
def to_java_upper(symbol): def to_java_upper(symbol):
symbol = str(symbol) return _format_name(symbol, "_", "upper")
out = ""
for i in range(0, len(symbol)):
c = symbol[i]
if str.istitle(c) and i is not 0 and not str.istitle(symbol[i - 1]):
out += "_"
out += c.upper()
return out
def to_log_lower(symbol): def to_hyphenated_lower(symbol):
symbol = str(symbol) return _format_name(symbol, "-", "lower")
out = ""
for i in range(0, len(symbol)):
c = symbol[i]
if str.istitle(c) and i is not 0 and not str.istitle(symbol[i - 1]):
out += "-"
out += c.lower()
return out
root = os.path.dirname(os.path.abspath(__file__)) root = os.path.dirname(os.path.abspath(__file__))
@@ -167,10 +159,10 @@ with open(root + "/yoga/YGEnums.cpp", "w") as f:
for value in values: for value in values:
if isinstance(value, tuple): if isinstance(value, tuple):
f.write(" case YG%s%s:\n" % (name, value[0])) f.write(" case YG%s%s:\n" % (name, value[0]))
f.write(' return "%s";\n' % to_log_lower(value[0])) f.write(' return "%s";\n' % to_hyphenated_lower(value[0]))
else: else:
f.write(" case YG%s%s:\n" % (name, value)) f.write(" case YG%s%s:\n" % (name, value))
f.write(' return "%s";\n' % to_log_lower(value)) f.write(' return "%s";\n' % to_hyphenated_lower(value))
f.write(" }\n") f.write(" }\n")
f.write(' return "unknown";\n') f.write(' return "unknown";\n')
f.write("}\n") f.write("}\n")
@@ -246,61 +238,27 @@ for name, values in sorted(ENUMS.items()):
f.write(" }\n") f.write(" }\n")
f.write("}\n") f.write("}\n")
# write out javascript file # write out TypeScript file
with open(root + "/javascript/src/generated/YGEnums.js", "w") as f: with open(root + "/javascript/src/generated/YGEnums.ts", "w") as f:
f.write(get_license("js")) f.write(get_license("js"))
items = sorted(ENUMS.items()) enums = sorted(ENUMS.items())
for name, values in items: for enum_name, ordinals in enums:
base = 0 f.write(f"export enum {enum_name} {{\n")
for value in values: for ordinal_index, ordinal in enumerate(ordinals):
value_arg = value[0] if isinstance(value, tuple) else value ordinal_name = ordinal[0] if isinstance(ordinal, tuple) else ordinal
ordinal_arg = value[1] if isinstance(value, tuple) else base ordinal_value = ordinal[1] if isinstance(ordinal, tuple) else ordinal_index
f.write(f" {ordinal_name} = {ordinal_value},\n")
f.write("}\n\n")
f.write("const constants = {\n")
for enum_name, ordinals in enums:
for ordinal in ordinals:
ordinal_name = ordinal[0] if isinstance(ordinal, tuple) else ordinal
ordinal_value = ordinal[1] if isinstance(ordinal, tuple) else ordinal_index
f.write( f.write(
"exports.%s_%s = %d;\n" f" {to_java_upper(enum_name)}_{to_java_upper(ordinal_name)}: {enum_name}.{ordinal_name},\n"
% (to_java_upper(name), to_java_upper(value_arg), ordinal_arg)
)
base = ordinal_arg + 1
if name != items[-1][0]:
f.write("\n")
with open(root + "/javascript/src/generated/YGEnums.d.ts", "w") as f:
f.write(get_license("js"))
for name, values in sorted(ENUMS.items()):
base = 0
for value in values:
value_arg = value[0] if isinstance(value, tuple) else value
ordinal_arg = value[1] if isinstance(value, tuple) else base
f.write(
(
"type {name}_{value} = {ordinal} & ['{name}']\n"
+ "export declare const {name}_{value}: {name}_{value};\n\n"
).format(
name=to_java_upper(name),
value=to_java_upper(value_arg),
ordinal=ordinal_arg,
)
) )
base = ordinal_arg + 1 f.write("}\n")
f.write("export default constants")
f.write("\n")
for name, values in sorted(ENUMS.items()):
f.write("export type {} =\n".format(name))
for value in values:
unpackedValue = value[0] if isinstance(value, tuple) else value
f.write(
" | typeof {}_{}".format(
to_java_upper(name), to_java_upper(unpackedValue)
)
)
if values[-1] == value:
f.write(";\n")
else:
f.write("\n")
f.write("\n")

View File

@@ -7,21 +7,21 @@ This package provides prebuilt JavaScript bindings for the Yoga layout engine. B
The default entrypoint provides an asynchronous loader function to return a Yoga instance. The default entrypoint provides an asynchronous loader function to return a Yoga instance.
```ts ```ts
import { loadYoga, ALIGN_CENTER } from "yoga-layout"; import {loadYoga, Align} from 'yoga-layout';
const Yoga = await loadYoga(); const Yoga = await loadYoga();
const node = Yoga.Node.create(); const node = Yoga.Node.create();
node.setAlignContent(ALIGN_CENTER); node.setAlignContent(Align.Center);
``` ```
An alternative synchronous API is provided for compatibility, but requires using asm.js in browsers instead of WebAssembly, leading to worse performance and larger assets. An alternative synchronous API is provided for compatibility, but requires using asm.js in browsers instead of WebAssembly, leading to worse performance and larger assets.
```ts ```ts
import Yoga, { ALIGN_CENTER } from "yoga-layout/sync"; import Yoga, {Align} from 'yoga-layout/sync';
const node = Yoga.Node.create(); const node = Yoga.Node.create();
node.setAlignContent(ALIGN_CENTER); node.setAlignContent(Align.Center);
``` ```
Objects created by `Yoga.<>.create()` are not automatically garbage collected and should be freed once they are no longer in use. Objects created by `Yoga.<>.create()` are not automatically garbage collected and should be freed once they are no longer in use.
@@ -44,7 +44,7 @@ For better performance and smaller packages, WebAssembly is preferred to asm.js
A specific entrypoint may be specified on platforms which do not understand export conditions. A specific entrypoint may be specified on platforms which do not understand export conditions.
```ts ```ts
import { loadYoga } from "yoga-layout/dist/entrypoint/wasm-async"; import {loadYoga} from 'yoga-layout/dist/entrypoint/wasm-async';
``` ```

View File

@@ -1,347 +0,0 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
// @generated by enums.py
type ALIGN_AUTO = 0 & ['ALIGN']
export declare const ALIGN_AUTO: ALIGN_AUTO;
type ALIGN_FLEX_START = 1 & ['ALIGN']
export declare const ALIGN_FLEX_START: ALIGN_FLEX_START;
type ALIGN_CENTER = 2 & ['ALIGN']
export declare const ALIGN_CENTER: ALIGN_CENTER;
type ALIGN_FLEX_END = 3 & ['ALIGN']
export declare const ALIGN_FLEX_END: ALIGN_FLEX_END;
type ALIGN_STRETCH = 4 & ['ALIGN']
export declare const ALIGN_STRETCH: ALIGN_STRETCH;
type ALIGN_BASELINE = 5 & ['ALIGN']
export declare const ALIGN_BASELINE: ALIGN_BASELINE;
type ALIGN_SPACE_BETWEEN = 6 & ['ALIGN']
export declare const ALIGN_SPACE_BETWEEN: ALIGN_SPACE_BETWEEN;
type ALIGN_SPACE_AROUND = 7 & ['ALIGN']
export declare const ALIGN_SPACE_AROUND: ALIGN_SPACE_AROUND;
type DIMENSION_WIDTH = 0 & ['DIMENSION']
export declare const DIMENSION_WIDTH: DIMENSION_WIDTH;
type DIMENSION_HEIGHT = 1 & ['DIMENSION']
export declare const DIMENSION_HEIGHT: DIMENSION_HEIGHT;
type DIRECTION_INHERIT = 0 & ['DIRECTION']
export declare const DIRECTION_INHERIT: DIRECTION_INHERIT;
type DIRECTION_LTR = 1 & ['DIRECTION']
export declare const DIRECTION_LTR: DIRECTION_LTR;
type DIRECTION_RTL = 2 & ['DIRECTION']
export declare const DIRECTION_RTL: DIRECTION_RTL;
type DISPLAY_FLEX = 0 & ['DISPLAY']
export declare const DISPLAY_FLEX: DISPLAY_FLEX;
type DISPLAY_NONE = 1 & ['DISPLAY']
export declare const DISPLAY_NONE: DISPLAY_NONE;
type EDGE_LEFT = 0 & ['EDGE']
export declare const EDGE_LEFT: EDGE_LEFT;
type EDGE_TOP = 1 & ['EDGE']
export declare const EDGE_TOP: EDGE_TOP;
type EDGE_RIGHT = 2 & ['EDGE']
export declare const EDGE_RIGHT: EDGE_RIGHT;
type EDGE_BOTTOM = 3 & ['EDGE']
export declare const EDGE_BOTTOM: EDGE_BOTTOM;
type EDGE_START = 4 & ['EDGE']
export declare const EDGE_START: EDGE_START;
type EDGE_END = 5 & ['EDGE']
export declare const EDGE_END: EDGE_END;
type EDGE_HORIZONTAL = 6 & ['EDGE']
export declare const EDGE_HORIZONTAL: EDGE_HORIZONTAL;
type EDGE_VERTICAL = 7 & ['EDGE']
export declare const EDGE_VERTICAL: EDGE_VERTICAL;
type EDGE_ALL = 8 & ['EDGE']
export declare const EDGE_ALL: EDGE_ALL;
type ERRATA_NONE = 0 & ['ERRATA']
export declare const ERRATA_NONE: ERRATA_NONE;
type ERRATA_STRETCH_FLEX_BASIS = 1 & ['ERRATA']
export declare const ERRATA_STRETCH_FLEX_BASIS: ERRATA_STRETCH_FLEX_BASIS;
type ERRATA_ALL = 2147483647 & ['ERRATA']
export declare const ERRATA_ALL: ERRATA_ALL;
type ERRATA_CLASSIC = 2147483646 & ['ERRATA']
export declare const ERRATA_CLASSIC: ERRATA_CLASSIC;
type EXPERIMENTAL_FEATURE_WEB_FLEX_BASIS = 0 & ['EXPERIMENTAL_FEATURE']
export declare const EXPERIMENTAL_FEATURE_WEB_FLEX_BASIS: EXPERIMENTAL_FEATURE_WEB_FLEX_BASIS;
type EXPERIMENTAL_FEATURE_ABSOLUTE_PERCENTAGE_AGAINST_PADDING_EDGE = 1 & ['EXPERIMENTAL_FEATURE']
export declare const EXPERIMENTAL_FEATURE_ABSOLUTE_PERCENTAGE_AGAINST_PADDING_EDGE: EXPERIMENTAL_FEATURE_ABSOLUTE_PERCENTAGE_AGAINST_PADDING_EDGE;
type EXPERIMENTAL_FEATURE_FIX_ABSOLUTE_TRAILING_COLUMN_MARGIN = 2 & ['EXPERIMENTAL_FEATURE']
export declare const EXPERIMENTAL_FEATURE_FIX_ABSOLUTE_TRAILING_COLUMN_MARGIN: EXPERIMENTAL_FEATURE_FIX_ABSOLUTE_TRAILING_COLUMN_MARGIN;
type FLEX_DIRECTION_COLUMN = 0 & ['FLEX_DIRECTION']
export declare const FLEX_DIRECTION_COLUMN: FLEX_DIRECTION_COLUMN;
type FLEX_DIRECTION_COLUMN_REVERSE = 1 & ['FLEX_DIRECTION']
export declare const FLEX_DIRECTION_COLUMN_REVERSE: FLEX_DIRECTION_COLUMN_REVERSE;
type FLEX_DIRECTION_ROW = 2 & ['FLEX_DIRECTION']
export declare const FLEX_DIRECTION_ROW: FLEX_DIRECTION_ROW;
type FLEX_DIRECTION_ROW_REVERSE = 3 & ['FLEX_DIRECTION']
export declare const FLEX_DIRECTION_ROW_REVERSE: FLEX_DIRECTION_ROW_REVERSE;
type GUTTER_COLUMN = 0 & ['GUTTER']
export declare const GUTTER_COLUMN: GUTTER_COLUMN;
type GUTTER_ROW = 1 & ['GUTTER']
export declare const GUTTER_ROW: GUTTER_ROW;
type GUTTER_ALL = 2 & ['GUTTER']
export declare const GUTTER_ALL: GUTTER_ALL;
type JUSTIFY_FLEX_START = 0 & ['JUSTIFY']
export declare const JUSTIFY_FLEX_START: JUSTIFY_FLEX_START;
type JUSTIFY_CENTER = 1 & ['JUSTIFY']
export declare const JUSTIFY_CENTER: JUSTIFY_CENTER;
type JUSTIFY_FLEX_END = 2 & ['JUSTIFY']
export declare const JUSTIFY_FLEX_END: JUSTIFY_FLEX_END;
type JUSTIFY_SPACE_BETWEEN = 3 & ['JUSTIFY']
export declare const JUSTIFY_SPACE_BETWEEN: JUSTIFY_SPACE_BETWEEN;
type JUSTIFY_SPACE_AROUND = 4 & ['JUSTIFY']
export declare const JUSTIFY_SPACE_AROUND: JUSTIFY_SPACE_AROUND;
type JUSTIFY_SPACE_EVENLY = 5 & ['JUSTIFY']
export declare const JUSTIFY_SPACE_EVENLY: JUSTIFY_SPACE_EVENLY;
type LOG_LEVEL_ERROR = 0 & ['LOG_LEVEL']
export declare const LOG_LEVEL_ERROR: LOG_LEVEL_ERROR;
type LOG_LEVEL_WARN = 1 & ['LOG_LEVEL']
export declare const LOG_LEVEL_WARN: LOG_LEVEL_WARN;
type LOG_LEVEL_INFO = 2 & ['LOG_LEVEL']
export declare const LOG_LEVEL_INFO: LOG_LEVEL_INFO;
type LOG_LEVEL_DEBUG = 3 & ['LOG_LEVEL']
export declare const LOG_LEVEL_DEBUG: LOG_LEVEL_DEBUG;
type LOG_LEVEL_VERBOSE = 4 & ['LOG_LEVEL']
export declare const LOG_LEVEL_VERBOSE: LOG_LEVEL_VERBOSE;
type LOG_LEVEL_FATAL = 5 & ['LOG_LEVEL']
export declare const LOG_LEVEL_FATAL: LOG_LEVEL_FATAL;
type MEASURE_MODE_UNDEFINED = 0 & ['MEASURE_MODE']
export declare const MEASURE_MODE_UNDEFINED: MEASURE_MODE_UNDEFINED;
type MEASURE_MODE_EXACTLY = 1 & ['MEASURE_MODE']
export declare const MEASURE_MODE_EXACTLY: MEASURE_MODE_EXACTLY;
type MEASURE_MODE_AT_MOST = 2 & ['MEASURE_MODE']
export declare const MEASURE_MODE_AT_MOST: MEASURE_MODE_AT_MOST;
type NODE_TYPE_DEFAULT = 0 & ['NODE_TYPE']
export declare const NODE_TYPE_DEFAULT: NODE_TYPE_DEFAULT;
type NODE_TYPE_TEXT = 1 & ['NODE_TYPE']
export declare const NODE_TYPE_TEXT: NODE_TYPE_TEXT;
type OVERFLOW_VISIBLE = 0 & ['OVERFLOW']
export declare const OVERFLOW_VISIBLE: OVERFLOW_VISIBLE;
type OVERFLOW_HIDDEN = 1 & ['OVERFLOW']
export declare const OVERFLOW_HIDDEN: OVERFLOW_HIDDEN;
type OVERFLOW_SCROLL = 2 & ['OVERFLOW']
export declare const OVERFLOW_SCROLL: OVERFLOW_SCROLL;
type POSITION_TYPE_STATIC = 0 & ['POSITION_TYPE']
export declare const POSITION_TYPE_STATIC: POSITION_TYPE_STATIC;
type POSITION_TYPE_RELATIVE = 1 & ['POSITION_TYPE']
export declare const POSITION_TYPE_RELATIVE: POSITION_TYPE_RELATIVE;
type POSITION_TYPE_ABSOLUTE = 2 & ['POSITION_TYPE']
export declare const POSITION_TYPE_ABSOLUTE: POSITION_TYPE_ABSOLUTE;
type PRINT_OPTIONS_LAYOUT = 1 & ['PRINT_OPTIONS']
export declare const PRINT_OPTIONS_LAYOUT: PRINT_OPTIONS_LAYOUT;
type PRINT_OPTIONS_STYLE = 2 & ['PRINT_OPTIONS']
export declare const PRINT_OPTIONS_STYLE: PRINT_OPTIONS_STYLE;
type PRINT_OPTIONS_CHILDREN = 4 & ['PRINT_OPTIONS']
export declare const PRINT_OPTIONS_CHILDREN: PRINT_OPTIONS_CHILDREN;
type UNIT_UNDEFINED = 0 & ['UNIT']
export declare const UNIT_UNDEFINED: UNIT_UNDEFINED;
type UNIT_POINT = 1 & ['UNIT']
export declare const UNIT_POINT: UNIT_POINT;
type UNIT_PERCENT = 2 & ['UNIT']
export declare const UNIT_PERCENT: UNIT_PERCENT;
type UNIT_AUTO = 3 & ['UNIT']
export declare const UNIT_AUTO: UNIT_AUTO;
type WRAP_NO_WRAP = 0 & ['WRAP']
export declare const WRAP_NO_WRAP: WRAP_NO_WRAP;
type WRAP_WRAP = 1 & ['WRAP']
export declare const WRAP_WRAP: WRAP_WRAP;
type WRAP_WRAP_REVERSE = 2 & ['WRAP']
export declare const WRAP_WRAP_REVERSE: WRAP_WRAP_REVERSE;
export type Align =
| typeof ALIGN_AUTO
| typeof ALIGN_FLEX_START
| typeof ALIGN_CENTER
| typeof ALIGN_FLEX_END
| typeof ALIGN_STRETCH
| typeof ALIGN_BASELINE
| typeof ALIGN_SPACE_BETWEEN
| typeof ALIGN_SPACE_AROUND;
export type Dimension =
| typeof DIMENSION_WIDTH
| typeof DIMENSION_HEIGHT;
export type Direction =
| typeof DIRECTION_INHERIT
| typeof DIRECTION_LTR
| typeof DIRECTION_RTL;
export type Display =
| typeof DISPLAY_FLEX
| typeof DISPLAY_NONE;
export type Edge =
| typeof EDGE_LEFT
| typeof EDGE_TOP
| typeof EDGE_RIGHT
| typeof EDGE_BOTTOM
| typeof EDGE_START
| typeof EDGE_END
| typeof EDGE_HORIZONTAL
| typeof EDGE_VERTICAL
| typeof EDGE_ALL;
export type Errata =
| typeof ERRATA_NONE
| typeof ERRATA_STRETCH_FLEX_BASIS
| typeof ERRATA_ALL
| typeof ERRATA_CLASSIC;
export type ExperimentalFeature =
| typeof EXPERIMENTAL_FEATURE_WEB_FLEX_BASIS
| typeof EXPERIMENTAL_FEATURE_ABSOLUTE_PERCENTAGE_AGAINST_PADDING_EDGE
| typeof EXPERIMENTAL_FEATURE_FIX_ABSOLUTE_TRAILING_COLUMN_MARGIN;
export type FlexDirection =
| typeof FLEX_DIRECTION_COLUMN
| typeof FLEX_DIRECTION_COLUMN_REVERSE
| typeof FLEX_DIRECTION_ROW
| typeof FLEX_DIRECTION_ROW_REVERSE;
export type Gutter =
| typeof GUTTER_COLUMN
| typeof GUTTER_ROW
| typeof GUTTER_ALL;
export type Justify =
| typeof JUSTIFY_FLEX_START
| typeof JUSTIFY_CENTER
| typeof JUSTIFY_FLEX_END
| typeof JUSTIFY_SPACE_BETWEEN
| typeof JUSTIFY_SPACE_AROUND
| typeof JUSTIFY_SPACE_EVENLY;
export type LogLevel =
| typeof LOG_LEVEL_ERROR
| typeof LOG_LEVEL_WARN
| typeof LOG_LEVEL_INFO
| typeof LOG_LEVEL_DEBUG
| typeof LOG_LEVEL_VERBOSE
| typeof LOG_LEVEL_FATAL;
export type MeasureMode =
| typeof MEASURE_MODE_UNDEFINED
| typeof MEASURE_MODE_EXACTLY
| typeof MEASURE_MODE_AT_MOST;
export type NodeType =
| typeof NODE_TYPE_DEFAULT
| typeof NODE_TYPE_TEXT;
export type Overflow =
| typeof OVERFLOW_VISIBLE
| typeof OVERFLOW_HIDDEN
| typeof OVERFLOW_SCROLL;
export type PositionType =
| typeof POSITION_TYPE_STATIC
| typeof POSITION_TYPE_RELATIVE
| typeof POSITION_TYPE_ABSOLUTE;
export type PrintOptions =
| typeof PRINT_OPTIONS_LAYOUT
| typeof PRINT_OPTIONS_STYLE
| typeof PRINT_OPTIONS_CHILDREN;
export type Unit =
| typeof UNIT_UNDEFINED
| typeof UNIT_POINT
| typeof UNIT_PERCENT
| typeof UNIT_AUTO;
export type Wrap =
| typeof WRAP_NO_WRAP
| typeof WRAP_WRAP
| typeof WRAP_WRAP_REVERSE;

View File

@@ -1,97 +0,0 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
// @generated by enums.py
exports.ALIGN_AUTO = 0;
exports.ALIGN_FLEX_START = 1;
exports.ALIGN_CENTER = 2;
exports.ALIGN_FLEX_END = 3;
exports.ALIGN_STRETCH = 4;
exports.ALIGN_BASELINE = 5;
exports.ALIGN_SPACE_BETWEEN = 6;
exports.ALIGN_SPACE_AROUND = 7;
exports.DIMENSION_WIDTH = 0;
exports.DIMENSION_HEIGHT = 1;
exports.DIRECTION_INHERIT = 0;
exports.DIRECTION_LTR = 1;
exports.DIRECTION_RTL = 2;
exports.DISPLAY_FLEX = 0;
exports.DISPLAY_NONE = 1;
exports.EDGE_LEFT = 0;
exports.EDGE_TOP = 1;
exports.EDGE_RIGHT = 2;
exports.EDGE_BOTTOM = 3;
exports.EDGE_START = 4;
exports.EDGE_END = 5;
exports.EDGE_HORIZONTAL = 6;
exports.EDGE_VERTICAL = 7;
exports.EDGE_ALL = 8;
exports.ERRATA_NONE = 0;
exports.ERRATA_STRETCH_FLEX_BASIS = 1;
exports.ERRATA_ALL = 2147483647;
exports.ERRATA_CLASSIC = 2147483646;
exports.EXPERIMENTAL_FEATURE_WEB_FLEX_BASIS = 0;
exports.EXPERIMENTAL_FEATURE_ABSOLUTE_PERCENTAGE_AGAINST_PADDING_EDGE = 1;
exports.EXPERIMENTAL_FEATURE_FIX_ABSOLUTE_TRAILING_COLUMN_MARGIN = 2;
exports.FLEX_DIRECTION_COLUMN = 0;
exports.FLEX_DIRECTION_COLUMN_REVERSE = 1;
exports.FLEX_DIRECTION_ROW = 2;
exports.FLEX_DIRECTION_ROW_REVERSE = 3;
exports.GUTTER_COLUMN = 0;
exports.GUTTER_ROW = 1;
exports.GUTTER_ALL = 2;
exports.JUSTIFY_FLEX_START = 0;
exports.JUSTIFY_CENTER = 1;
exports.JUSTIFY_FLEX_END = 2;
exports.JUSTIFY_SPACE_BETWEEN = 3;
exports.JUSTIFY_SPACE_AROUND = 4;
exports.JUSTIFY_SPACE_EVENLY = 5;
exports.LOG_LEVEL_ERROR = 0;
exports.LOG_LEVEL_WARN = 1;
exports.LOG_LEVEL_INFO = 2;
exports.LOG_LEVEL_DEBUG = 3;
exports.LOG_LEVEL_VERBOSE = 4;
exports.LOG_LEVEL_FATAL = 5;
exports.MEASURE_MODE_UNDEFINED = 0;
exports.MEASURE_MODE_EXACTLY = 1;
exports.MEASURE_MODE_AT_MOST = 2;
exports.NODE_TYPE_DEFAULT = 0;
exports.NODE_TYPE_TEXT = 1;
exports.OVERFLOW_VISIBLE = 0;
exports.OVERFLOW_HIDDEN = 1;
exports.OVERFLOW_SCROLL = 2;
exports.POSITION_TYPE_STATIC = 0;
exports.POSITION_TYPE_RELATIVE = 1;
exports.POSITION_TYPE_ABSOLUTE = 2;
exports.PRINT_OPTIONS_LAYOUT = 1;
exports.PRINT_OPTIONS_STYLE = 2;
exports.PRINT_OPTIONS_CHILDREN = 4;
exports.UNIT_UNDEFINED = 0;
exports.UNIT_POINT = 1;
exports.UNIT_PERCENT = 2;
exports.UNIT_AUTO = 3;
exports.WRAP_NO_WRAP = 0;
exports.WRAP_WRAP = 1;
exports.WRAP_WRAP_REVERSE = 2;

View File

@@ -0,0 +1,208 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
// @generated by enums.py
export enum Align {
Auto = 0,
FlexStart = 1,
Center = 2,
FlexEnd = 3,
Stretch = 4,
Baseline = 5,
SpaceBetween = 6,
SpaceAround = 7,
}
export enum Dimension {
Width = 0,
Height = 1,
}
export enum Direction {
Inherit = 0,
LTR = 1,
RTL = 2,
}
export enum Display {
Flex = 0,
None = 1,
}
export enum Edge {
Left = 0,
Top = 1,
Right = 2,
Bottom = 3,
Start = 4,
End = 5,
Horizontal = 6,
Vertical = 7,
All = 8,
}
export enum Errata {
None = 0,
StretchFlexBasis = 1,
All = 2147483647,
Classic = 2147483646,
}
export enum ExperimentalFeature {
WebFlexBasis = 0,
AbsolutePercentageAgainstPaddingEdge = 1,
FixAbsoluteTrailingColumnMargin = 2,
}
export enum FlexDirection {
Column = 0,
ColumnReverse = 1,
Row = 2,
RowReverse = 3,
}
export enum Gutter {
Column = 0,
Row = 1,
All = 2,
}
export enum Justify {
FlexStart = 0,
Center = 1,
FlexEnd = 2,
SpaceBetween = 3,
SpaceAround = 4,
SpaceEvenly = 5,
}
export enum LogLevel {
Error = 0,
Warn = 1,
Info = 2,
Debug = 3,
Verbose = 4,
Fatal = 5,
}
export enum MeasureMode {
Undefined = 0,
Exactly = 1,
AtMost = 2,
}
export enum NodeType {
Default = 0,
Text = 1,
}
export enum Overflow {
Visible = 0,
Hidden = 1,
Scroll = 2,
}
export enum PositionType {
Static = 0,
Relative = 1,
Absolute = 2,
}
export enum PrintOptions {
Layout = 1,
Style = 2,
Children = 4,
}
export enum Unit {
Undefined = 0,
Point = 1,
Percent = 2,
Auto = 3,
}
export enum Wrap {
NoWrap = 0,
Wrap = 1,
WrapReverse = 2,
}
const constants = {
ALIGN_AUTO: Align.Auto,
ALIGN_FLEX_START: Align.FlexStart,
ALIGN_CENTER: Align.Center,
ALIGN_FLEX_END: Align.FlexEnd,
ALIGN_STRETCH: Align.Stretch,
ALIGN_BASELINE: Align.Baseline,
ALIGN_SPACE_BETWEEN: Align.SpaceBetween,
ALIGN_SPACE_AROUND: Align.SpaceAround,
DIMENSION_WIDTH: Dimension.Width,
DIMENSION_HEIGHT: Dimension.Height,
DIRECTION_INHERIT: Direction.Inherit,
DIRECTION_LTR: Direction.LTR,
DIRECTION_RTL: Direction.RTL,
DISPLAY_FLEX: Display.Flex,
DISPLAY_NONE: Display.None,
EDGE_LEFT: Edge.Left,
EDGE_TOP: Edge.Top,
EDGE_RIGHT: Edge.Right,
EDGE_BOTTOM: Edge.Bottom,
EDGE_START: Edge.Start,
EDGE_END: Edge.End,
EDGE_HORIZONTAL: Edge.Horizontal,
EDGE_VERTICAL: Edge.Vertical,
EDGE_ALL: Edge.All,
ERRATA_NONE: Errata.None,
ERRATA_STRETCH_FLEX_BASIS: Errata.StretchFlexBasis,
ERRATA_ALL: Errata.All,
ERRATA_CLASSIC: Errata.Classic,
EXPERIMENTAL_FEATURE_WEB_FLEX_BASIS: ExperimentalFeature.WebFlexBasis,
EXPERIMENTAL_FEATURE_ABSOLUTE_PERCENTAGE_AGAINST_PADDING_EDGE: ExperimentalFeature.AbsolutePercentageAgainstPaddingEdge,
EXPERIMENTAL_FEATURE_FIX_ABSOLUTE_TRAILING_COLUMN_MARGIN: ExperimentalFeature.FixAbsoluteTrailingColumnMargin,
FLEX_DIRECTION_COLUMN: FlexDirection.Column,
FLEX_DIRECTION_COLUMN_REVERSE: FlexDirection.ColumnReverse,
FLEX_DIRECTION_ROW: FlexDirection.Row,
FLEX_DIRECTION_ROW_REVERSE: FlexDirection.RowReverse,
GUTTER_COLUMN: Gutter.Column,
GUTTER_ROW: Gutter.Row,
GUTTER_ALL: Gutter.All,
JUSTIFY_FLEX_START: Justify.FlexStart,
JUSTIFY_CENTER: Justify.Center,
JUSTIFY_FLEX_END: Justify.FlexEnd,
JUSTIFY_SPACE_BETWEEN: Justify.SpaceBetween,
JUSTIFY_SPACE_AROUND: Justify.SpaceAround,
JUSTIFY_SPACE_EVENLY: Justify.SpaceEvenly,
LOG_LEVEL_ERROR: LogLevel.Error,
LOG_LEVEL_WARN: LogLevel.Warn,
LOG_LEVEL_INFO: LogLevel.Info,
LOG_LEVEL_DEBUG: LogLevel.Debug,
LOG_LEVEL_VERBOSE: LogLevel.Verbose,
LOG_LEVEL_FATAL: LogLevel.Fatal,
MEASURE_MODE_UNDEFINED: MeasureMode.Undefined,
MEASURE_MODE_EXACTLY: MeasureMode.Exactly,
MEASURE_MODE_AT_MOST: MeasureMode.AtMost,
NODE_TYPE_DEFAULT: NodeType.Default,
NODE_TYPE_TEXT: NodeType.Text,
OVERFLOW_VISIBLE: Overflow.Visible,
OVERFLOW_HIDDEN: Overflow.Hidden,
OVERFLOW_SCROLL: Overflow.Scroll,
POSITION_TYPE_STATIC: PositionType.Static,
POSITION_TYPE_RELATIVE: PositionType.Relative,
POSITION_TYPE_ABSOLUTE: PositionType.Absolute,
PRINT_OPTIONS_LAYOUT: PrintOptions.Layout,
PRINT_OPTIONS_STYLE: PrintOptions.Style,
PRINT_OPTIONS_CHILDREN: PrintOptions.Children,
UNIT_UNDEFINED: Unit.Undefined,
UNIT_POINT: Unit.Point,
UNIT_PERCENT: Unit.Percent,
UNIT_AUTO: Unit.Auto,
WRAP_NO_WRAP: Wrap.NoWrap,
WRAP_WRAP: Wrap.Wrap,
WRAP_WRAP_REVERSE: Wrap.WrapReverse,
}
export default constants

View File

@@ -24,7 +24,7 @@ import type {
Wrap, Wrap,
} from './generated/YGEnums'; } from './generated/YGEnums';
import type * as YGEnums from './generated/YGEnums'; import YGEnums from './generated/YGEnums';
type Layout = { type Layout = {
left: number; left: number;

View File

@@ -7,7 +7,7 @@
* @format * @format
*/ */
const CONSTANTS = require('./generated/YGEnums'); import YGEnums, {Unit, Direction} from './generated/YGEnums';
module.exports = lib => { module.exports = lib => {
function patch(prototype, name, fn) { function patch(prototype, name, fn) {
@@ -31,9 +31,9 @@ module.exports = lib => {
'setPadding', 'setPadding',
]) { ]) {
const methods = { const methods = {
[CONSTANTS.UNIT_POINT]: lib.Node.prototype[fnName], [Unit.Point]: lib.Node.prototype[fnName],
[CONSTANTS.UNIT_PERCENT]: lib.Node.prototype[`${fnName}Percent`], [Unit.Percent]: lib.Node.prototype[`${fnName}Percent`],
[CONSTANTS.UNIT_AUTO]: lib.Node.prototype[`${fnName}Auto`], [Unit.Auto]: lib.Node.prototype[`${fnName}Auto`],
}; };
patch(lib.Node.prototype, fnName, function (original, ...args) { patch(lib.Node.prototype, fnName, function (original, ...args) {
@@ -44,7 +44,7 @@ module.exports = lib => {
let unit, asNumber; let unit, asNumber;
if (value === 'auto') { if (value === 'auto') {
unit = CONSTANTS.UNIT_AUTO; unit = Unit.Auto;
asNumber = undefined; asNumber = undefined;
} else if (typeof value === 'object') { } else if (typeof value === 'object') {
unit = value.unit; unit = value.unit;
@@ -52,8 +52,8 @@ module.exports = lib => {
} else { } else {
unit = unit =
typeof value === 'string' && value.endsWith('%') typeof value === 'string' && value.endsWith('%')
? CONSTANTS.UNIT_PERCENT ? Unit.Percent
: CONSTANTS.UNIT_POINT; : Unit.Point;
asNumber = parseFloat(value); asNumber = parseFloat(value);
if (!Number.isNaN(value) && Number.isNaN(asNumber)) { if (!Number.isNaN(value) && Number.isNaN(asNumber)) {
throw new Error(`Invalid value ${value} for ${fnName}`); throw new Error(`Invalid value ${value} for ${fnName}`);
@@ -132,12 +132,7 @@ module.exports = lib => {
patch( patch(
lib.Node.prototype, lib.Node.prototype,
'calculateLayout', 'calculateLayout',
function ( function (original, width = NaN, height = NaN, direction = Direction.LTR) {
original,
width = NaN,
height = NaN,
direction = CONSTANTS.DIRECTION_LTR,
) {
// Just a small patch to add support for the function default parameters // Just a small patch to add support for the function default parameters
return original.call(this, width, height, direction); return original.call(this, width, height, direction);
}, },
@@ -146,6 +141,6 @@ module.exports = lib => {
return { return {
Config: lib.Config, Config: lib.Config,
Node: lib.Node, Node: lib.Node,
...CONSTANTS, ...YGEnums,
}; };
}; };