From 35f2d05921daa9191044ea8eaa88095bbb409333 Mon Sep 17 00:00:00 2001
From: Mathieu Dutour
Date: Wed, 22 Apr 2020 09:50:11 +0200
Subject: [PATCH 1/2] update deps
---
package.json | 30 +-
src/types/yoga-layout-prebuilt.d.ts | 410 ----------------------------
2 files changed, 15 insertions(+), 425 deletions(-)
delete mode 100644 src/types/yoga-layout-prebuilt.d.ts
diff --git a/package.json b/package.json
index 7e5ea03e..65f761a4 100644
--- a/package.json
+++ b/package.json
@@ -39,8 +39,8 @@
"watch": "run-s clean build:main && run-p \"build:main -- -w\" \"test:unit -- --watch\""
},
"dependencies": {
- "@lona/svg-model": "^1.0.4",
- "@sketch-hq/sketch-file-format-ts": "^4.0.0",
+ "@lona/svg-model": "^2.0.0",
+ "@sketch-hq/sketch-file-format-ts": "^4.0.3",
"airbnb-prop-types": "^2.15.0",
"error-stack-parser": "^2.0.6",
"invariant": "^2.2.2",
@@ -51,7 +51,7 @@
"pegjs": "^0.10.0",
"prop-types": "^15.7.2",
"seedrandom": "^3.0.5",
- "yoga-layout-prebuilt": "^1.9.3"
+ "yoga-layout-prebuilt": "^1.9.5"
},
"peerDependencies": {
"react": "*",
@@ -85,11 +85,11 @@
"@skpm/test-runner": "^0.4.1",
"@types/airbnb-prop-types": "^2.13.1",
"@types/invariant": "^2.2.31",
- "@types/jest": "^24.9.0",
- "@types/node": "^13.1.8",
+ "@types/jest": "^25.2.1",
+ "@types/node": "^13.13.2",
"@types/pegjs": "^0.10.1",
- "@types/react": "^16.9.17",
- "@types/react-test-renderer": "^16.9.1",
+ "@types/react": "^16.9.34",
+ "@types/react-test-renderer": "^16.9.2",
"@types/seedrandom": "^2.4.28",
"gitbook-cli": "^2.3.0",
"gitbook-plugin-anchorjs": "^2.1.0",
@@ -97,18 +97,18 @@
"gitbook-plugin-edit-link": "^2.0.2",
"gitbook-plugin-github": "^2.0.0",
"gitbook-plugin-prism": "^2.3.0",
- "jest": "^24.9.0",
- "jest-cli": "^24.9.0",
- "lint-staged": "^10.0.0",
+ "jest": "^25.4.0",
+ "jest-cli": "^25.4.0",
+ "lint-staged": "^10.1.7",
"npm-run-all": "^4.1.5",
"pre-commit": "^1.2.2",
- "prettier": "^1.19.1",
- "react": "^16.12.0",
- "react-test-renderer": "^16.12.0",
+ "prettier": "^2.0.5",
+ "react": "^16.13.1",
+ "react-test-renderer": "^16.13.1",
"sketchapp-json-flow-types": "^0.3.6",
"trash-cli": "^3.0.0",
- "ts-jest": "^24.3.0",
- "typescript": "^3.7.5"
+ "ts-jest": "^25.4.0",
+ "typescript": "^3.8.3"
},
"skpm": {
"test": {
diff --git a/src/types/yoga-layout-prebuilt.d.ts b/src/types/yoga-layout-prebuilt.d.ts
deleted file mode 100644
index d12caee4..00000000
--- a/src/types/yoga-layout-prebuilt.d.ts
+++ /dev/null
@@ -1,410 +0,0 @@
-declare module 'yoga-layout-prebuilt' {
- // Type definitions for yoga-layout 1.9
- // Project: https://github.com/facebook/yoga#readme
- // Definitions by: tnobody
- // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
- // TypeScript Version: 2.1
-
- export const ALIGN_AUTO: 0;
- export const ALIGN_COUNT: 8;
- export const ALIGN_FLEX_START: 1;
- export const ALIGN_CENTER: 2;
- export const ALIGN_FLEX_END: 3;
- export const ALIGN_STRETCH: 4;
- export const ALIGN_BASELINE: 5;
- export const ALIGN_SPACE_BETWEEN: 6;
- export const ALIGN_SPACE_AROUND: 7;
- export const DIMENSION_COUNT: 2;
- export const DIMENSION_WIDTH: 0;
- export const DIMENSION_HEIGHT: 1;
- export const DIRECTION_COUNT: 3;
- export const DIRECTION_INHERIT: 0;
- export const DIRECTION_LTR: 1;
- export const DIRECTION_RTL: 2;
- export const DISPLAY_COUNT: 2;
- export const DISPLAY_FLEX: 0;
- export const DISPLAY_NONE: 1;
- export const EDGE_COUNT: 9;
- export const EDGE_LEFT: 0;
- export const EDGE_TOP: 1;
- export const EDGE_RIGHT: 2;
- export const EDGE_BOTTOM: 3;
- export const EDGE_START: 4;
- export const EDGE_END: 5;
- export const EDGE_HORIZONTAL: 6;
- export const EDGE_VERTICAL: 7;
- export const EDGE_ALL: 8;
- export const EXPERIMENTAL_FEATURE_COUNT: 1;
- export const EXPERIMENTAL_FEATURE_WEB_FLEX_BASIS: 0;
- export const FLEX_DIRECTION_COUNT: 4;
- export const FLEX_DIRECTION_COLUMN: 0;
- export const FLEX_DIRECTION_COLUMN_REVERSE: 1;
- export const FLEX_DIRECTION_ROW: 2;
- export const FLEX_DIRECTION_ROW_REVERSE: 3;
- export const JUSTIFY_COUNT: 6;
- export const JUSTIFY_FLEX_START: 0;
- export const JUSTIFY_CENTER: 1;
- export const JUSTIFY_FLEX_END: 2;
- export const JUSTIFY_SPACE_BETWEEN: 3;
- export const JUSTIFY_SPACE_AROUND: 4;
- export const JUSTIFY_SPACE_EVENLY: 5;
- export const LOG_LEVEL_COUNT: 6;
- export const LOG_LEVEL_ERROR: 0;
- export const LOG_LEVEL_WARN: 1;
- export const LOG_LEVEL_INFO: 2;
- export const LOG_LEVEL_DEBUG: 3;
- export const LOG_LEVEL_VERBOSE: 4;
- export const LOG_LEVEL_FATAL: 5;
- export const MEASURE_MODE_COUNT: 3;
- export const MEASURE_MODE_UNDEFINED: 0;
- export const MEASURE_MODE_EXACTLY: 1;
- export const MEASURE_MODE_AT_MOST: 2;
- export const NODE_TYPE_COUNT: 2;
- export const NODE_TYPE_DEFAULT: 0;
- export const NODE_TYPE_TEXT: 1;
- export const OVERFLOW_COUNT: 3;
- export const OVERFLOW_VISIBLE: 0;
- export const OVERFLOW_HIDDEN: 1;
- export const OVERFLOW_SCROLL: 2;
- export const POSITION_TYPE_COUNT: 2;
- export const POSITION_TYPE_RELATIVE: 0;
- export const POSITION_TYPE_ABSOLUTE: 1;
- export const PRINT_OPTIONS_COUNT: 3;
- export const PRINT_OPTIONS_LAYOUT: 1;
- export const PRINT_OPTIONS_STYLE: 2;
- export const PRINT_OPTIONS_CHILDREN: 4;
- export const UNIT_COUNT: 4;
- export const UNIT_UNDEFINED: 0;
- export const UNIT_POINT: 1;
- export const UNIT_PERCENT: 2;
- export const UNIT_AUTO: 3;
- export const WRAP_COUNT: 3;
- export const WRAP_NO_WRAP: 0;
- export const WRAP_WRAP: 1;
- export const WRAP_WRAP_REVERSE: 2;
-
- interface ConstantsStatic {
- readonly ALIGN_AUTO: typeof ALIGN_AUTO;
- readonly ALIGN_COUNT: typeof ALIGN_COUNT;
- readonly ALIGN_FLEX_START: typeof ALIGN_FLEX_START;
- readonly ALIGN_CENTER: typeof ALIGN_CENTER;
- readonly ALIGN_FLEX_END: typeof ALIGN_FLEX_END;
- readonly ALIGN_STRETCH: typeof ALIGN_STRETCH;
- readonly ALIGN_BASELINE: typeof ALIGN_BASELINE;
- readonly ALIGN_SPACE_BETWEEN: typeof ALIGN_SPACE_BETWEEN;
- readonly ALIGN_SPACE_AROUND: typeof ALIGN_SPACE_AROUND;
- readonly DIMENSION_COUNT: typeof DIMENSION_COUNT;
- readonly DIMENSION_WIDTH: typeof DIMENSION_WIDTH;
- readonly DIMENSION_HEIGHT: typeof DIMENSION_HEIGHT;
- readonly DIRECTION_COUNT: typeof DIRECTION_COUNT;
- readonly DIRECTION_INHERIT: typeof DIRECTION_INHERIT;
- readonly DIRECTION_LTR: typeof DIRECTION_LTR;
- readonly DIRECTION_RTL: typeof DIRECTION_RTL;
- readonly DISPLAY_COUNT: typeof DISPLAY_COUNT;
- readonly DISPLAY_FLEX: typeof DISPLAY_FLEX;
- readonly DISPLAY_NONE: typeof DISPLAY_NONE;
- readonly EDGE_COUNT: typeof EDGE_COUNT;
- readonly EDGE_LEFT: typeof EDGE_LEFT;
- readonly EDGE_TOP: typeof EDGE_TOP;
- readonly EDGE_RIGHT: typeof EDGE_RIGHT;
- readonly EDGE_BOTTOM: typeof EDGE_BOTTOM;
- readonly EDGE_START: typeof EDGE_START;
- readonly EDGE_END: typeof EDGE_END;
- readonly EDGE_HORIZONTAL: typeof EDGE_HORIZONTAL;
- readonly EDGE_VERTICAL: typeof EDGE_VERTICAL;
- readonly EDGE_ALL: typeof EDGE_ALL;
- readonly EXPERIMENTAL_FEATURE_COUNT: typeof EXPERIMENTAL_FEATURE_COUNT;
- readonly EXPERIMENTAL_FEATURE_WEB_FLEX_BASIS: typeof EXPERIMENTAL_FEATURE_WEB_FLEX_BASIS;
- readonly FLEX_DIRECTION_COUNT: typeof FLEX_DIRECTION_COUNT;
- readonly FLEX_DIRECTION_COLUMN: typeof FLEX_DIRECTION_COLUMN;
- readonly FLEX_DIRECTION_COLUMN_REVERSE: typeof FLEX_DIRECTION_COLUMN_REVERSE;
- readonly FLEX_DIRECTION_ROW: typeof FLEX_DIRECTION_ROW;
- readonly FLEX_DIRECTION_ROW_REVERSE: typeof FLEX_DIRECTION_ROW_REVERSE;
- readonly JUSTIFY_COUNT: typeof JUSTIFY_COUNT;
- readonly JUSTIFY_FLEX_START: typeof JUSTIFY_FLEX_START;
- readonly JUSTIFY_CENTER: typeof JUSTIFY_CENTER;
- readonly JUSTIFY_FLEX_END: typeof JUSTIFY_FLEX_END;
- readonly JUSTIFY_SPACE_BETWEEN: typeof JUSTIFY_SPACE_BETWEEN;
- readonly JUSTIFY_SPACE_AROUND: typeof JUSTIFY_SPACE_AROUND;
- readonly JUSTIFY_SPACE_EVENLY: typeof JUSTIFY_SPACE_EVENLY;
- readonly LOG_LEVEL_COUNT: typeof LOG_LEVEL_COUNT;
- readonly LOG_LEVEL_ERROR: typeof LOG_LEVEL_ERROR;
- readonly LOG_LEVEL_WARN: typeof LOG_LEVEL_WARN;
- readonly LOG_LEVEL_INFO: typeof LOG_LEVEL_INFO;
- readonly LOG_LEVEL_DEBUG: typeof LOG_LEVEL_DEBUG;
- readonly LOG_LEVEL_VERBOSE: typeof LOG_LEVEL_VERBOSE;
- readonly LOG_LEVEL_FATAL: typeof LOG_LEVEL_FATAL;
- readonly MEASURE_MODE_COUNT: typeof MEASURE_MODE_COUNT;
- readonly MEASURE_MODE_UNDEFINED: typeof MEASURE_MODE_UNDEFINED;
- readonly MEASURE_MODE_EXACTLY: typeof MEASURE_MODE_EXACTLY;
- readonly MEASURE_MODE_AT_MOST: typeof MEASURE_MODE_AT_MOST;
- readonly NODE_TYPE_COUNT: typeof NODE_TYPE_COUNT;
- readonly NODE_TYPE_DEFAULT: typeof NODE_TYPE_DEFAULT;
- readonly NODE_TYPE_TEXT: typeof NODE_TYPE_TEXT;
- readonly OVERFLOW_COUNT: typeof OVERFLOW_COUNT;
- readonly OVERFLOW_VISIBLE: typeof OVERFLOW_VISIBLE;
- readonly OVERFLOW_HIDDEN: typeof OVERFLOW_HIDDEN;
- readonly OVERFLOW_SCROLL: typeof OVERFLOW_SCROLL;
- readonly POSITION_TYPE_COUNT: typeof POSITION_TYPE_COUNT;
- readonly POSITION_TYPE_RELATIVE: typeof POSITION_TYPE_RELATIVE;
- readonly POSITION_TYPE_ABSOLUTE: typeof POSITION_TYPE_ABSOLUTE;
- readonly PRINT_OPTIONS_COUNT: typeof PRINT_OPTIONS_COUNT;
- readonly PRINT_OPTIONS_LAYOUT: typeof PRINT_OPTIONS_LAYOUT;
- readonly PRINT_OPTIONS_STYLE: typeof PRINT_OPTIONS_STYLE;
- readonly PRINT_OPTIONS_CHILDREN: typeof PRINT_OPTIONS_CHILDREN;
- readonly UNIT_COUNT: typeof UNIT_COUNT;
- readonly UNIT_UNDEFINED: typeof UNIT_UNDEFINED;
- readonly UNIT_POINT: typeof UNIT_POINT;
- readonly UNIT_PERCENT: typeof UNIT_PERCENT;
- readonly UNIT_AUTO: typeof UNIT_AUTO;
- readonly WRAP_COUNT: typeof WRAP_COUNT;
- readonly WRAP_NO_WRAP: typeof WRAP_NO_WRAP;
- readonly WRAP_WRAP: typeof WRAP_WRAP;
- readonly WRAP_WRAP_REVERSE: typeof WRAP_WRAP_REVERSE;
- }
-
- export namespace Yoga {
- type YogaJustifyContent =
- | typeof JUSTIFY_CENTER
- | typeof JUSTIFY_FLEX_END
- | typeof JUSTIFY_FLEX_START
- | typeof JUSTIFY_SPACE_AROUND
- | typeof JUSTIFY_SPACE_BETWEEN
- | typeof JUSTIFY_SPACE_EVENLY;
-
- type YogaAlign =
- | typeof ALIGN_AUTO
- | typeof ALIGN_BASELINE
- | typeof ALIGN_CENTER
- | typeof ALIGN_FLEX_END
- | typeof ALIGN_FLEX_START
- | typeof ALIGN_SPACE_AROUND
- | typeof ALIGN_SPACE_BETWEEN
- | typeof ALIGN_STRETCH;
-
- type YogaFlexDirection =
- | typeof FLEX_DIRECTION_COLUMN
- | typeof FLEX_DIRECTION_COLUMN_REVERSE
- | typeof FLEX_DIRECTION_COUNT
- | typeof FLEX_DIRECTION_ROW
- | typeof FLEX_DIRECTION_ROW_REVERSE;
-
- type YogaDirection =
- | typeof DIRECTION_INHERIT
- | typeof DIRECTION_LTR
- | typeof DIRECTION_RTL;
-
- type YogaFlexWrap =
- | typeof WRAP_NO_WRAP
- | typeof WRAP_WRAP
- | typeof WRAP_WRAP_REVERSE;
-
- type YogaEdge =
- | 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;
-
- type YogaDisplay =
- | typeof DISPLAY_FLEX
- | typeof DISPLAY_NONE;
-
- type YogaUnit =
- | typeof UNIT_AUTO
- | typeof UNIT_PERCENT
- | typeof UNIT_POINT
- | typeof UNIT_UNDEFINED;
-
- type YogaOverflow =
- | typeof OVERFLOW_HIDDEN
- | typeof OVERFLOW_SCROLL
- | typeof OVERFLOW_VISIBLE;
-
- type YogaPositionType =
- | typeof POSITION_TYPE_ABSOLUTE
- | typeof POSITION_TYPE_RELATIVE;
-
- type YogaExperimentalFeature = typeof EXPERIMENTAL_FEATURE_WEB_FLEX_BASIS;
-
- interface YogaNode {
- calculateLayout(
- width?: number,
- height?: number,
- direction?: YogaDirection,
- ): void;
- copyStyle(node: YogaNode): void;
- free(): void;
- freeRecursive(): void;
- getAlignContent(): YogaAlign;
- getAlignItems(): YogaAlign;
- getAlignSelf(): YogaAlign;
- getAspectRatio(): number;
- getBorder(edge: YogaEdge): number;
- getChild(index: number): YogaNode;
- getChildCount(): number;
- getComputedBorder(edge: YogaEdge): number;
- getComputedBottom(): number;
- getComputedHeight(): number;
- getComputedLayout(): Layout;
- getComputedLeft(): number;
- getComputedMargin(edge: YogaEdge): number;
- getComputedPadding(edge: YogaEdge): number;
- getComputedRight(): number;
- getComputedTop(): number;
- getComputedWidth(): number;
- getDisplay(): YogaDisplay;
- getFlexBasis(): number;
- getFlexDirection(): YogaFlexDirection;
- getFlexGrow(): number;
- getFlexShrink(): number;
- getFlexWrap(): YogaFlexWrap;
- getHeight(): Value;
- getJustifyContent(): YogaJustifyContent;
- getMargin(edge: YogaEdge): Value;
- getMaxHeight(): Value;
- getMaxWidth(): Value;
- getMinHeight(): Value;
- getMinWidth(): Value;
- getOverflow(): YogaOverflow;
- getPadding(edge: YogaEdge): Value;
- getParent(): YogaNode | null;
- getPosition(edge: YogaEdge): Value;
- getPositionType(): YogaPositionType;
- getWidth(): Value;
- insertChild(child: YogaNode, index: number): void;
- isDirty(): boolean;
- markDirty(): void;
- removeChild(child: YogaNode): void;
- reset(): void;
- setAlignContent(alignContent: YogaAlign): void;
- setAlignItems(alignItems: YogaAlign): void;
- setAlignSelf(alignSelf: YogaAlign): void;
- setAspectRatio(aspectRatio: number): void;
- setBorder(edge: YogaEdge, borderWidth: number): void;
- setDisplay(display: YogaDisplay): void;
- setFlex(flex: number): void;
- setFlexBasis(flexBasis: number | string): void;
- setFlexBasisPercent(flexBasis: number): void;
- setFlexDirection(flexDirection: YogaFlexDirection): void;
- setFlexGrow(flexGrow: number): void;
- setFlexShrink(flexShrink: number): void;
- setFlexWrap(flexWrap: YogaFlexWrap): void;
- setHeight(height: number | string): void;
- setHeightAuto(): void;
- setHeightPercent(height: number): void;
- setJustifyContent(justifyContent: YogaJustifyContent): void;
- setMargin(edge: YogaEdge, margin: number): void;
- setMarginAuto(edge: YogaEdge): void;
- setMarginPercent(edge: YogaEdge, margin: number): void;
- setMaxHeight(maxHeight: number | string): void;
- setMaxHeightPercent(maxHeight: number): void;
- setMaxWidth(maxWidth: number | string): void;
- setMaxWidthPercent(maxWidth: number): void;
- setMeasureFunc(measureFunc: (() => any) | null): void;
- setMinHeight(minHeight: number | string): void;
- setMinHeightPercent(minHeight: number): void;
- setMinWidth(minWidth: number | string): void;
- setMinWidthPercent(minWidth: number): void;
- setOverflow(overflow: YogaOverflow): void;
- setPadding(edge: YogaEdge, padding: number | string): void;
- setPaddingPercent(edge: YogaEdge, padding: number): void;
- setPosition(edge: YogaEdge, position: number | string): void;
- setPositionPercent(edge: YogaEdge, position: number): void;
- setPositionType(positionType: YogaPositionType): void;
- setWidth(width: number | string): void;
- setWidthAuto(): void;
- setWidthPercent(width: number): void;
- unsetMeasureFun(): void;
- }
-
- interface YogaConfig {
- isExperimentalFeatureEnabled(feature: YogaExperimentalFeature): boolean;
- setExperimentalFeatureEnabled(
- feature: YogaExperimentalFeature,
- enabled: boolean,
- ): void;
- setPointScaleFactor(factor: number): void;
- }
- }
-
- export class Layout {
- readonly left: number;
- readonly right: number;
- readonly top: number;
- readonly bottom: number;
- readonly width: number;
- readonly height: number;
- constructor(
- left: number,
- right: number,
- top: number,
- bottom: number,
- width: number,
- height: number,
- );
-
- fromJs(expose: (
- left: number,
- right: number,
- top: number,
- bottom: number,
- width: number,
- height: number,
- ) => any): void;
-
- toString(): string;
- }
-
- export class Size {
- static fromJS(dim: { width: number, height: number }): Size;
-
- readonly width: number;
- readonly height: number;
-
- constructor(width: number, height: number);
-
- fromJS(expose: (width: number, height: number) => any): void;
-
- toString(): string;
- }
-
- export class Value {
- readonly unit: Yoga.YogaUnit | number;
- readonly value: number;
-
- constructor(unit: Yoga.YogaUnit | number, value: number);
-
- fromJS(expose: (unit: Yoga.YogaUnit | number, value: number) => any): void;
-
- toString(): string;
- valueOf(): number;
- }
-
- interface NodeStatic {
- create(): Yoga.YogaNode;
- createDefault(): Yoga.YogaNode;
- createWithConfig(config: Yoga.YogaConfig): Yoga.YogaNode;
- destroy(node: Yoga.YogaNode): any;
- }
-
- interface ConfigStatic {
- create(): Yoga.YogaConfig;
- destroy(config: Yoga.YogaConfig): any;
- }
-
- interface YogaStatic extends ConstantsStatic {
- Node: NodeStatic;
- Config: ConfigStatic;
- getInstanceCount(): number;
- }
-
- export const Yoga: YogaStatic;
-
- export default Yoga
-
-}
From c1c23cc08af0e93b3242f52d194b987531776688 Mon Sep 17 00:00:00 2001
From: Mathieu Dutour
Date: Wed, 22 Apr 2020 15:20:59 +0200
Subject: [PATCH 2/2] refactor around platforms
---
__tests__/jest/components/Artboard.tsx | 4 +-
__tests__/jest/components/Document.tsx | 2 +-
__tests__/jest/components/Image.tsx | 4 +-
__tests__/jest/components/Page.tsx | 2 +-
__tests__/jest/components/RedBox.tsx | 2 +-
__tests__/jest/components/Text.tsx | 4 +-
__tests__/jest/components/View.tsx | 4 +-
__tests__/jest/components/nodeImpl/Svg.tsx | 4 +-
__tests__/jest/index.ts | 6 +-
__tests__/jest/jsonUtils/computeTextTree.ts | 4 +-
__tests__/jest/jsonUtils/computeYogaNode.ts | 9 +-
__tests__/jest/jsonUtils/computeYogaTree.ts | 9 +-
__tests__/jest/jsonUtils/layerGroup.ts | 2 +-
__tests__/jest/reactTreeToFlexTree.ts | 7 +-
__tests__/jest/sharedStyles/TextStyles.ts | 19 +-
__tests__/jest/utils/isDefined.ts | 2 +-
__tests__/jest/utils/sortObjectKeys.ts | 2 +-
__tests__/jest/utils/zIndex.ts | 2 +-
.../basic-setup-typescript/src/my-command.tsx | 18 +-
examples/basic-setup/package.json | 4 +-
examples/basic-setup/src/my-command.js | 8 +-
examples/colors/src/main.js | 2 +-
examples/emotion/src/my-command.js | 2 +-
.../src/components/StrengthMeter.js | 2 +-
examples/form-validation/src/main.js | 2 +-
examples/foursquare-maps/src/App.js | 4 +-
examples/foursquare-maps/src/getVenues.js | 4 +-
examples/profile-cards-graphql/.flowconfig | 7 -
examples/profile-cards-graphql/src/main.js | 2 +-
.../src/components/Profile.js | 2 +-
examples/profile-cards-primitives/src/main.js | 2 +-
examples/profile-cards-primitives/src/web.js | 2 +-
.../src/main.js | 2 +-
examples/profile-cards/.flowconfig | 7 -
examples/profile-cards/src/main.js | 2 +-
examples/react-router-prototyping/src/App.js | 5 +-
.../src/components/AppBar.js | 28 +--
.../src/components/NavBar.js | 16 +-
examples/react-router-prototyping/src/main.js | 12 +-
.../src/routes/about.js | 4 +-
.../src/routes/home.js | 13 +-
.../src/routes/post.js | 32 +--
.../src/routes/profile.js | 5 +-
examples/styled-components/src/my-command.js | 12 +-
examples/styleguide/src/components/Palette.js | 2 +-
examples/styleguide/src/main.js | 2 +-
examples/styleguide/src/processColor.js | 2 +-
examples/timeline-airtable/src/main.js | 8 +-
package.json | 11 +-
src/Platform.ts | 4 +-
src/buildTree.ts | 20 +-
src/components/Artboard.tsx | 6 +-
src/components/Document.tsx | 2 +-
src/components/Image.tsx | 8 +-
src/components/ImageStylePropTypes.ts | 6 +-
src/components/Page.tsx | 6 +-
src/components/PageStylePropTypes.ts | 2 +-
src/components/RedBox.tsx | 6 +-
src/components/ResizeModePropTypes.ts | 11 +-
src/components/ResizingConstraintPropTypes.ts | 2 +-
src/components/ShadowsPropTypes.ts | 2 +-
src/components/Svg/Circle.tsx | 2 +-
src/components/Svg/ClipPath.tsx | 2 +-
src/components/Svg/Defs.tsx | 2 +-
src/components/Svg/Ellipse.tsx | 2 +-
src/components/Svg/G.tsx | 2 +-
src/components/Svg/Image.tsx | 2 +-
src/components/Svg/Line.tsx | 2 +-
src/components/Svg/LinearGradient.tsx | 2 +-
src/components/Svg/Path.tsx | 2 +-
src/components/Svg/Pattern.tsx | 2 +-
src/components/Svg/Polygon.tsx | 2 +-
src/components/Svg/Polyline.tsx | 2 +-
src/components/Svg/RadialGradient.tsx | 2 +-
src/components/Svg/Rect.tsx | 2 +-
src/components/Svg/Stop.tsx | 2 +-
src/components/Svg/Svg.tsx | 44 ++---
src/components/Svg/Symbol.tsx | 2 +-
src/components/Svg/TSpan.tsx | 2 +-
src/components/Svg/Text.tsx | 2 +-
src/components/Svg/TextPath.tsx | 2 +-
src/components/Svg/Use.tsx | 2 +-
src/components/Svg/index.tsx | 42 ++--
src/components/Text.tsx | 6 +-
src/components/TextStylePropTypes.ts | 4 +-
src/components/View.tsx | 10 +-
src/components/ViewStylePropTypes.ts | 2 +-
src/components/index.ts | 8 +
src/context.tsx | 18 +-
src/flexToSketchJSON.ts | 17 +-
src/index.common.ts | 6 +
src/index.sketch.ts | 41 ++++
src/index.ts | 103 +++++-----
src/jsonUtils/borders.ts | 2 +-
src/jsonUtils/computeTextTree.ts | 6 +-
src/jsonUtils/computeYogaNode.ts | 22 +--
src/jsonUtils/computeYogaTree.ts | 20 +-
src/jsonUtils/hotspotLayer.ts | 4 +-
src/jsonUtils/layerGroup.ts | 6 +-
.../graphics/curvePoint.ts | 0
.../graphics/path.ts | 0
.../graphics/point.ts | 0
.../graphics/rect.ts | 8 +-
.../graphics/types.ts | 0
.../index.sketch.ts} | 8 +-
.../makeSvgLayer.ts => makeSvgLayer/index.ts} | 16 +-
src/jsonUtils/models.ts | 19 +-
.../nodeImpl/createStringMeasurer.ts | 7 -
src/jsonUtils/nodeImpl/findFontName.ts | 6 -
.../nodeImpl/makeImageDataFromUrl.ts | 5 -
src/jsonUtils/nodeImpl/requireObjCBridge.ts | 11 --
src/jsonUtils/nodeImpl/requireSvgModel.ts | 4 -
src/jsonUtils/resizeConstraint.ts | 4 +-
src/jsonUtils/shapeLayers.ts | 2 +-
.../fromSJSON.ts} | 0
.../toSJSON.ts} | 0
src/jsonUtils/style.ts | 4 +-
src/jsonUtils/svgLayer.ts | 14 --
src/jsonUtils/textLayers.ts | 45 +++--
src/platformBridges/macos.ts | 11 ++
.../sketch}/createStringMeasurer.ts | 8 +-
.../sketch}/findFontName.ts | 8 +-
src/platformBridges/sketch/index.ts | 12 ++
.../sketch}/makeImageDataFromUrl.ts | 2 +-
src/render.tsx | 76 ++++----
src/renderToJSON.ts | 12 ++
src/renderers/ArtboardRenderer.ts | 6 +-
src/renderers/ImageRenderer.ts | 8 +-
src/renderers/SketchRenderer.ts | 16 +-
src/renderers/SvgRenderer.ts | 8 +-
src/renderers/SymbolInstanceRenderer.ts | 13 +-
src/renderers/SymbolMasterRenderer.ts | 4 +-
src/renderers/TextRenderer.ts | 14 +-
src/renderers/ViewRenderer.ts | 6 +-
src/renderers/index.ts | 14 +-
src/resets.ts | 4 +-
src/sharedStyles/TextStyles.ts | 182 +++++++++---------
src/stylesheet/expandStyle.ts | 2 +-
src/stylesheet/index.ts | 12 +-
src/symbol.tsx | 36 ++--
src/types/index.ts | 11 +-
src/types/node-sketch-bridge.d.ts | 1 +
src/utils/Context.ts | 4 +-
src/utils/createStringMeasurer.ts | 29 ++-
src/utils/findFont.ts | 14 --
src/utils/getImageDataFromURL.ts | 12 +-
src/utils/hasAnyDefined.ts | 6 +-
src/utils/hashStyle.ts | 6 +-
src/utils/isDefined.ts | 3 +-
src/utils/isNativeDocument.ts | 2 +-
src/utils/isNativePage.ts | 3 +-
src/utils/isNativeSymbolsPage.ts | 6 +-
src/utils/pick.ts | 6 +-
src/utils/processTransform/index.ts | 6 +-
src/utils/processTransform/matrix2D.ts | 2 +-
.../parseTransformOriginProp.ts | 5 +-
.../processTransform/parseTransformProp.ts | 4 +-
src/utils/same.ts | 4 +-
src/utils/sharedTextStyles.ts | 5 -
.../sharedTextStyles/index.sketch.ts} | 20 +-
.../sharedTextStyles/index.ts} | 4 +-
src/utils/sortObjectKeys.ts | 4 +-
src/utils/zIndex.ts | 4 +-
tsconfig.json | 14 +-
tsconfig.module.json | 9 +
165 files changed, 772 insertions(+), 807 deletions(-)
delete mode 100644 examples/profile-cards-graphql/.flowconfig
delete mode 100644 examples/profile-cards/.flowconfig
create mode 100644 src/components/index.ts
create mode 100644 src/index.common.ts
create mode 100644 src/index.sketch.ts
rename src/jsonUtils/{nodeImpl => makeSvgLayer}/graphics/curvePoint.ts (100%)
rename src/jsonUtils/{nodeImpl => makeSvgLayer}/graphics/path.ts (100%)
rename src/jsonUtils/{nodeImpl => makeSvgLayer}/graphics/point.ts (100%)
rename src/jsonUtils/{nodeImpl => makeSvgLayer}/graphics/rect.ts (92%)
rename src/jsonUtils/{nodeImpl => makeSvgLayer}/graphics/types.ts (100%)
rename src/jsonUtils/{sketchImpl/makeSvgLayer.ts => makeSvgLayer/index.sketch.ts} (82%)
rename src/jsonUtils/{nodeImpl/makeSvgLayer.ts => makeSvgLayer/index.ts} (85%)
delete mode 100644 src/jsonUtils/nodeImpl/createStringMeasurer.ts
delete mode 100644 src/jsonUtils/nodeImpl/findFontName.ts
delete mode 100644 src/jsonUtils/nodeImpl/makeImageDataFromUrl.ts
delete mode 100644 src/jsonUtils/nodeImpl/requireObjCBridge.ts
delete mode 100644 src/jsonUtils/nodeImpl/requireSvgModel.ts
rename src/jsonUtils/{sketchImpl/json-to-sketch.ts => sketchJson/fromSJSON.ts} (100%)
rename src/jsonUtils/{sketchImpl/sketch-to-json.ts => sketchJson/toSJSON.ts} (100%)
delete mode 100644 src/jsonUtils/svgLayer.ts
create mode 100644 src/platformBridges/macos.ts
rename src/{jsonUtils/sketchImpl => platformBridges/sketch}/createStringMeasurer.ts (92%)
rename src/{jsonUtils/sketchImpl => platformBridges/sketch}/findFontName.ts (95%)
create mode 100644 src/platformBridges/sketch/index.ts
rename src/{jsonUtils/sketchImpl => platformBridges/sketch}/makeImageDataFromUrl.ts (95%)
create mode 100644 src/renderToJSON.ts
create mode 100644 src/types/node-sketch-bridge.d.ts
delete mode 100644 src/utils/findFont.ts
delete mode 100644 src/utils/sharedTextStyles.ts
rename src/{jsonUtils/sketchImpl/sharedTextStyles.ts => utils/sharedTextStyles/index.sketch.ts} (83%)
rename src/{jsonUtils/nodeImpl/sharedTextStyles.ts => utils/sharedTextStyles/index.ts} (82%)
create mode 100644 tsconfig.module.json
diff --git a/__tests__/jest/components/Artboard.tsx b/__tests__/jest/components/Artboard.tsx
index 91d64a64..fa243be3 100644
--- a/__tests__/jest/components/Artboard.tsx
+++ b/__tests__/jest/components/Artboard.tsx
@@ -1,7 +1,7 @@
import * as React from 'react';
import * as renderer from 'react-test-renderer';
-import Artboard from '../../../src/components/Artboard';
-import StyleSheet from '../../../src/stylesheet';
+import { Artboard } from '../../../src/components/Artboard';
+import { StyleSheet } from '../../../src/stylesheet';
describe('', () => {
it('renders children', () => {
diff --git a/__tests__/jest/components/Document.tsx b/__tests__/jest/components/Document.tsx
index 7d61434d..0fb37b19 100644
--- a/__tests__/jest/components/Document.tsx
+++ b/__tests__/jest/components/Document.tsx
@@ -1,6 +1,6 @@
import * as React from 'react';
import * as renderer from 'react-test-renderer';
-import Document from '../../../src/components/Document';
+import { Document } from '../../../src/components/Document';
describe('', () => {
it('renders children', () => {
diff --git a/__tests__/jest/components/Image.tsx b/__tests__/jest/components/Image.tsx
index 23541181..833a6057 100644
--- a/__tests__/jest/components/Image.tsx
+++ b/__tests__/jest/components/Image.tsx
@@ -1,7 +1,7 @@
import * as React from 'react';
import * as renderer from 'react-test-renderer';
-import Image from '../../../src/components/Image';
-import StyleSheet from '../../../src/stylesheet';
+import { Image } from '../../../src/components/Image';
+import { StyleSheet } from '../../../src/stylesheet';
describe('', () => {
it('renders children', () => {
diff --git a/__tests__/jest/components/Page.tsx b/__tests__/jest/components/Page.tsx
index ab607f19..8d593f6a 100644
--- a/__tests__/jest/components/Page.tsx
+++ b/__tests__/jest/components/Page.tsx
@@ -1,6 +1,6 @@
import * as React from 'react';
import * as renderer from 'react-test-renderer';
-import Page from '../../../src/components/Page';
+import { Page } from '../../../src/components/Page';
describe('', () => {
it('renders children', () => {
diff --git a/__tests__/jest/components/RedBox.tsx b/__tests__/jest/components/RedBox.tsx
index 952e3b3f..6bacb297 100644
--- a/__tests__/jest/components/RedBox.tsx
+++ b/__tests__/jest/components/RedBox.tsx
@@ -1,6 +1,6 @@
import * as React from 'react';
import * as renderer from 'react-test-renderer';
-import RedBox from '../../../src/components/RedBox';
+import { RedBox } from '../../../src/components/RedBox';
describe('', () => {
it('renders simple errors', () => {
diff --git a/__tests__/jest/components/Text.tsx b/__tests__/jest/components/Text.tsx
index cf5876a6..a151a5bd 100644
--- a/__tests__/jest/components/Text.tsx
+++ b/__tests__/jest/components/Text.tsx
@@ -1,7 +1,7 @@
import * as React from 'react';
import * as renderer from 'react-test-renderer';
-import Text from '../../../src/components/Text';
-import StyleSheet from '../../../src/stylesheet';
+import { Text } from '../../../src/components/Text';
+import { StyleSheet } from '../../../src/stylesheet';
describe('', () => {
it('passes its children', () => {
diff --git a/__tests__/jest/components/View.tsx b/__tests__/jest/components/View.tsx
index 803551b6..52024341 100644
--- a/__tests__/jest/components/View.tsx
+++ b/__tests__/jest/components/View.tsx
@@ -1,7 +1,7 @@
import * as React from 'react';
import * as renderer from 'react-test-renderer';
-import View from '../../../src/components/View';
-import StyleSheet from '../../../src/stylesheet';
+import { View } from '../../../src/components/View';
+import { StyleSheet } from '../../../src/stylesheet';
describe('', () => {
it('passes its children', () => {
diff --git a/__tests__/jest/components/nodeImpl/Svg.tsx b/__tests__/jest/components/nodeImpl/Svg.tsx
index 97cf75b5..f8b71959 100644
--- a/__tests__/jest/components/nodeImpl/Svg.tsx
+++ b/__tests__/jest/components/nodeImpl/Svg.tsx
@@ -1,11 +1,11 @@
import * as React from 'react';
-import ReactSketch from '../../../../src';
+import * as ReactSketch from '../../../../src';
import Svg from '../../../../src/components/Svg';
jest.mock('../../../../src/jsonUtils/models', () => ({
...require.requireActual('../../../../src/jsonUtils/models'),
- generateID: jest.fn(seed => (seed ? `${seed}mockID` : 'mockID')),
+ generateID: jest.fn((seed) => (seed ? `${seed}mockID` : 'mockID')),
}));
describe('node ', () => {
diff --git a/__tests__/jest/index.ts b/__tests__/jest/index.ts
index 3bdd2c33..8ca01daa 100644
--- a/__tests__/jest/index.ts
+++ b/__tests__/jest/index.ts
@@ -1,8 +1,4 @@
-import ReactSketch from '../../src';
-jest.mock('../../src/jsonUtils/sketchImpl/createStringMeasurer');
-jest.mock('../../src/jsonUtils/sketchImpl/findFontName');
-jest.mock('../../src/jsonUtils/sketchImpl/makeImageDataFromUrl');
-jest.mock('../../src/jsonUtils/sketchImpl/makeSvgLayer');
+import * as ReactSketch from '../../src';
describe('public API', () => {
it('exports render', () => {
diff --git a/__tests__/jest/jsonUtils/computeTextTree.ts b/__tests__/jest/jsonUtils/computeTextTree.ts
index 2b285b3a..bb544c0c 100644
--- a/__tests__/jest/jsonUtils/computeTextTree.ts
+++ b/__tests__/jest/jsonUtils/computeTextTree.ts
@@ -1,5 +1,5 @@
-import computeTextTree from '../../../src/jsonUtils/computeTextTree';
-import Context from '../../../src/utils/Context';
+import { computeTextTree } from '../../../src/jsonUtils/computeTextTree';
+import { Context } from '../../../src/utils/Context';
// Example Text component tree
const treeStub = {
diff --git a/__tests__/jest/jsonUtils/computeYogaNode.ts b/__tests__/jest/jsonUtils/computeYogaNode.ts
index 58a232d2..a9c094a2 100644
--- a/__tests__/jest/jsonUtils/computeYogaNode.ts
+++ b/__tests__/jest/jsonUtils/computeYogaNode.ts
@@ -1,6 +1,7 @@
import yoga from 'yoga-layout-prebuilt';
-import computeYogaNode from '../../../src/jsonUtils/computeYogaNode';
-import Context from '../../../src/utils/Context';
+import { computeYogaNode } from '../../../src/jsonUtils/computeYogaNode';
+import { Context } from '../../../src/utils/Context';
+import bridge from '../../../src/platformBridges/macos';
const widthAndHeightStylesStub = {
width: 10,
@@ -30,10 +31,10 @@ const createYogaNodes = (
containerHeight?: number,
) => {
const yogaNodes = [];
- styles.forEach(style => {
+ styles.forEach((style) => {
const treeNode = createTreeNode(style);
const ctx = new Context();
- const { node } = computeYogaNode(treeNode, ctx);
+ const { node } = computeYogaNode(bridge)(treeNode, ctx);
node.calculateLayout(
containerWidth || undefined,
containerHeight || undefined,
diff --git a/__tests__/jest/jsonUtils/computeYogaTree.ts b/__tests__/jest/jsonUtils/computeYogaTree.ts
index 8a445adc..105af72f 100644
--- a/__tests__/jest/jsonUtils/computeYogaTree.ts
+++ b/__tests__/jest/jsonUtils/computeYogaTree.ts
@@ -1,6 +1,7 @@
import yoga from 'yoga-layout-prebuilt';
-import computeYogaTree from '../../../src/jsonUtils/computeYogaTree';
-import Context from '../../../src/utils/Context';
+import { computeYogaTree } from '../../../src/jsonUtils/computeYogaTree';
+import { Context } from '../../../src/utils/Context';
+import bridge from '../../../src/platformBridges/macos';
const treeRootStub = {
type: 'artboard',
@@ -36,11 +37,11 @@ const treeRootStub = {
],
};
-computeYogaTree(treeRootStub, new Context());
+computeYogaTree(bridge)(treeRootStub, new Context());
describe('Compute Yoga Tree', () => {
it('correctly create yoga nodes into layout tree', () => {
- const yogaTree = computeYogaTree(treeRootStub, new Context());
+ const yogaTree = computeYogaTree(bridge)(treeRootStub, new Context());
yogaTree.calculateLayout(undefined, undefined, yoga.DIRECTION_LTR);
expect(yogaTree.getComputedLayout()).toEqual({
bottom: 0,
diff --git a/__tests__/jest/jsonUtils/layerGroup.ts b/__tests__/jest/jsonUtils/layerGroup.ts
index f72e6012..5417b6c2 100644
--- a/__tests__/jest/jsonUtils/layerGroup.ts
+++ b/__tests__/jest/jsonUtils/layerGroup.ts
@@ -1,4 +1,4 @@
-import layerGroup from '../../../src/jsonUtils/layerGroup';
+import { layerGroup } from '../../../src/jsonUtils/layerGroup';
describe('layer group', () => {
it('is correctly constructed', () => {
diff --git a/__tests__/jest/reactTreeToFlexTree.ts b/__tests__/jest/reactTreeToFlexTree.ts
index 60c3cd6b..d8066d7f 100644
--- a/__tests__/jest/reactTreeToFlexTree.ts
+++ b/__tests__/jest/reactTreeToFlexTree.ts
@@ -1,7 +1,8 @@
import yoga from 'yoga-layout-prebuilt';
-import computeYogaTree from '../../src/jsonUtils/computeYogaTree';
-import Context from '../../src/utils/Context';
+import { computeYogaTree } from '../../src/jsonUtils/computeYogaTree';
+import { Context } from '../../src/utils/Context';
import { reactTreeToFlexTree } from '../../src/buildTree';
+import bridge from '../../src/platformBridges/macos';
const treeRootStub = {
type: 'artboard',
@@ -58,7 +59,7 @@ const treeRootStub = {
describe('Compute Flex Tree', () => {
it('correctly creates flex tree', () => {
- const yogaNode = computeYogaTree(treeRootStub, new Context());
+ const yogaNode = computeYogaTree(bridge)(treeRootStub, new Context());
yogaNode.calculateLayout(undefined, undefined, yoga.DIRECTION_LTR);
const tree = reactTreeToFlexTree(treeRootStub, yogaNode, new Context());
diff --git a/__tests__/jest/sharedStyles/TextStyles.ts b/__tests__/jest/sharedStyles/TextStyles.ts
index 80f13c5d..99a94713 100644
--- a/__tests__/jest/sharedStyles/TextStyles.ts
+++ b/__tests__/jest/sharedStyles/TextStyles.ts
@@ -1,3 +1,5 @@
+import bridge from '../../../src/platformBridges/macos';
+
let TextStyles;
let doc;
let sharedTextStyles;
@@ -9,21 +11,16 @@ beforeEach(() => {
getSketchVersion: jest.fn(() => 51),
}));
- TextStyles = require('../../../src/sharedStyles/TextStyles');
+ TextStyles = require('../../../src/sharedStyles/TextStyles').TextStyles;
sharedTextStyles = require('../../../src/utils/sharedTextStyles');
jest.mock('../../../src/utils/sharedTextStyles');
- jest.mock('../../../src/jsonUtils/sketchImpl/createStringMeasurer');
- jest.mock('../../../src/jsonUtils/sketchImpl/findFontName');
- jest.mock('../../../src/jsonUtils/sketchImpl/makeImageDataFromUrl');
- jest.mock('../../../src/jsonUtils/sketchImpl/makeSvgLayer');
-
- TextStyles = TextStyles.default;
- sharedTextStyles = sharedTextStyles.default;
+ TextStyles = TextStyles(() => bridge);
+ sharedTextStyles = sharedTextStyles.sharedTextStyles;
- sharedTextStyles.setDocument = jest.fn(doc => {
+ sharedTextStyles.setDocument = jest.fn((doc) => {
if (!doc) {
throw new Error('Please provide a sketch document reference');
}
@@ -144,11 +141,11 @@ describe('create', () => {
const firstStoredStyle = res[Object.keys(res)[0]].cssStyle;
- whitelist.forEach(key => {
+ whitelist.forEach((key) => {
expect(firstStoredStyle).toHaveProperty(key, true);
});
- blacklist.forEach(key => {
+ blacklist.forEach((key) => {
expect(firstStoredStyle).not.toHaveProperty(key);
});
});
diff --git a/__tests__/jest/utils/isDefined.ts b/__tests__/jest/utils/isDefined.ts
index 0be90b86..2707eb83 100644
--- a/__tests__/jest/utils/isDefined.ts
+++ b/__tests__/jest/utils/isDefined.ts
@@ -1,4 +1,4 @@
-import isDefined from '../../../src/utils/isDefined';
+import { isDefined } from '../../../src/utils/isDefined';
describe('isNullOrUndefined', () => {
it('correctly identify null', () => {
diff --git a/__tests__/jest/utils/sortObjectKeys.ts b/__tests__/jest/utils/sortObjectKeys.ts
index a543f854..cc28f9ee 100644
--- a/__tests__/jest/utils/sortObjectKeys.ts
+++ b/__tests__/jest/utils/sortObjectKeys.ts
@@ -1,4 +1,4 @@
-import sortObjectKeys from '../../../src/utils/sortObjectKeys';
+import { sortObjectKeys } from '../../../src/utils/sortObjectKeys';
test('simple example', () => {
const a = {
diff --git a/__tests__/jest/utils/zIndex.ts b/__tests__/jest/utils/zIndex.ts
index da1de221..3d1294cb 100644
--- a/__tests__/jest/utils/zIndex.ts
+++ b/__tests__/jest/utils/zIndex.ts
@@ -1,4 +1,4 @@
-import zIndex from '../../../src/utils/zIndex';
+import { zIndex } from '../../../src/utils/zIndex';
const noZIndexNode = {
props: {
diff --git a/examples/basic-setup-typescript/src/my-command.tsx b/examples/basic-setup-typescript/src/my-command.tsx
index 2de521ea..b431e578 100644
--- a/examples/basic-setup-typescript/src/my-command.tsx
+++ b/examples/basic-setup-typescript/src/my-command.tsx
@@ -8,14 +8,12 @@ const textColor = (hex: string) => {
if (vsWhite > 4) {
return '#FFF';
}
- return chroma(hex)
- .darken(3)
- .hex();
+ return chroma(hex).darken(3).hex();
};
interface SwatchProps {
- name: string,
- hex: string,
+ name: string;
+ hex: string;
}
const Swatch = ({ name, hex }: SwatchProps) => (
@@ -29,10 +27,7 @@ const Swatch = ({ name, hex }: SwatchProps) => (
padding: 8,
}}
>
-
+
{name}
@@ -42,7 +37,7 @@ const Swatch = ({ name, hex }: SwatchProps) => (
);
interface DocumentProps {
- colors: { [key: string]: string }
+ colors: { [key: string]: string };
}
const Document = ({ colors }: DocumentProps) => (
(
width: (96 + 8) * 4,
}}
>
- {Object.keys(colors).map(color => (
+ {Object.keys(colors).map((color) => (
))}
);
-
export default () => {
const colorList = {
Haus: '#F3F4F4',
diff --git a/examples/basic-setup/package.json b/examples/basic-setup/package.json
index 05d61df6..a2eee603 100644
--- a/examples/basic-setup/package.json
+++ b/examples/basic-setup/package.json
@@ -9,14 +9,14 @@
"scripts": {
"build": "skpm-build",
"watch": "skpm-build --watch",
- "render": "skpm-build --watch --run",
+ "render": "node ../../../skpm/packages/builder/lib/build.js --watch --run",
"render:once": "skpm-build --run",
"postinstall": "npm run build && skpm-link"
},
"author": "Jon Gold ",
"license": "MIT",
"devDependencies": {
- "@skpm/builder": "^0.7.4"
+ "@skpm/builder": "^0.7.5"
},
"dependencies": {
"chroma-js": "^1.2.2",
diff --git a/examples/basic-setup/src/my-command.js b/examples/basic-setup/src/my-command.js
index e39e029e..9c7bf422 100644
--- a/examples/basic-setup/src/my-command.js
+++ b/examples/basic-setup/src/my-command.js
@@ -4,14 +4,12 @@ import { render, Artboard, Text, View } from 'react-sketchapp';
import chroma from 'chroma-js';
// take a hex and give us a nice text color to put over it
-const textColor = hex => {
+const textColor = (hex) => {
const vsWhite = chroma.contrast(hex, 'white');
if (vsWhite > 4) {
return '#FFF';
}
- return chroma(hex)
- .darken(3)
- .hex();
+ return chroma(hex).darken(3).hex();
};
const Swatch = ({ name, hex }) => (
@@ -50,7 +48,7 @@ const Document = ({ colors }) => (
width: (96 + 8) * 4,
}}
>
- {Object.keys(colors).map(color => (
+ {Object.keys(colors).map((color) => (
))}
diff --git a/examples/colors/src/main.js b/examples/colors/src/main.js
index ddc54654..606c6e73 100644
--- a/examples/colors/src/main.js
+++ b/examples/colors/src/main.js
@@ -19,7 +19,7 @@ const Document = ({ colors, steps }) => {
return (
- {times(i => color(i / steps).hex(), steps).map((val, i) => (
+ {times((i) => color(i / steps).hex(), steps).map((val, i) => (
props.theme.backgroundColor}
+ background-color: ${(props) => props.theme.backgroundColor}
`;
const Description = emotion.Text`
diff --git a/examples/form-validation/src/components/StrengthMeter.js b/examples/form-validation/src/components/StrengthMeter.js
index 8a4e75f1..62be90ee 100644
--- a/examples/form-validation/src/components/StrengthMeter.js
+++ b/examples/form-validation/src/components/StrengthMeter.js
@@ -49,7 +49,7 @@ const styles = {
},
};
-const passwordStrength = password => {
+const passwordStrength = (password) => {
// Faux password checking
if (password.length <= 6) {
return 'short';
diff --git a/examples/form-validation/src/main.js b/examples/form-validation/src/main.js
index c1339be2..f2f136d4 100644
--- a/examples/form-validation/src/main.js
+++ b/examples/form-validation/src/main.js
@@ -15,7 +15,7 @@ const Page = ({ sessions }) => (
flexWrap: 'wrap',
}}
>
- {sessions.map(session => (
+ {sessions.map((session) => (
diff --git a/examples/foursquare-maps/src/App.js b/examples/foursquare-maps/src/App.js
index 1cc9c66b..6326d474 100644
--- a/examples/foursquare-maps/src/App.js
+++ b/examples/foursquare-maps/src/App.js
@@ -63,7 +63,7 @@ const Row = ({ name, location }) => (
Row.propTypes = Venue;
const App = ({ center, venues }) => {
- const pins = venues.map(v => ({
+ const pins = venues.map((v) => ({
latitude: v.location.lat,
longitude: v.location.lng,
}));
@@ -82,7 +82,7 @@ const App = ({ center, venues }) => {
markers={pins}
/>
- {venues.map(v => (
+ {venues.map((v) => (
))}
diff --git a/examples/foursquare-maps/src/getVenues.js b/examples/foursquare-maps/src/getVenues.js
index e27cb372..54caf4c7 100644
--- a/examples/foursquare-maps/src/getVenues.js
+++ b/examples/foursquare-maps/src/getVenues.js
@@ -16,8 +16,8 @@ export default () => {
});
return fetch(`https://api.foursquare.com/v2/venues/search?${params}`)
- .then(res => res.json())
- .then(data => ({
+ .then((res) => res.json())
+ .then((data) => ({
venues: data.response.venues,
latitude,
longitude,
diff --git a/examples/profile-cards-graphql/.flowconfig b/examples/profile-cards-graphql/.flowconfig
deleted file mode 100644
index 4a58bdcd..00000000
--- a/examples/profile-cards-graphql/.flowconfig
+++ /dev/null
@@ -1,7 +0,0 @@
-[ignore]
-
-[include]
-
-[libs]
-
-[options]
diff --git a/examples/profile-cards-graphql/src/main.js b/examples/profile-cards-graphql/src/main.js
index 52d1dd45..c10d8c0f 100644
--- a/examples/profile-cards-graphql/src/main.js
+++ b/examples/profile-cards-graphql/src/main.js
@@ -44,7 +44,7 @@ const Page = ({ users }) => (
width: users.length * 300,
}}
>
- {users.map(user => (
+ {users.map((user) => (
diff --git a/examples/profile-cards-primitives/src/components/Profile.js b/examples/profile-cards-primitives/src/components/Profile.js
index 8969b12c..80646ac5 100644
--- a/examples/profile-cards-primitives/src/components/Profile.js
+++ b/examples/profile-cards-primitives/src/components/Profile.js
@@ -27,7 +27,7 @@ const Subtitle = ({ children }) => {children} {children};
-const Profile = props => (
+const Profile = (props) => (
diff --git a/examples/profile-cards-primitives/src/main.js b/examples/profile-cards-primitives/src/main.js
index ee28e8c5..dc4e3d00 100644
--- a/examples/profile-cards-primitives/src/main.js
+++ b/examples/profile-cards-primitives/src/main.js
@@ -16,7 +16,7 @@ const Page = ({ users }) => (
width: users.length * 300,
}}
>
- {users.map(user => (
+ {users.map((user) => (
diff --git a/examples/profile-cards-primitives/src/web.js b/examples/profile-cards-primitives/src/web.js
index 775c4892..752ed16a 100644
--- a/examples/profile-cards-primitives/src/web.js
+++ b/examples/profile-cards-primitives/src/web.js
@@ -23,7 +23,7 @@ export default () => (
can use it in our web UI, and continue to use primitives, or mix them with DOM elements
- {DATA.map(user => (
+ {DATA.map((user) => (
diff --git a/examples/profile-cards-react-with-styles/src/main.js b/examples/profile-cards-react-with-styles/src/main.js
index a39475f7..71571fc1 100644
--- a/examples/profile-cards-react-with-styles/src/main.js
+++ b/examples/profile-cards-react-with-styles/src/main.js
@@ -17,7 +17,7 @@ const Page = ({ users }) => (
width: users.length * 300,
}}
>
- {users.map(user => (
+ {users.map((user) => (
))}
diff --git a/examples/profile-cards/.flowconfig b/examples/profile-cards/.flowconfig
deleted file mode 100644
index 4a58bdcd..00000000
--- a/examples/profile-cards/.flowconfig
+++ /dev/null
@@ -1,7 +0,0 @@
-[ignore]
-
-[include]
-
-[libs]
-
-[options]
diff --git a/examples/profile-cards/src/main.js b/examples/profile-cards/src/main.js
index 710d93d8..e46a4d4c 100644
--- a/examples/profile-cards/src/main.js
+++ b/examples/profile-cards/src/main.js
@@ -14,7 +14,7 @@ const Page = ({ users }) => (
width: users.length * 300,
}}
>
- {users.map(user => (
+ {users.map((user) => (
diff --git a/examples/react-router-prototyping/src/App.js b/examples/react-router-prototyping/src/App.js
index 0d6b778b..e3c3ed53 100644
--- a/examples/react-router-prototyping/src/App.js
+++ b/examples/react-router-prototyping/src/App.js
@@ -7,7 +7,10 @@ import Post from './routes/post';
import Profile from './routes/profile';
const App = () => (
-
+
{/* (Need to have menus/sidebars inside of a Route) */}
} />
diff --git a/examples/react-router-prototyping/src/components/AppBar.js b/examples/react-router-prototyping/src/components/AppBar.js
index 5f4bfb67..f0b645ac 100644
--- a/examples/react-router-prototyping/src/components/AppBar.js
+++ b/examples/react-router-prototyping/src/components/AppBar.js
@@ -10,20 +10,20 @@ const AppBar = () => (
height: 80,
paddingLeft: 16,
paddingRight: 16,
- }
- }>
-
-
- My Blog
-
+ }}
+ >
+
+ My Blog
diff --git a/examples/react-router-prototyping/src/components/NavBar.js b/examples/react-router-prototyping/src/components/NavBar.js
index 6c810c4f..48f402c3 100644
--- a/examples/react-router-prototyping/src/components/NavBar.js
+++ b/examples/react-router-prototyping/src/components/NavBar.js
@@ -5,23 +5,25 @@ import { Link } from 'react-router-primitives';
const MenuItem = ({ name, href }) => (
-
- {name}
-
+ {name}
-)
+);
const NavBar = () => (
-
- {[{ name: 'About Us', href: '/about' }].map((props => ))}
+ }}
+ >
+ {[{ name: 'About Us', href: '/about' }].map((props) => (
+
+ ))}
);
diff --git a/examples/react-router-prototyping/src/main.js b/examples/react-router-prototyping/src/main.js
index 4d3a8a6c..7fc006e2 100644
--- a/examples/react-router-prototyping/src/main.js
+++ b/examples/react-router-prototyping/src/main.js
@@ -4,10 +4,12 @@ import { render, Page, Document as RootDocument } from 'react-sketchapp';
import App from './App';
-const pages = [{
- name: 'App',
- component: App,
-}];
+const pages = [
+ {
+ name: 'App',
+ component: App,
+ },
+];
const Document = () => (
@@ -19,13 +21,11 @@ const Document = () => (
);
-
export default () => {
const data = context.document.documentData();
const pages = context.document.pages();
data.setCurrentPage(pages.firstObject());
-
render();
};
diff --git a/examples/react-router-prototyping/src/routes/about.js b/examples/react-router-prototyping/src/routes/about.js
index 6c1f625d..865f667f 100644
--- a/examples/react-router-prototyping/src/routes/about.js
+++ b/examples/react-router-prototyping/src/routes/about.js
@@ -7,9 +7,7 @@ const About = () => (
-
- About Us
-
+ About Us
diff --git a/examples/react-router-prototyping/src/routes/home.js b/examples/react-router-prototyping/src/routes/home.js
index e939a380..f2036b04 100644
--- a/examples/react-router-prototyping/src/routes/home.js
+++ b/examples/react-router-prototyping/src/routes/home.js
@@ -10,22 +10,19 @@ const PostSummary = () => (
-
- Title of a Blog Post
-
+ Title of a Blog Post
- Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
+ Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt
+ ut labore et dolore magna aliqua.
-
- {`> `}
-
+ {`> `}
Click here to read more
-)
+);
const Home = () => (
diff --git a/examples/react-router-prototyping/src/routes/post.js b/examples/react-router-prototyping/src/routes/post.js
index 767c79c1..e8f23c71 100644
--- a/examples/react-router-prototyping/src/routes/post.js
+++ b/examples/react-router-prototyping/src/routes/post.js
@@ -8,16 +8,16 @@ import NavBar from '../components/NavBar';
const posts = {
'1': {
title: 'Title of a Blog Post',
- content: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.',
+ content:
+ 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.',
author: {
id: 'john',
name: 'John',
- }
- }
-}
+ },
+ },
+};
const Post = ({ id }) => {
-
return (
@@ -26,20 +26,22 @@ const Post = ({ id }) => {
-
- {posts[id].title}
-
+ {posts[id].title}
-
-
- {posts[id].author.name}
-
+
+ {posts[id].author.name}
-
- {posts[id].content}
-
+ {posts[id].content}
)}
diff --git a/examples/react-router-prototyping/src/routes/profile.js b/examples/react-router-prototyping/src/routes/profile.js
index a5e85d21..2fd11ed1 100644
--- a/examples/react-router-prototyping/src/routes/profile.js
+++ b/examples/react-router-prototyping/src/routes/profile.js
@@ -4,7 +4,6 @@ import { View, Text } from 'react-sketchapp';
import AppBar from '../components/AppBar';
import NavBar from '../components/NavBar';
-
const Profile = ({ user }) => {
const name = user ? `${user.charAt(0).toUpperCase()}${user.slice(1)}` : 'User not found';
@@ -13,9 +12,7 @@ const Profile = ({ user }) => {
-
- {name}
-
+ {name}
);
diff --git a/examples/styled-components/src/my-command.js b/examples/styled-components/src/my-command.js
index 75673df5..f4c23ada 100644
--- a/examples/styled-components/src/my-command.js
+++ b/examples/styled-components/src/my-command.js
@@ -5,14 +5,12 @@ import { render } from 'react-sketchapp';
import chroma from 'chroma-js';
// take a hex and give us a nice text color to put over it
-const textColor = hex => {
+const textColor = (hex) => {
const vsWhite = chroma.contrast(hex, 'white');
if (vsWhite > 4) {
return '#FFF';
}
- return chroma(hex)
- .darken(3)
- .hex();
+ return chroma(hex).darken(3).hex();
};
const SwatchTile = styled.View`
@@ -20,13 +18,13 @@ const SwatchTile = styled.View`
width: 250px;
border-radius: 4px;
margin: 4px;
- background-color: ${props => props.hex};
+ background-color: ${(props) => props.hex};
justify-content: center;
align-items: center;
`;
const SwatchName = styled.Text`
- color: ${props => textColor(props.hex)};
+ color: ${(props) => textColor(props.hex)};
font-weight: bold;
`;
@@ -70,7 +68,7 @@ const Artboard = styled.View`
const Document = ({ colors }) => (
Max’s Sweaters
- {Object.keys(colors).map(color => (
+ {Object.keys(colors).map((color) => (
))}
diff --git a/examples/styleguide/src/components/Palette.js b/examples/styleguide/src/components/Palette.js
index e76c0273..7cb43dc8 100644
--- a/examples/styleguide/src/components/Palette.js
+++ b/examples/styleguide/src/components/Palette.js
@@ -12,7 +12,7 @@ const Palette = ({ colors }) => (
flexDirection: 'row',
}}
>
- {Object.keys(colors).map(name => (
+ {Object.keys(colors).map((name) => (
))}
diff --git a/examples/styleguide/src/main.js b/examples/styleguide/src/main.js
index 13f0961e..a0202520 100644
--- a/examples/styleguide/src/main.js
+++ b/examples/styleguide/src/main.js
@@ -17,7 +17,7 @@ const Document = ({ system }) => (
- {Object.keys(system.fonts).map(name => (
+ {Object.keys(system.fonts).map((name) => (
))}
diff --git a/examples/styleguide/src/processColor.js b/examples/styleguide/src/processColor.js
index 17e53c11..d660b825 100644
--- a/examples/styleguide/src/processColor.js
+++ b/examples/styleguide/src/processColor.js
@@ -7,7 +7,7 @@ const minimums = {
aaaLarge: 4.5,
};
-export default hex => {
+export default (hex) => {
const contrast = chroma.contrast(hex, 'white');
return {
hex,
diff --git a/examples/timeline-airtable/src/main.js b/examples/timeline-airtable/src/main.js
index ca75b318..7d29f48c 100644
--- a/examples/timeline-airtable/src/main.js
+++ b/examples/timeline-airtable/src/main.js
@@ -121,7 +121,7 @@ Row.propTypes = {
status: PropTypes.string,
};
-const Timeline = props => (
+const Timeline = (props) => (
{props.data.records.map(({ id, fields }) => (
@@ -146,9 +146,9 @@ Timeline.propTypes = {
export default () => {
fetch(API_ENDPOINT_URL)
- .then(res => res.json())
- .then(data => {
+ .then((res) => res.json())
+ .then((data) => {
render(, context.document.currentPage());
})
- .catch(e => console.error(e));
+ .catch((e) => console.error(e));
};
diff --git a/package.json b/package.json
index 65f761a4..3d9ad2d3 100644
--- a/package.json
+++ b/package.json
@@ -2,7 +2,10 @@
"name": "react-sketchapp",
"version": "3.2.0",
"description": "A React renderer for Sketch.app",
+ "sideEffects": false,
"main": "lib/index.js",
+ "module": "lib/module/index.js",
+ "sketch": "lib/module/index.sketch.js",
"types": "lib/index.d.ts",
"license": "MIT",
"author": "Jon Gold (http://jon.gold)",
@@ -18,6 +21,7 @@
"scripts": {
"build": "run-s clean && run-p build:*",
"build:main": "tsc -p tsconfig.json",
+ "build:module": "tsc -p tsconfig.module.json",
"fix": "run-s fix:*",
"fix:prettier": "prettier \"src/**/*.ts\" --write",
"clean": "trash lib",
@@ -73,12 +77,7 @@
},
"homepage": "https://github.com/airbnb/react-sketchapp",
"lint-staged": {
- "*.(j|t)sx?": [
- "npm run prettier:base"
- ],
- "*.md": [
- "npm run prettier:base"
- ]
+ "*.{js,jsx,ts,tsx,md}": "npm run prettier:base"
},
"devDependencies": {
"@skpm/babel-preset": "^0.2.1",
diff --git a/src/Platform.ts b/src/Platform.ts
index a5f529ec..a69ad9d8 100644
--- a/src/Platform.ts
+++ b/src/Platform.ts
@@ -1,7 +1,5 @@
-const Platform = {
+export const Platform = {
OS: 'sketch',
Version: 1,
select: (obj: { sketch: any }) => obj.sketch,
};
-
-export default Platform;
diff --git a/src/buildTree.ts b/src/buildTree.ts
index dfcd80f9..246f9b9d 100644
--- a/src/buildTree.ts
+++ b/src/buildTree.ts
@@ -1,13 +1,13 @@
import * as TestRenderer from 'react-test-renderer';
import yoga from 'yoga-layout-prebuilt';
-import Context from './utils/Context';
-import { TreeNode, TextNode } from './types';
-import hasAnyDefined from './utils/hasAnyDefined';
-import pick from './utils/pick';
-import computeYogaTree from './jsonUtils/computeYogaTree';
-import computeTextTree from './jsonUtils/computeTextTree';
+import { Context } from './utils/Context';
+import { TreeNode, TextNode, PlatformBridge } from './types';
+import { hasAnyDefined } from './utils/hasAnyDefined';
+import { pick } from './utils/pick';
+import { computeYogaTree } from './jsonUtils/computeYogaTree';
+import { computeTextTree } from './jsonUtils/computeTextTree';
import { INHERITABLE_FONT_STYLES } from './utils/constants';
-import zIndex from './utils/zIndex';
+import { zIndex } from './utils/zIndex';
export const reactTreeToFlexTree = (
node: TestRenderer.ReactTestRendererNode,
@@ -89,7 +89,7 @@ export const reactTreeToFlexTree = (
};
};
-const buildTree = (element: React.ReactElement) => {
+export const buildTree = (bridge: PlatformBridge) => (element: React.ReactElement) => {
let renderer: TestRenderer.ReactTestRenderer | undefined;
if (typeof TestRenderer.act !== 'undefined') {
@@ -109,11 +109,9 @@ const buildTree = (element: React.ReactElement) => {
if (!json) {
throw new Error('Cannot render react element');
}
- const yogaNode = computeYogaTree(json, new Context());
+ const yogaNode = computeYogaTree(bridge)(json, new Context());
yogaNode.calculateLayout(undefined, undefined, yoga.DIRECTION_LTR);
const tree = reactTreeToFlexTree(json, yogaNode, new Context());
return tree;
};
-
-export default buildTree;
diff --git a/src/components/Artboard.tsx b/src/components/Artboard.tsx
index b2338c15..75ec1c3b 100644
--- a/src/components/Artboard.tsx
+++ b/src/components/Artboard.tsx
@@ -1,8 +1,8 @@
import * as React from 'react';
import * as PropTypes from 'prop-types';
import { or } from 'airbnb-prop-types';
-import StyleSheet from '../stylesheet';
-import ViewStylePropTypes from './ViewStylePropTypes';
+import { StyleSheet } from '../stylesheet';
+import { ViewStylePropTypes } from './ViewStylePropTypes';
import { ArtboardProvider } from '../context';
const ViewportPropTypes = {
@@ -23,7 +23,7 @@ export const ArtboardPropTypes = {
export type Props = PropTypes.InferProps;
-export default class Artboard extends React.Component {
+export class Artboard extends React.Component {
static propTypes = ArtboardPropTypes;
static defaultProps = {
diff --git a/src/components/Document.tsx b/src/components/Document.tsx
index 87ea6df0..b8035694 100644
--- a/src/components/Document.tsx
+++ b/src/components/Document.tsx
@@ -7,7 +7,7 @@ export const DocumentPropTypes = {
type Props = PropTypes.InferProps;
-export default class Document extends React.Component {
+export class Document extends React.Component {
static propTypes = {
children: PropTypes.node,
};
diff --git a/src/components/Image.tsx b/src/components/Image.tsx
index c9769a6d..1d32ff14 100644
--- a/src/components/Image.tsx
+++ b/src/components/Image.tsx
@@ -2,9 +2,9 @@ import * as React from 'react';
import { FileFormat1 as FileFormat } from '@sketch-hq/sketch-file-format-ts';
import * as PropTypes from 'prop-types';
import { or } from 'airbnb-prop-types';
-import StyleSheet from '../stylesheet';
-import ResizeModePropTypes from './ResizeModePropTypes';
-import ImageStylePropTypes from './ImageStylePropTypes';
+import { StyleSheet } from '../stylesheet';
+import { ResizeModePropTypes } from './ResizeModePropTypes';
+import { ImageStylePropTypes } from './ImageStylePropTypes';
import { ViewPropTypes } from './View';
const ImageURISourcePropType = PropTypes.shape({
@@ -44,7 +44,7 @@ export const ImagePropTypes = {
export type Props = PropTypes.InferProps;
-export default class Image extends React.Component {
+export class Image extends React.Component {
static propTypes = ImagePropTypes;
static defaultProps = {
diff --git a/src/components/ImageStylePropTypes.ts b/src/components/ImageStylePropTypes.ts
index 255a99f9..61cdc1bf 100644
--- a/src/components/ImageStylePropTypes.ts
+++ b/src/components/ImageStylePropTypes.ts
@@ -1,7 +1,7 @@
-import ViewStylePropTypes from './ViewStylePropTypes';
-import ResizeModePropTypes from './ResizeModePropTypes';
+import { ViewStylePropTypes } from './ViewStylePropTypes';
+import { ResizeModePropTypes } from './ResizeModePropTypes';
-export default {
+export const ImageStylePropTypes = {
...ViewStylePropTypes,
resizeMode: ResizeModePropTypes,
};
diff --git a/src/components/Page.tsx b/src/components/Page.tsx
index 606cb272..b48e288e 100644
--- a/src/components/Page.tsx
+++ b/src/components/Page.tsx
@@ -1,8 +1,8 @@
import * as React from 'react';
import * as PropTypes from 'prop-types';
import { or } from 'airbnb-prop-types';
-import StyleSheet from '../stylesheet';
-import PageStylePropTypes from './PageStylePropTypes';
+import { StyleSheet } from '../stylesheet';
+import { PageStylePropTypes } from './PageStylePropTypes';
export const PagePropTypes = {
name: PropTypes.string,
@@ -12,7 +12,7 @@ export const PagePropTypes = {
type Props = PropTypes.InferProps;
-export default class Page extends React.Component {
+export class Page extends React.Component {
static propTypes = PagePropTypes;
render() {
diff --git a/src/components/PageStylePropTypes.ts b/src/components/PageStylePropTypes.ts
index ff8b4c56..dc2900bd 100644
--- a/src/components/PageStylePropTypes.ts
+++ b/src/components/PageStylePropTypes.ts
@@ -1 +1 @@
-export default {};
+export const PageStylePropTypes = {};
diff --git a/src/components/RedBox.tsx b/src/components/RedBox.tsx
index e02548b7..55c88016 100644
--- a/src/components/RedBox.tsx
+++ b/src/components/RedBox.tsx
@@ -1,8 +1,8 @@
import * as React from 'react';
import * as PropTypes from 'prop-types';
import ErrorStackParser from 'error-stack-parser';
-import Text from './Text';
-import View from './View';
+import { Text } from './Text';
+import { View } from './View';
type StackFrame = {
isConstrutor?: boolean;
@@ -48,7 +48,7 @@ export const ErrorBoxPropTypes = {
type Props = PropTypes.InferProps;
-export default class RedBox extends React.Component {
+export class RedBox extends React.Component {
static propTypes = ErrorBoxPropTypes;
static defaultProps = {
diff --git a/src/components/ResizeModePropTypes.ts b/src/components/ResizeModePropTypes.ts
index 579b161d..e66a6d2b 100644
--- a/src/components/ResizeModePropTypes.ts
+++ b/src/components/ResizeModePropTypes.ts
@@ -1,5 +1,10 @@
import * as PropTypes from 'prop-types';
-const PropType = PropTypes.oneOf(['contain', 'cover', 'stretch', 'center', 'repeat', 'none']);
-
-export default PropType;
+export const ResizeModePropTypes = PropTypes.oneOf([
+ 'contain',
+ 'cover',
+ 'stretch',
+ 'center',
+ 'repeat',
+ 'none',
+]);
diff --git a/src/components/ResizingConstraintPropTypes.ts b/src/components/ResizingConstraintPropTypes.ts
index 664de159..2696bf74 100644
--- a/src/components/ResizingConstraintPropTypes.ts
+++ b/src/components/ResizingConstraintPropTypes.ts
@@ -1,6 +1,6 @@
import * as PropTypes from 'prop-types';
-export default {
+export const ResizingConstraintPropTypes = {
top: PropTypes.bool,
right: PropTypes.bool,
bottom: PropTypes.bool,
diff --git a/src/components/ShadowsPropTypes.ts b/src/components/ShadowsPropTypes.ts
index a7ace11b..47ed235a 100644
--- a/src/components/ShadowsPropTypes.ts
+++ b/src/components/ShadowsPropTypes.ts
@@ -1,6 +1,6 @@
import * as PropTypes from 'prop-types';
-export default {
+export const ShadowsPropTypes = {
shadowColor: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
shadowOffset: PropTypes.shape({
width: PropTypes.number,
diff --git a/src/components/Svg/Circle.tsx b/src/components/Svg/Circle.tsx
index 77402be6..3e0bcbc8 100755
--- a/src/components/Svg/Circle.tsx
+++ b/src/components/Svg/Circle.tsx
@@ -11,7 +11,7 @@ const propTypes = {
type Props = PropTypes.InferProps;
-export default class Circle extends React.Component {
+export class Circle extends React.Component {
static propTypes = propTypes;
static defaultProps = {
diff --git a/src/components/Svg/ClipPath.tsx b/src/components/Svg/ClipPath.tsx
index aa9adb02..af48a291 100755
--- a/src/components/Svg/ClipPath.tsx
+++ b/src/components/Svg/ClipPath.tsx
@@ -8,7 +8,7 @@ const propTypes = {
type Props = PropTypes.InferProps;
-export default class ClipPath extends React.Component {
+export class ClipPath extends React.Component {
static propTypes = propTypes;
render() {
diff --git a/src/components/Svg/Defs.tsx b/src/components/Svg/Defs.tsx
index 80911e66..b474f0c7 100755
--- a/src/components/Svg/Defs.tsx
+++ b/src/components/Svg/Defs.tsx
@@ -7,7 +7,7 @@ const propTypes = {
type Props = PropTypes.InferProps;
-export default class Defs extends React.Component {
+export class Defs extends React.Component {
static propTypes = propTypes;
render() {
diff --git a/src/components/Svg/Ellipse.tsx b/src/components/Svg/Ellipse.tsx
index ccfa9150..e767f50c 100755
--- a/src/components/Svg/Ellipse.tsx
+++ b/src/components/Svg/Ellipse.tsx
@@ -12,7 +12,7 @@ const propTypes = {
type Props = PropTypes.InferProps;
-export default class Ellipse extends React.Component {
+export class Ellipse extends React.Component {
static propTypes = propTypes;
static defaultProps = {
diff --git a/src/components/Svg/G.tsx b/src/components/Svg/G.tsx
index ec03ae2f..c05d42ad 100755
--- a/src/components/Svg/G.tsx
+++ b/src/components/Svg/G.tsx
@@ -9,7 +9,7 @@ const propTypes = {
type Props = PropTypes.InferProps;
-export default class G extends React.Component {
+export class G extends React.Component {
static propTypes = propTypes;
render() {
diff --git a/src/components/Svg/Image.tsx b/src/components/Svg/Image.tsx
index 2f1c14a8..d43047ab 100755
--- a/src/components/Svg/Image.tsx
+++ b/src/components/Svg/Image.tsx
@@ -15,7 +15,7 @@ const propTypes = {
type Props = PropTypes.InferProps;
-export default class SVGImage extends React.Component {
+export class SVGImage extends React.Component {
static propTypes = propTypes;
static defaultProps = {
diff --git a/src/components/Svg/Line.tsx b/src/components/Svg/Line.tsx
index 25c3afdf..df9f5879 100755
--- a/src/components/Svg/Line.tsx
+++ b/src/components/Svg/Line.tsx
@@ -12,7 +12,7 @@ const propTypes = {
type Props = PropTypes.InferProps;
-export default class Line extends React.Component {
+export class Line extends React.Component {
static propTypes = propTypes;
static defaultProps = {
diff --git a/src/components/Svg/LinearGradient.tsx b/src/components/Svg/LinearGradient.tsx
index e86cdc12..1710e580 100755
--- a/src/components/Svg/LinearGradient.tsx
+++ b/src/components/Svg/LinearGradient.tsx
@@ -14,7 +14,7 @@ const propTypes = {
type Props = PropTypes.InferProps;
-export default class LinearGradient extends React.Component {
+export class LinearGradient extends React.Component {
static propTypes = propTypes;
static defaultProps = {
diff --git a/src/components/Svg/Path.tsx b/src/components/Svg/Path.tsx
index 5624f5d9..2cf7f27d 100755
--- a/src/components/Svg/Path.tsx
+++ b/src/components/Svg/Path.tsx
@@ -9,7 +9,7 @@ const propTypes = {
type Props = PropTypes.InferProps;
-export default class Path extends React.Component {
+export class Path extends React.Component {
static propTypes = propTypes;
render() {
diff --git a/src/components/Svg/Pattern.tsx b/src/components/Svg/Pattern.tsx
index 8a82c9be..8adcacf1 100755
--- a/src/components/Svg/Pattern.tsx
+++ b/src/components/Svg/Pattern.tsx
@@ -15,7 +15,7 @@ const propTypes = {
type Props = PropTypes.InferProps;
-export default class Pattern extends React.Component {
+export class Pattern extends React.Component {
static propTypes = propTypes;
render() {
diff --git a/src/components/Svg/Polygon.tsx b/src/components/Svg/Polygon.tsx
index 612c2f89..06652643 100755
--- a/src/components/Svg/Polygon.tsx
+++ b/src/components/Svg/Polygon.tsx
@@ -9,7 +9,7 @@ const propTypes = {
type Props = PropTypes.InferProps;
-export default class Polygon extends React.Component {
+export class Polygon extends React.Component {
static displayName = 'Polygon';
static propTypes = propTypes;
diff --git a/src/components/Svg/Polyline.tsx b/src/components/Svg/Polyline.tsx
index 48aba54b..f8f68b4e 100755
--- a/src/components/Svg/Polyline.tsx
+++ b/src/components/Svg/Polyline.tsx
@@ -9,7 +9,7 @@ const propTypes = {
type Props = PropTypes.InferProps;
-export default class Polyline extends React.Component {
+export class Polyline extends React.Component {
static propTypes = propTypes;
static defaultProps = {
diff --git a/src/components/Svg/RadialGradient.tsx b/src/components/Svg/RadialGradient.tsx
index 094eab71..840a8950 100755
--- a/src/components/Svg/RadialGradient.tsx
+++ b/src/components/Svg/RadialGradient.tsx
@@ -17,7 +17,7 @@ const propTypes = {
type Props = PropTypes.InferProps;
-export default class RadialGradient extends React.Component {
+export class RadialGradient extends React.Component {
static propTypes = propTypes;
static defaultProps = {
diff --git a/src/components/Svg/Rect.tsx b/src/components/Svg/Rect.tsx
index 8f66a784..d43bd024 100755
--- a/src/components/Svg/Rect.tsx
+++ b/src/components/Svg/Rect.tsx
@@ -14,7 +14,7 @@ const propTypes = {
type Props = PropTypes.InferProps;
-export default class Rect extends React.Component {
+export class Rect extends React.Component {
static propTypes = propTypes;
static defaultProps = {
diff --git a/src/components/Svg/Stop.tsx b/src/components/Svg/Stop.tsx
index b933521d..d9dc0980 100755
--- a/src/components/Svg/Stop.tsx
+++ b/src/components/Svg/Stop.tsx
@@ -10,7 +10,7 @@ const propTypes = {
type Props = PropTypes.InferProps;
-export default class Stop extends React.Component {
+export class Stop extends React.Component {
static propTypes = propTypes;
static defaultProps = {
diff --git a/src/components/Svg/Svg.tsx b/src/components/Svg/Svg.tsx
index 755811b9..31bd8cbd 100755
--- a/src/components/Svg/Svg.tsx
+++ b/src/components/Svg/Svg.tsx
@@ -1,27 +1,27 @@
import * as React from 'react';
import * as PropTypes from 'prop-types';
import { ViewPropTypes } from '../View';
-import StyleSheet from '../../stylesheet';
-import Circle from './Circle';
-import ClipPath from './ClipPath';
-import Defs from './Defs';
-import Ellipse from './Ellipse';
-import G from './G';
-import Image from './Image';
-import Line from './Line';
-import LinearGradient from './LinearGradient';
-import Path from './Path';
-import Pattern from './Pattern';
-import Polygon from './Polygon';
-import Polyline from './Polyline';
-import RadialGradient from './RadialGradient';
-import Rect from './Rect';
-import Stop from './Stop';
-import Symbol from './Symbol';
-import Text from './Text';
-import TextPath from './TextPath';
-import TSpan from './TSpan';
-import Use from './Use';
+import { StyleSheet } from '../../stylesheet';
+import { Circle } from './Circle';
+import { ClipPath } from './ClipPath';
+import { Defs } from './Defs';
+import { Ellipse } from './Ellipse';
+import { G } from './G';
+import { SVGImage as Image } from './Image';
+import { Line } from './Line';
+import { LinearGradient } from './LinearGradient';
+import { Path } from './Path';
+import { Pattern } from './Pattern';
+import { Polygon } from './Polygon';
+import { Polyline } from './Polyline';
+import { RadialGradient } from './RadialGradient';
+import { Rect } from './Rect';
+import { Stop } from './Stop';
+import { Symbol } from './Symbol';
+import { Text } from './Text';
+import { TextPath } from './TextPath';
+import { TSpan } from './TSpan';
+import { Use } from './Use';
const propTypes = {
...ViewPropTypes,
@@ -37,7 +37,7 @@ const propTypes = {
export type Props = PropTypes.InferProps;
-export default class Svg extends React.Component {
+export class Svg extends React.Component {
static displayName = 'Svg';
static propTypes = propTypes;
diff --git a/src/components/Svg/Symbol.tsx b/src/components/Svg/Symbol.tsx
index b7f423f2..d89ad52e 100755
--- a/src/components/Svg/Symbol.tsx
+++ b/src/components/Svg/Symbol.tsx
@@ -10,7 +10,7 @@ const propTypes = {
type Props = PropTypes.InferProps;
-export default class Symbol extends React.Component {
+export class Symbol extends React.Component {
static propTypes = propTypes;
render() {
diff --git a/src/components/Svg/TSpan.tsx b/src/components/Svg/TSpan.tsx
index 8ebc68fe..523fa06a 100755
--- a/src/components/Svg/TSpan.tsx
+++ b/src/components/Svg/TSpan.tsx
@@ -4,7 +4,7 @@ import { textProps } from './props';
type Props = PropTypes.InferProps;
-export default class TSpan extends React.Component {
+export class TSpan extends React.Component {
static propTypes = textProps;
static childContextTypes = {
diff --git a/src/components/Svg/Text.tsx b/src/components/Svg/Text.tsx
index b443951c..378475dd 100755
--- a/src/components/Svg/Text.tsx
+++ b/src/components/Svg/Text.tsx
@@ -4,7 +4,7 @@ import { textProps } from './props';
type Props = PropTypes.InferProps;
-export default class Text extends React.Component {
+export class Text extends React.Component {
static propTypes = textProps;
static childContextTypes = {
diff --git a/src/components/Svg/TextPath.tsx b/src/components/Svg/TextPath.tsx
index 4f8c466e..501ac34e 100755
--- a/src/components/Svg/TextPath.tsx
+++ b/src/components/Svg/TextPath.tsx
@@ -6,7 +6,7 @@ type Props = PropTypes.InferProps;
const idExpReg = /^#(.+)$/;
-export default class TextPath extends React.Component {
+export class TextPath extends React.Component {
static propTypes = textPathProps;
render() {
diff --git a/src/components/Svg/Use.tsx b/src/components/Svg/Use.tsx
index 6decb496..8bed1a12 100755
--- a/src/components/Svg/Use.tsx
+++ b/src/components/Svg/Use.tsx
@@ -13,7 +13,7 @@ type Props = PropTypes.InferProps;
const idExpReg = /^#(.+)$/;
-export default class Use extends React.Component {
+export class Use extends React.Component {
static propTypes = propTypes;
render() {
diff --git a/src/components/Svg/index.tsx b/src/components/Svg/index.tsx
index 065cd2b4..751e9fa5 100644
--- a/src/components/Svg/index.tsx
+++ b/src/components/Svg/index.tsx
@@ -1,21 +1,21 @@
-export { default as Circle } from './Circle';
-export { default as ClipPath } from './ClipPath';
-export { default as Defs } from './Defs';
-export { default as Ellipse } from './Ellipse';
-export { default as G } from './G';
-export { default as Image } from './Image';
-export { default as Line } from './Line';
-export { default as LinearGradient } from './LinearGradient';
-export { default as Path } from './Path';
-export { default as Pattern } from './Pattern';
-export { default as Polygon } from './Polygon';
-export { default as Polyline } from './Polyline';
-export { default as RadialGradient } from './RadialGradient';
-export { default as Rect } from './Rect';
-export { default as Stop } from './Stop';
-export { default as Symbol } from './Symbol';
-export { default as Text } from './Text';
-export { default as TextPath } from './TextPath';
-export { default as TSpan } from './TSpan';
-export { default as Use } from './Use';
-export { default } from './Svg';
+export { Circle } from './Circle';
+export { ClipPath } from './ClipPath';
+export { Defs } from './Defs';
+export { Ellipse } from './Ellipse';
+export { G } from './G';
+export { SVGImage as Image } from './Image';
+export { Line } from './Line';
+export { LinearGradient } from './LinearGradient';
+export { Path } from './Path';
+export { Pattern } from './Pattern';
+export { Polygon } from './Polygon';
+export { Polyline } from './Polyline';
+export { RadialGradient } from './RadialGradient';
+export { Rect } from './Rect';
+export { Stop } from './Stop';
+export { Symbol } from './Symbol';
+export { Text } from './Text';
+export { TextPath } from './TextPath';
+export { TSpan } from './TSpan';
+export { Use } from './Use';
+export { Svg as default } from './Svg';
diff --git a/src/components/Text.tsx b/src/components/Text.tsx
index 0d20facd..9e7f709a 100644
--- a/src/components/Text.tsx
+++ b/src/components/Text.tsx
@@ -1,8 +1,8 @@
import * as React from 'react';
import * as PropTypes from 'prop-types';
import { or } from 'airbnb-prop-types';
-import StyleSheet from '../stylesheet';
-import TextStylePropTypes from './TextStylePropTypes';
+import { StyleSheet } from '../stylesheet';
+import { TextStylePropTypes } from './TextStylePropTypes';
import { ViewPropTypes } from './View';
export const TextPropTypes = {
@@ -18,7 +18,7 @@ export type Props = PropTypes.InferProps;
* Hello World!
*
*/
-export default class Text extends React.Component {
+export class Text extends React.Component {
static propTypes = TextPropTypes;
render() {
diff --git a/src/components/TextStylePropTypes.ts b/src/components/TextStylePropTypes.ts
index 0b72186c..1091f910 100644
--- a/src/components/TextStylePropTypes.ts
+++ b/src/components/TextStylePropTypes.ts
@@ -1,7 +1,7 @@
import * as PropTypes from 'prop-types';
-import ViewStylePropTypes, { Color } from './ViewStylePropTypes';
+import { ViewStylePropTypes, Color } from './ViewStylePropTypes';
-export default {
+export const TextStylePropTypes = {
...ViewStylePropTypes,
fontFamily: PropTypes.string,
fontSize: PropTypes.number,
diff --git a/src/components/View.tsx b/src/components/View.tsx
index de4b3569..3e519ecc 100644
--- a/src/components/View.tsx
+++ b/src/components/View.tsx
@@ -1,10 +1,10 @@
import * as React from 'react';
import * as PropTypes from 'prop-types';
import { or } from 'airbnb-prop-types';
-import StyleSheet from '../stylesheet';
-import ViewStylePropTypes from './ViewStylePropTypes';
-import ResizingConstraintPropTypes from './ResizingConstraintPropTypes';
-import ShadowsPropTypes from './ShadowsPropTypes';
+import { StyleSheet } from '../stylesheet';
+import { ViewStylePropTypes } from './ViewStylePropTypes';
+import { ResizingConstraintPropTypes } from './ResizingConstraintPropTypes';
+import { ShadowsPropTypes } from './ShadowsPropTypes';
export const ViewPropTypes = {
// TODO(lmr): do some nice warning stuff like RN does
@@ -28,7 +28,7 @@ export const ViewPropTypes = {
export type Props = PropTypes.InferProps;
-export default class View extends React.Component {
+export class View extends React.Component {
static propTypes = ViewPropTypes;
static defaultProps = {
diff --git a/src/components/ViewStylePropTypes.ts b/src/components/ViewStylePropTypes.ts
index 20d3f7ff..fbba2abf 100644
--- a/src/components/ViewStylePropTypes.ts
+++ b/src/components/ViewStylePropTypes.ts
@@ -12,7 +12,7 @@ export const Overflow = PropTypes.oneOf<'visible' | 'hidden' | 'scroll'>([
'scroll',
]);
-export default {
+export const ViewStylePropTypes = {
display: PropTypes.oneOf(['flex', 'none']),
color: Color,
shadowColor: Color,
diff --git a/src/components/index.ts b/src/components/index.ts
new file mode 100644
index 00000000..1ccb310b
--- /dev/null
+++ b/src/components/index.ts
@@ -0,0 +1,8 @@
+export { Document } from './Document';
+export { Page } from './Page';
+export { Artboard } from './Artboard';
+export { Image } from './Image';
+export { RedBox } from './RedBox';
+export * as Svg from './Svg';
+export { View } from './View';
+export { Text } from './Text';
diff --git a/src/context.tsx b/src/context.tsx
index c3f3a71d..669a8e0c 100644
--- a/src/context.tsx
+++ b/src/context.tsx
@@ -10,7 +10,7 @@ const initialArtboardState = {
fontScale: 1,
};
-const ArtboardContext = React.createContext({
+export const ArtboardContext = React.createContext({
state: initialArtboardState,
});
@@ -19,7 +19,7 @@ export const useWindowDimensions = () => {
const { width, height, scale, fontScale } = state || {};
return { width, height, scale, fontScale };
-}
+};
const ArtboardPropTypes = {
viewport: PropTypes.shape({
@@ -33,8 +33,8 @@ const ArtboardPropTypes = {
};
type ArtboardProps = PropTypes.InferProps & {
- children: any,
- style?: Style,
+ children: any;
+ style?: Style;
};
export const ArtboardProvider = ({ children, viewport, style }: ArtboardProps) => {
@@ -52,11 +52,5 @@ export const ArtboardProvider = ({ children, viewport, style }: ArtboardProps) =
fontScale: viewport.fontScale || oState.scale,
};
- return (
-
- {children}
-
- )
-}
-
-export default ArtboardContext;
+ return {children};
+};
diff --git a/src/flexToSketchJSON.ts b/src/flexToSketchJSON.ts
index aac3a3c4..1ec0d5d9 100644
--- a/src/flexToSketchJSON.ts
+++ b/src/flexToSketchJSON.ts
@@ -1,7 +1,7 @@
import { FileFormat1 as FileFormat } from '@sketch-hq/sketch-file-format-ts';
import * as renderers from './renderers';
-import SketchRenderer from './renderers/SketchRenderer';
-import { TreeNode } from './types';
+import { SketchRenderer } from './renderers/SketchRenderer';
+import { TreeNode, PlatformBridge } from './types';
function missingRendererError(type: string, annotations?: string) {
return new Error(
@@ -9,7 +9,7 @@ function missingRendererError(type: string, annotations?: string) {
);
}
-const flexToSketchJSON = (
+export const flexToSketchJSON = (bridge: PlatformBridge) => (
node: TreeNode | string,
):
| FileFormat.SymbolMaster
@@ -45,7 +45,7 @@ const flexToSketchJSON = (
throw missingRendererError(type);
}
- const renderer = new Renderer();
+ const renderer = new Renderer(bridge);
const groupLayer = renderer.renderGroupLayer(node);
if (groupLayer._class === 'symbolInstance') {
@@ -55,13 +55,14 @@ const flexToSketchJSON = (
const backingLayers = renderer.renderBackingLayers(node);
// stopping the walk down the tree if we have an svg
+ const curriedFlexToSketchJSON = flexToSketchJSON(bridge);
const sublayers =
- children && type !== 'sketch_svg' ? children.map(child => flexToSketchJSON(child)) : [];
+ children && type !== 'sketch_svg'
+ ? children.map((child) => curriedFlexToSketchJSON(child))
+ : [];
// Filter out anything null, undefined
- const layers = [...backingLayers, ...sublayers].filter(l => l);
+ const layers = [...backingLayers, ...sublayers].filter((l) => l);
return { ...groupLayer, layers };
};
-
-export default flexToSketchJSON;
diff --git a/src/index.common.ts b/src/index.common.ts
new file mode 100644
index 00000000..1cc33950
--- /dev/null
+++ b/src/index.common.ts
@@ -0,0 +1,6 @@
+export { Platform } from './Platform';
+export { StyleSheet } from './stylesheet';
+export { getSymbolComponentByName, getSymbolMasterByName, injectSymbols } from './symbol';
+export { useWindowDimensions } from './context';
+
+export * from './components';
diff --git a/src/index.sketch.ts b/src/index.sketch.ts
new file mode 100644
index 00000000..2bc870b3
--- /dev/null
+++ b/src/index.sketch.ts
@@ -0,0 +1,41 @@
+import { render as _render } from './render';
+import { renderToJSON as _renderToJSON } from './renderToJSON';
+import { makeSymbol as _makeSymbol, SymbolMasterProps } from './symbol';
+import {
+ SketchLayer,
+ WrappedSketchLayer,
+ SketchDocumentData,
+ WrappedSketchDocument,
+ SketchDocument,
+ PlatformBridge,
+} from './types';
+import { TextStyles as _TextStyles } from './sharedStyles/TextStyles';
+import SketchBridge from './platformBridges/sketch';
+
+export function render(
+ element: React.ReactElement,
+ container?: SketchLayer | WrappedSketchLayer,
+ platformBridge: PlatformBridge = SketchBridge,
+) {
+ return _render(platformBridge)(element, container);
+}
+
+export function renderToJSON(
+ element: React.ReactElement,
+ platformBridge: PlatformBridge = SketchBridge,
+) {
+ return _renderToJSON(platformBridge)(element);
+}
+
+export function makeSymbol(
+ Component: React.ComponentType,
+ symbolProps: string | SymbolMasterProps,
+ document: SketchDocumentData | SketchDocument | WrappedSketchDocument | undefined,
+ bridge: PlatformBridge = SketchBridge,
+) {
+ return _makeSymbol(bridge)(Component, symbolProps, document);
+}
+
+export const TextStyles = _TextStyles(() => SketchBridge);
+
+export * from './index.common';
diff --git a/src/index.ts b/src/index.ts
index 2c62e775..01e0982f 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -1,59 +1,46 @@
-import { render as _render, renderToJSON as _renderToJSON } from './render';
-import _Platform from './Platform';
-import _StyleSheet from './stylesheet';
-import _Document from './components/Document';
-import _Page from './components/Page';
-import _Artboard from './components/Artboard';
-import _Image from './components/Image';
-import _RedBox from './components/RedBox';
-import _Svg from './components/Svg';
-import _View from './components/View';
-import _Text from './components/Text';
-import _TextStyles from './sharedStyles/TextStyles';
+import { render as _render } from './render';
+import { renderToJSON as _renderToJSON } from './renderToJSON';
+import { makeSymbol as _makeSymbol, SymbolMasterProps } from './symbol';
+
import {
- makeSymbol as _makeSymbol,
- getSymbolComponentByName as _getSymbolComponentByName,
- getSymbolMasterByName as _getSymbolMasterByName,
- injectSymbols as _injectSymbols,
-} from './symbol';
-import { useWindowDimensions as _useWindowDimensions } from './context';
-
-export const render = _render;
-export const renderToJSON = _renderToJSON;
-export const StyleSheet = _StyleSheet;
-export const Document = _Document;
-export const Page = _Page;
-export const Artboard = _Artboard;
-export const Image = _Image;
-export const RedBox = _RedBox;
-export const Svg = _Svg;
-export const Text = _Text;
-export const TextStyles = _TextStyles;
-export const View = _View;
-export const Platform = _Platform;
-export const makeSymbol = _makeSymbol;
-export const getSymbolComponentByName = _getSymbolComponentByName;
-export const getSymbolMasterByName = _getSymbolMasterByName;
-export const injectSymbols = _injectSymbols;
-export const useWindowDimensions = _useWindowDimensions;
-
-export default {
- render,
- renderToJSON,
- StyleSheet,
- Document,
- Page,
- Artboard,
- Image,
- RedBox,
- Svg,
- Text,
- TextStyles,
- View,
- Platform,
- makeSymbol,
- getSymbolComponentByName,
- getSymbolMasterByName,
- injectSymbols,
- useWindowDimensions,
-};
+ SketchLayer,
+ WrappedSketchLayer,
+ SketchDocumentData,
+ WrappedSketchDocument,
+ SketchDocument,
+ PlatformBridge,
+} from './types';
+
+import { TextStyles as _TextStyles } from './sharedStyles/TextStyles';
+
+function getDefaultPlatformBridge() {
+ return require('./platformBridges/macos');
+}
+
+export function render(
+ element: React.ReactElement,
+ container?: SketchLayer | WrappedSketchLayer,
+ platformBridge: PlatformBridge = getDefaultPlatformBridge(),
+) {
+ return _render(platformBridge)(element, container);
+}
+
+export function renderToJSON(
+ element: React.ReactElement,
+ platformBridge: PlatformBridge = getDefaultPlatformBridge(),
+) {
+ return _renderToJSON(platformBridge)(element);
+}
+
+export function makeSymbol(
+ Component: React.ComponentType,
+ symbolProps: string | SymbolMasterProps,
+ document: SketchDocumentData | SketchDocument | WrappedSketchDocument | undefined,
+ bridge: PlatformBridge = getDefaultPlatformBridge(),
+) {
+ return _makeSymbol(bridge)(Component, symbolProps, document);
+}
+
+export const TextStyles = _TextStyles(() => getDefaultPlatformBridge());
+
+export * from './index.common';
diff --git a/src/jsonUtils/borders.ts b/src/jsonUtils/borders.ts
index b32bfdab..bacbacce 100644
--- a/src/jsonUtils/borders.ts
+++ b/src/jsonUtils/borders.ts
@@ -1,7 +1,7 @@
import { FileFormat1 as FileFormat } from '@sketch-hq/sketch-file-format-ts';
import { makeColorFromCSS, emptyGradient } from './models';
import { ViewStyle, LayoutInfo, BorderStyle, Color } from '../types';
-import same from '../utils/same';
+import { same } from '../utils/same';
import { makeVerticalBorder, makeHorizontalBorder } from './shapeLayers';
import { makeBorderOptions } from './style';
diff --git a/src/jsonUtils/computeTextTree.ts b/src/jsonUtils/computeTextTree.ts
index 14ecc718..f236117e 100644
--- a/src/jsonUtils/computeTextTree.ts
+++ b/src/jsonUtils/computeTextTree.ts
@@ -1,6 +1,6 @@
import { ReactTestRendererNode } from 'react-test-renderer';
import { TextNode } from '../types';
-import Context from '../utils/Context';
+import { Context } from '../utils/Context';
import { VALID_TEXT_CHILDREN_TYPES } from '../utils/constants';
const walkTextTree = (textTree: ReactTestRendererNode, context: Context, textNodes: TextNode[]) => {
@@ -27,7 +27,7 @@ const walkTextTree = (textTree: ReactTestRendererNode, context: Context, textNod
}
};
-const computeTextTree = (
+export const computeTextTree = (
node: ReactTestRendererNode,
context: Context,
textNodes: TextNode[] = [],
@@ -60,5 +60,3 @@ const computeTextTree = (
return textNodes;
};
-
-export default computeTextTree;
diff --git a/src/jsonUtils/computeYogaNode.ts b/src/jsonUtils/computeYogaNode.ts
index cc93c16a..84ad17ac 100644
--- a/src/jsonUtils/computeYogaNode.ts
+++ b/src/jsonUtils/computeYogaNode.ts
@@ -1,13 +1,13 @@
import yoga from 'yoga-layout-prebuilt';
import { ReactTestRendererNode } from 'react-test-renderer';
-import { ViewStyle } from '../types';
-import Context from '../utils/Context';
-import createStringMeasurer from '../utils/createStringMeasurer';
-import hasAnyDefined from '../utils/hasAnyDefined';
-import pick from '../utils/pick';
-import computeTextTree from './computeTextTree';
+import { ViewStyle, PlatformBridge } from '../types';
+import { Context } from '../utils/Context';
+import { createStringMeasurer } from '../utils/createStringMeasurer';
+import { hasAnyDefined } from '../utils/hasAnyDefined';
+import { pick } from '../utils/pick';
+import { computeTextTree } from './computeTextTree';
import { INHERITABLE_FONT_STYLES } from '../utils/constants';
-import isDefined from '../utils/isDefined';
+import { isDefined } from '../utils/isDefined';
import { getSymbolMasterById } from '../symbol';
// flatten all styles (including nested) into one object
@@ -21,14 +21,14 @@ export const getStyles = (node: ReactTestRendererNode): ViewStyle => {
if (Array.isArray(style)) {
const flattened = Array.prototype.concat.apply([], style);
const themeFlattened = Array.prototype.concat.apply([], flattened);
- const objectsOnly = themeFlattened.filter(f => f);
+ const objectsOnly = themeFlattened.filter((f) => f);
style = Object.assign({}, ...objectsOnly);
}
return style;
};
-const computeYogaNode = (
+export const computeYogaNode = (bridge: PlatformBridge) => (
node: ReactTestRendererNode,
context: Context,
): { node: yoga.YogaNode; stop?: boolean } => {
@@ -346,12 +346,10 @@ const computeYogaNode = (
// Handle Text Children
const textNodes = computeTextTree(node, context);
- yogaNode.setMeasureFunc(createStringMeasurer(textNodes));
+ yogaNode.setMeasureFunc(createStringMeasurer(bridge)(textNodes));
return { node: yogaNode, stop: true };
}
return { node: yogaNode };
};
-
-export default computeYogaNode;
diff --git a/src/jsonUtils/computeYogaTree.ts b/src/jsonUtils/computeYogaTree.ts
index 33321623..561ed522 100644
--- a/src/jsonUtils/computeYogaTree.ts
+++ b/src/jsonUtils/computeYogaTree.ts
@@ -1,11 +1,12 @@
import yoga from 'yoga-layout-prebuilt';
import { ReactTestRendererNode } from 'react-test-renderer';
-import computeYogaNode from './computeYogaNode';
-import Context from '../utils/Context';
-import zIndex from '../utils/zIndex';
+import { PlatformBridge } from '../types';
+import { computeYogaNode } from './computeYogaNode';
+import { Context } from '../utils/Context';
+import { zIndex } from '../utils/zIndex';
-const walkTree = (tree: ReactTestRendererNode, context: Context) => {
- const { node, stop } = computeYogaNode(tree, context);
+const walkTree = (bridge: PlatformBridge) => (tree: ReactTestRendererNode, context: Context) => {
+ const { node, stop } = computeYogaNode(bridge)(tree, context);
if (typeof tree === 'string' || tree.type === 'sketch_svg') {
// handle svg node, eg: stop here, we will handle the children in the renderer
@@ -20,7 +21,7 @@ const walkTree = (tree: ReactTestRendererNode, context: Context) => {
const childComponent = children[index];
// Avoid going into node's children
if (!stop) {
- const childNode = walkTree(childComponent, context.forChildren());
+ const childNode = walkTree(bridge)(childComponent, context.forChildren());
node.insertChild(childNode, index);
}
}
@@ -28,7 +29,8 @@ const walkTree = (tree: ReactTestRendererNode, context: Context) => {
return node;
};
-const treeToNodes = (root: ReactTestRendererNode, context: Context): yoga.YogaNode =>
- walkTree(root, context);
-export default treeToNodes;
+export const computeYogaTree = (bridge: PlatformBridge) => (
+ root: ReactTestRendererNode,
+ context: Context,
+): yoga.YogaNode => walkTree(bridge)(root, context);
diff --git a/src/jsonUtils/hotspotLayer.ts b/src/jsonUtils/hotspotLayer.ts
index a0b1eb67..e5a23259 100644
--- a/src/jsonUtils/hotspotLayer.ts
+++ b/src/jsonUtils/hotspotLayer.ts
@@ -19,7 +19,7 @@ const getArtboard = (target: string) => {
return generateID(`artboard:${target}`, true);
};
-const hotspotLayer = ({
+export const hotspotLayer = ({
targetId,
target,
animationType,
@@ -34,5 +34,3 @@ const hotspotLayer = ({
destinationArtboardID: target ? getArtboard(target) : targetId || 'broken',
},
});
-
-export default hotspotLayer;
diff --git a/src/jsonUtils/layerGroup.ts b/src/jsonUtils/layerGroup.ts
index 1523148d..4f61c2e4 100644
--- a/src/jsonUtils/layerGroup.ts
+++ b/src/jsonUtils/layerGroup.ts
@@ -1,10 +1,10 @@
import { FileFormat1 as FileFormat } from '@sketch-hq/sketch-file-format-ts';
-import makeResizeConstraint from './resizeConstraint';
+import { makeResizeConstraint } from './resizeConstraint';
import { generateID, makeRect } from './models';
import { ResizeConstraints } from '../types';
import { makeStyle } from './style';
-const layerGroup = (
+export const layerGroup = (
x: number,
y: number,
width: number,
@@ -39,5 +39,3 @@ const layerGroup = (
booleanOperation: FileFormat.BooleanOperation.NA,
isFixedToViewport: false,
});
-
-export default layerGroup;
diff --git a/src/jsonUtils/nodeImpl/graphics/curvePoint.ts b/src/jsonUtils/makeSvgLayer/graphics/curvePoint.ts
similarity index 100%
rename from src/jsonUtils/nodeImpl/graphics/curvePoint.ts
rename to src/jsonUtils/makeSvgLayer/graphics/curvePoint.ts
diff --git a/src/jsonUtils/nodeImpl/graphics/path.ts b/src/jsonUtils/makeSvgLayer/graphics/path.ts
similarity index 100%
rename from src/jsonUtils/nodeImpl/graphics/path.ts
rename to src/jsonUtils/makeSvgLayer/graphics/path.ts
diff --git a/src/jsonUtils/nodeImpl/graphics/point.ts b/src/jsonUtils/makeSvgLayer/graphics/point.ts
similarity index 100%
rename from src/jsonUtils/nodeImpl/graphics/point.ts
rename to src/jsonUtils/makeSvgLayer/graphics/point.ts
diff --git a/src/jsonUtils/nodeImpl/graphics/rect.ts b/src/jsonUtils/makeSvgLayer/graphics/rect.ts
similarity index 92%
rename from src/jsonUtils/nodeImpl/graphics/rect.ts
rename to src/jsonUtils/makeSvgLayer/graphics/rect.ts
index 75236ccf..62a765e0 100644
--- a/src/jsonUtils/nodeImpl/graphics/rect.ts
+++ b/src/jsonUtils/makeSvgLayer/graphics/rect.ts
@@ -3,10 +3,10 @@ import { makeRect } from '../../models';
import { Point, Size } from './types';
export function makeBoundingRectFromPoints(points: Point[]): FileFormat.Rect {
- const x = Math.min(...points.map(point => point.x));
- const y = Math.min(...points.map(point => point.y));
- const width = Math.max(...points.map(point => point.x)) - x;
- const height = Math.max(...points.map(point => point.y)) - y;
+ const x = Math.min(...points.map((point) => point.x));
+ const y = Math.min(...points.map((point) => point.y));
+ const width = Math.max(...points.map((point) => point.x)) - x;
+ const height = Math.max(...points.map((point) => point.y)) - y;
return makeRect(x, y, width, height);
}
diff --git a/src/jsonUtils/nodeImpl/graphics/types.ts b/src/jsonUtils/makeSvgLayer/graphics/types.ts
similarity index 100%
rename from src/jsonUtils/nodeImpl/graphics/types.ts
rename to src/jsonUtils/makeSvgLayer/graphics/types.ts
diff --git a/src/jsonUtils/sketchImpl/makeSvgLayer.ts b/src/jsonUtils/makeSvgLayer/index.sketch.ts
similarity index 82%
rename from src/jsonUtils/sketchImpl/makeSvgLayer.ts
rename to src/jsonUtils/makeSvgLayer/index.sketch.ts
index 91fa3f4a..2ee6a4cd 100644
--- a/src/jsonUtils/sketchImpl/makeSvgLayer.ts
+++ b/src/jsonUtils/makeSvgLayer/index.sketch.ts
@@ -1,13 +1,9 @@
import { FileFormat1 as FileFormat } from '@sketch-hq/sketch-file-format-ts';
-import { toSJSON } from './sketch-to-json';
+import { toSJSON } from '../sketchJson/toSJSON';
import { LayoutInfo } from '../../types';
-export default function makeSvgLayer(
- _layout: LayoutInfo,
- name: string,
- svg: string,
-): FileFormat.Group {
+export function makeSvgLayer(_layout: LayoutInfo, name: string, svg: string): FileFormat.Group {
const svgString = NSString.stringWithString(svg);
const svgData = svgString.dataUsingEncoding(NSUTF8StringEncoding);
const svgImporter = MSSVGImporter.svgImporter();
diff --git a/src/jsonUtils/nodeImpl/makeSvgLayer.ts b/src/jsonUtils/makeSvgLayer/index.ts
similarity index 85%
rename from src/jsonUtils/nodeImpl/makeSvgLayer.ts
rename to src/jsonUtils/makeSvgLayer/index.ts
index d719bc45..8cf96198 100644
--- a/src/jsonUtils/nodeImpl/makeSvgLayer.ts
+++ b/src/jsonUtils/makeSvgLayer/index.ts
@@ -1,12 +1,12 @@
import { FileFormat1 as FileFormat } from '@sketch-hq/sketch-file-format-ts';
+import svgModel from '@lona/svg-model';
import { LayoutInfo, ViewStyle } from '../../types';
import { makeShapeGroup, makeShapePath } from '../shapeLayers';
import { makeRect } from '../models';
import { createUniformBorder } from '../borders';
-import layerGroup from '../layerGroup';
+import { layerGroup } from '../layerGroup';
import { makePathsFromCommands, makeLineCapStyle } from './graphics/path';
import { unionRects, scaleRect, makeBoundingRectFromCommands, resize } from './graphics/rect';
-import requireSvgModel from './requireSvgModel';
function makeLayerFromPathElement(pathElement: any, _parentFrame: FileFormat.Rect, scale: number) {
const {
@@ -26,7 +26,7 @@ function makeLayerFromPathElement(pathElement: any, _parentFrame: FileFormat.Rec
// and we don't want to apply the origin translation twice.
const shapePathFrame = makeRect(0, 0, shapeGroupFrame.width, shapeGroupFrame.height);
- const shapePaths = paths.map(path => makeShapePath(shapePathFrame, path));
+ const shapePaths = paths.map((path) => makeShapePath(shapePathFrame, path));
const viewStyle: ViewStyle = {};
@@ -78,9 +78,7 @@ function makeLayerGroup(
return group;
}
-export default function makeSvgLayer(layout: LayoutInfo, name: string, svg: string) {
- const svgModel = requireSvgModel();
-
+export function makeSvgLayer(layout: LayoutInfo, name: string, svg: string) {
const {
data: { params, children },
} = svgModel(svg);
@@ -92,14 +90,10 @@ export default function makeSvgLayer(layout: LayoutInfo, name: string, svg: stri
width: layout.width,
height: layout.height,
},
- preserveAspectRatio = 'xMidYMid meet',
} = params;
- const meetOrSlice = preserveAspectRatio.split(' ')[1] || 'meet';
- const resizeMode = meetOrSlice === 'meet' ? 'contain' : 'cover';
-
// Determine the rect to generate layers within
- const croppedRect = resize(viewBox, layout, resizeMode);
+ const croppedRect = resize(viewBox, layout, 'contain');
const scale = croppedRect.width / viewBox.width;
// The top-level frame is the union of every path within
diff --git a/src/jsonUtils/models.ts b/src/jsonUtils/models.ts
index 1b11e5c6..51d53e4f 100644
--- a/src/jsonUtils/models.ts
+++ b/src/jsonUtils/models.ts
@@ -2,7 +2,7 @@ import { FileFormat1 as FileFormat } from '@sketch-hq/sketch-file-format-ts';
import seedrandom from 'seedrandom';
import normalizeColor, { rgba } from 'normalize-css-color';
import { Color, ResizeConstraints } from '../types';
-import makeResizeConstraint from './resizeConstraint';
+import { makeResizeConstraint } from './resizeConstraint';
const lut: string[] = [];
for (let i = 0; i < 256; i += 1) {
@@ -15,16 +15,13 @@ function e7(seed?: string) {
const d1 = (random() * 0xffffffff) | 0;
const d2 = (random() * 0xffffffff) | 0;
const d3 = (random() * 0xffffffff) | 0;
- return `${lut[d0 & 0xff] +
- lut[(d0 >> 8) & 0xff] +
- lut[(d0 >> 16) & 0xff] +
- lut[(d0 >> 24) & 0xff]}-${lut[d1 & 0xff]}${lut[(d1 >> 8) & 0xff]}-${
- lut[((d1 >> 16) & 0x0f) | 0x40]
- }${lut[(d1 >> 24) & 0xff]}-${lut[(d2 & 0x3f) | 0x80]}${lut[(d2 >> 8) & 0xff]}-${
- lut[(d2 >> 16) & 0xff]
- }${lut[(d2 >> 24) & 0xff]}${lut[d3 & 0xff]}${lut[(d3 >> 8) & 0xff]}${lut[(d3 >> 16) & 0xff]}${
- lut[(d3 >> 24) & 0xff]
- }`;
+ return `${
+ lut[d0 & 0xff] + lut[(d0 >> 8) & 0xff] + lut[(d0 >> 16) & 0xff] + lut[(d0 >> 24) & 0xff]
+ }-${lut[d1 & 0xff]}${lut[(d1 >> 8) & 0xff]}-${lut[((d1 >> 16) & 0x0f) | 0x40]}${
+ lut[(d1 >> 24) & 0xff]
+ }-${lut[(d2 & 0x3f) | 0x80]}${lut[(d2 >> 8) & 0xff]}-${lut[(d2 >> 16) & 0xff]}${
+ lut[(d2 >> 24) & 0xff]
+ }${lut[d3 & 0xff]}${lut[(d3 >> 8) & 0xff]}${lut[(d3 >> 16) & 0xff]}${lut[(d3 >> 24) & 0xff]}`;
}
// Keep track on previous numbers that are generated
diff --git a/src/jsonUtils/nodeImpl/createStringMeasurer.ts b/src/jsonUtils/nodeImpl/createStringMeasurer.ts
deleted file mode 100644
index 9b8037a0..00000000
--- a/src/jsonUtils/nodeImpl/createStringMeasurer.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-import requireObjCBridge from './requireObjCBridge';
-
-import { TextNode, Size } from '../../types';
-
-export default function createStringMeasurer(textNodes: TextNode[], width: number): Size {
- return requireObjCBridge().createStringMeasurer(textNodes, width);
-}
diff --git a/src/jsonUtils/nodeImpl/findFontName.ts b/src/jsonUtils/nodeImpl/findFontName.ts
deleted file mode 100644
index f68952b5..00000000
--- a/src/jsonUtils/nodeImpl/findFontName.ts
+++ /dev/null
@@ -1,6 +0,0 @@
-import requireObjCBridge from './requireObjCBridge';
-import { TextStyle } from '../../types';
-
-export default function findFontName(style: TextStyle): string {
- return requireObjCBridge().findFontName(style);
-}
diff --git a/src/jsonUtils/nodeImpl/makeImageDataFromUrl.ts b/src/jsonUtils/nodeImpl/makeImageDataFromUrl.ts
deleted file mode 100644
index 7cfeb6ea..00000000
--- a/src/jsonUtils/nodeImpl/makeImageDataFromUrl.ts
+++ /dev/null
@@ -1,5 +0,0 @@
-import requireObjCBridge from './requireObjCBridge';
-
-export default function makeImageDataFromUrl(url?: string): string {
- return requireObjCBridge().makeImageDataFromUrl(url);
-}
diff --git a/src/jsonUtils/nodeImpl/requireObjCBridge.ts b/src/jsonUtils/nodeImpl/requireObjCBridge.ts
deleted file mode 100644
index afe41f81..00000000
--- a/src/jsonUtils/nodeImpl/requireObjCBridge.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-// This is the ugliest but it's kind of the only way to avoid bundling
-// this module when using skpm (the other solution would be to add an `ignore` option
-// in every client webpack config...)
-let cached$: any; // cache nodobjc instance
-export default function requireObjCBridge() {
- if (cached$) {
- return cached$;
- }
- cached$ = eval("require('node-sketch-bridge')");
- return cached$;
-}
diff --git a/src/jsonUtils/nodeImpl/requireSvgModel.ts b/src/jsonUtils/nodeImpl/requireSvgModel.ts
deleted file mode 100644
index 03099fa5..00000000
--- a/src/jsonUtils/nodeImpl/requireSvgModel.ts
+++ /dev/null
@@ -1,4 +0,0 @@
-// Hack to avoid bundling the node implementation/dependencies unless needed
-export default function requireSvgModel() {
- return eval("require('@lona/svg-model')");
-}
diff --git a/src/jsonUtils/resizeConstraint.ts b/src/jsonUtils/resizeConstraint.ts
index dad18fb5..ce3c2e92 100644
--- a/src/jsonUtils/resizeConstraint.ts
+++ b/src/jsonUtils/resizeConstraint.ts
@@ -64,9 +64,7 @@ const RESIZE_CONSTRAINTS: { [key: string]: number } = {
none: 63,
};
-export default function makeResizeConstraint(
- resizingConstraint?: ResizeConstraints | null,
-): number {
+export function makeResizeConstraint(resizingConstraint?: ResizeConstraints | null): number {
if (resizingConstraint) {
const constraints = [];
const { top, right, bottom, left, fixedHeight, fixedWidth } = resizingConstraint;
diff --git a/src/jsonUtils/shapeLayers.ts b/src/jsonUtils/shapeLayers.ts
index 4a0358c6..4745113b 100644
--- a/src/jsonUtils/shapeLayers.ts
+++ b/src/jsonUtils/shapeLayers.ts
@@ -1,5 +1,5 @@
import { FileFormat1 as FileFormat } from '@sketch-hq/sketch-file-format-ts';
-import makeResizeConstraint from './resizeConstraint';
+import { makeResizeConstraint } from './resizeConstraint';
import { generateID, makeRect, makeColorFromCSS, emptyGradient } from './models';
import { makeStyle } from './style';
import { Color, ResizeConstraints, ViewStyle } from '../types';
diff --git a/src/jsonUtils/sketchImpl/json-to-sketch.ts b/src/jsonUtils/sketchJson/fromSJSON.ts
similarity index 100%
rename from src/jsonUtils/sketchImpl/json-to-sketch.ts
rename to src/jsonUtils/sketchJson/fromSJSON.ts
diff --git a/src/jsonUtils/sketchImpl/sketch-to-json.ts b/src/jsonUtils/sketchJson/toSJSON.ts
similarity index 100%
rename from src/jsonUtils/sketchImpl/sketch-to-json.ts
rename to src/jsonUtils/sketchJson/toSJSON.ts
diff --git a/src/jsonUtils/style.ts b/src/jsonUtils/style.ts
index 27aa93a6..04dec60f 100644
--- a/src/jsonUtils/style.ts
+++ b/src/jsonUtils/style.ts
@@ -1,7 +1,7 @@
import { FileFormat1 as FileFormat } from '@sketch-hq/sketch-file-format-ts';
import { makeColorFromCSS, makeColorFill } from './models';
import { ViewStyle, TextStyle, BorderStyle } from '../types';
-import hasAnyDefined from '../utils/hasAnyDefined';
+import { hasAnyDefined } from '../utils/hasAnyDefined';
import { DEFAULT_BORDER_STYLE } from './borders';
const DEFAULT_SHADOW_COLOR = '#000';
@@ -169,7 +169,7 @@ export const makeStyle = (
}
if (shadowsProp) {
- shadowsProp.forEach(shadowStyle => {
+ shadowsProp.forEach((shadowStyle) => {
if (!shadowStyle) {
return;
}
diff --git a/src/jsonUtils/svgLayer.ts b/src/jsonUtils/svgLayer.ts
deleted file mode 100644
index 489dc567..00000000
--- a/src/jsonUtils/svgLayer.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-import { FileFormat1 as FileFormat } from '@sketch-hq/sketch-file-format-ts';
-import { LayoutInfo } from '../types';
-import { getSketchVersion } from '../utils/getSketchVersion';
-import sketchMethod from './sketchImpl/makeSvgLayer';
-import nodeMethod from './nodeImpl/makeSvgLayer';
-
-const makeSvgLayer = (layout: LayoutInfo, name: string, svg: string): FileFormat.Group => {
- if (getSketchVersion() === 'NodeJS') {
- return nodeMethod(layout, name, svg);
- }
- return sketchMethod(layout, name, svg);
-};
-
-export default makeSvgLayer;
diff --git a/src/jsonUtils/textLayers.ts b/src/jsonUtils/textLayers.ts
index 3cd8c32f..457b91ac 100644
--- a/src/jsonUtils/textLayers.ts
+++ b/src/jsonUtils/textLayers.ts
@@ -1,11 +1,9 @@
import { FileFormat1 as FileFormat } from '@sketch-hq/sketch-file-format-ts';
-import makeResizeConstraint from './resizeConstraint';
-import { TextNode, ResizeConstraints, TextStyle, ViewStyle } from '../types';
+import { makeResizeConstraint } from './resizeConstraint';
+import { TextNode, ResizeConstraints, TextStyle, ViewStyle, PlatformBridge } from '../types';
import { generateID, makeColorFromCSS } from './models';
import { makeStyle, parseStyle } from './style';
-import findFontName from '../utils/findFont';
-
export const TEXT_DECORATION_UNDERLINE: { [key: string]: number } = {
none: FileFormat.UnderlineStyle.None,
underline: FileFormat.UnderlineStyle.Underlined,
@@ -54,15 +52,17 @@ export const FONT_STYLES: { [key: string]: boolean } = {
oblique: true,
};
-const makeFontDescriptor = (style: TextStyle): FileFormat.FontDescriptor => ({
+const makeFontDescriptor = (bridge: PlatformBridge) => (
+ style: TextStyle,
+): FileFormat.FontDescriptor => ({
_class: 'fontDescriptor',
attributes: {
- name: String(findFontName(style)), // will default to the system font
+ name: bridge.findFontName(String(style)), // will default to the system font
size: style.fontSize || 14,
},
});
-const makeTextStyleAttributes = (style: TextStyle) =>
+const makeTextStyleAttributes = (bridge: PlatformBridge) => (style: TextStyle) =>
({
underlineStyle: style.textDecoration ? TEXT_DECORATION_UNDERLINE[style.textDecoration] || 0 : 0,
strikethroughStyle: style.textDecoration
@@ -90,19 +90,24 @@ const makeTextStyleAttributes = (style: TextStyle) =>
MSAttributedStringTextTransformAttribute: TEXT_TRANSFORM[style.textTransform] * 1,
}
: {}),
- MSAttributedStringFontAttribute: makeFontDescriptor(style),
+ MSAttributedStringFontAttribute: makeFontDescriptor(bridge)(style),
textStyleVerticalAlignmentKey: 0,
MSAttributedStringColorAttribute: makeColorFromCSS(style.color || 'black'),
} as const);
-const makeAttribute = (node: TextNode, location: number): FileFormat.StringAttribute => ({
+const makeAttribute = (bridge: PlatformBridge) => (
+ node: TextNode,
+ location: number,
+): FileFormat.StringAttribute => ({
_class: 'stringAttribute',
location,
length: node.content.length,
- attributes: makeTextStyleAttributes(node.textStyles),
+ attributes: makeTextStyleAttributes(bridge)(node.textStyles),
});
-const makeAttributedString = (textNodes: TextNode[]): FileFormat.AttributedString => {
+const makeAttributedString = (bridge: PlatformBridge) => (
+ textNodes: TextNode[],
+): FileFormat.AttributedString => {
const json: FileFormat.AttributedString = {
_class: 'attributedString',
string: '',
@@ -111,8 +116,8 @@ const makeAttributedString = (textNodes: TextNode[]): FileFormat.AttributedStrin
let location = 0;
- textNodes.forEach(node => {
- json.attributes.push(makeAttribute(node, location));
+ textNodes.forEach((node) => {
+ json.attributes.push(makeAttribute(bridge)(node, location));
json.string += node.content;
location += node.content.length;
});
@@ -120,14 +125,14 @@ const makeAttributedString = (textNodes: TextNode[]): FileFormat.AttributedStrin
return json;
};
-export const makeTextStyle = (
+export const makeTextStyle = (bridge: PlatformBridge) => (
style: TextStyle,
shadows?: (ViewStyle | undefined | null)[] | null,
): FileFormat.Style => {
const json = makeStyle(style, undefined, shadows);
json.textStyle = {
_class: 'textStyle',
- encodedAttributes: makeTextStyleAttributes(style),
+ encodedAttributes: makeTextStyleAttributes(bridge)(style),
verticalAlignment: FileFormat.TextVerticalAlignment.Top,
};
return json;
@@ -196,7 +201,7 @@ export const parseTextStyle = (json: FileFormat.Style): TextStyle => {
return style;
};
-const makeTextLayer = (
+export const makeTextLayer = (bridge: PlatformBridge) => (
frame: FileFormat.Rect,
name: string,
textNodes: TextNode[],
@@ -205,7 +210,7 @@ const makeTextLayer = (
shadows?: (ViewStyle | undefined | null)[] | null,
): FileFormat.Text => ({
_class: 'text',
- do_objectID: generateID(`text:${name}-${textNodes.map(node => node.content).join('')}`),
+ do_objectID: generateID(`text:${name}-${textNodes.map((node) => node.content).join('')}`),
frame,
isFlippedHorizontal: false,
isFlippedVertical: false,
@@ -218,8 +223,8 @@ const makeTextLayer = (
resizingType: FileFormat.ResizeType.Stretch,
rotation: 0,
shouldBreakMaskChain: false,
- attributedString: makeAttributedString(textNodes),
- style: makeTextStyle((textNodes[0] || { textStyles: {} }).textStyles, shadows),
+ attributedString: makeAttributedString(bridge)(textNodes),
+ style: makeTextStyle(bridge)((textNodes[0] || { textStyles: {} }).textStyles, shadows),
automaticallyDrawOnUnderlyingPath: false,
dontSynchroniseWithSymbol: false,
// NOTE(akp): I haven't fully figured out the meaning of glyphBounds
@@ -237,5 +242,3 @@ const makeTextLayer = (
},
isFixedToViewport: false,
});
-
-export default makeTextLayer;
diff --git a/src/platformBridges/macos.ts b/src/platformBridges/macos.ts
new file mode 100644
index 00000000..6cdb85e2
--- /dev/null
+++ b/src/platformBridges/macos.ts
@@ -0,0 +1,11 @@
+import { PlatformBridge } from '../types';
+
+import { createStringMeasurer, findFontName, makeImageDataFromUrl } from 'node-sketch-bridge';
+
+const NodeMacOSBridge: PlatformBridge = {
+ createStringMeasurer,
+ findFontName,
+ makeImageDataFromUrl,
+};
+
+export default NodeMacOSBridge;
diff --git a/src/jsonUtils/sketchImpl/createStringMeasurer.ts b/src/platformBridges/sketch/createStringMeasurer.ts
similarity index 92%
rename from src/jsonUtils/sketchImpl/createStringMeasurer.ts
rename to src/platformBridges/sketch/createStringMeasurer.ts
index d91e1376..cc7519e1 100644
--- a/src/jsonUtils/sketchImpl/createStringMeasurer.ts
+++ b/src/platformBridges/sketch/createStringMeasurer.ts
@@ -4,9 +4,9 @@ import {
TEXT_DECORATION_LINETHROUGH,
TEXT_ALIGN,
TEXT_TRANSFORM,
-} from '../textLayers';
+} from '../../jsonUtils/textLayers';
+import { makeColorFromCSS } from '../../jsonUtils/models';
import { findFont } from './findFontName';
-import { makeColorFromCSS } from '../models';
// TODO(lmr): do something more sensible here
const FLOAT_MAX = 999999;
@@ -71,9 +71,9 @@ function createAttributedString(textNode: TextNode): NSAttributedString {
return NSAttributedString.attributedStringWithString_attributes_(content, attribs);
}
-export default function createStringMeasurer(textNodes: TextNode[], width: number): Size {
+export function createStringMeasurer(textNodes: TextNode[], width: number): Size {
const fullStr = NSMutableAttributedString.alloc().init();
- textNodes.forEach(textNode => {
+ textNodes.forEach((textNode) => {
const newString = createAttributedString(textNode);
fullStr.appendAttributedString(newString);
});
diff --git a/src/jsonUtils/sketchImpl/findFontName.ts b/src/platformBridges/sketch/findFontName.ts
similarity index 95%
rename from src/jsonUtils/sketchImpl/findFontName.ts
rename to src/platformBridges/sketch/findFontName.ts
index 5b89110c..5709c607 100644
--- a/src/jsonUtils/sketchImpl/findFontName.ts
+++ b/src/platformBridges/sketch/findFontName.ts
@@ -1,6 +1,6 @@
-import hashStyle from '../../utils/hashStyle';
+import { hashStyle } from '../../utils/hashStyle';
import { TextStyle } from '../../types';
-import { FONT_STYLES } from '../textLayers';
+import { FONT_STYLES } from '../../jsonUtils/textLayers';
// this borrows heavily from react-native's RCTFont class
// thanks y'all
@@ -53,7 +53,7 @@ const weightOfFont = (font: NSFont): number => {
if (weight === 0.0) {
const weights = Object.keys(FONT_WEIGHTS);
const fontName = String(font.fontName()).toLowerCase();
- const matchingWeight = weights.find(w => fontName.endsWith(w));
+ const matchingWeight = weights.find((w) => fontName.endsWith(w));
if (matchingWeight) {
return FONT_WEIGHTS[matchingWeight];
}
@@ -190,7 +190,7 @@ export const findFont = (style: TextStyle): NSFont => {
return font;
};
-export default function findFontName(style: TextStyle): string {
+export function findFontName(style: TextStyle): string {
const font = findFont(style);
return font.fontDescriptor().postscriptName();
}
diff --git a/src/platformBridges/sketch/index.ts b/src/platformBridges/sketch/index.ts
new file mode 100644
index 00000000..54135f13
--- /dev/null
+++ b/src/platformBridges/sketch/index.ts
@@ -0,0 +1,12 @@
+import { PlatformBridge } from '../../types';
+import { createStringMeasurer } from './createStringMeasurer';
+import { findFontName } from './findFontName';
+import { makeImageDataFromUrl } from './makeImageDataFromUrl';
+
+const SketchBridge: PlatformBridge = {
+ createStringMeasurer,
+ findFontName,
+ makeImageDataFromUrl,
+};
+
+export default SketchBridge;
diff --git a/src/jsonUtils/sketchImpl/makeImageDataFromUrl.ts b/src/platformBridges/sketch/makeImageDataFromUrl.ts
similarity index 95%
rename from src/jsonUtils/sketchImpl/makeImageDataFromUrl.ts
rename to src/platformBridges/sketch/makeImageDataFromUrl.ts
index fb360f38..440bdeef 100644
--- a/src/jsonUtils/sketchImpl/makeImageDataFromUrl.ts
+++ b/src/platformBridges/sketch/makeImageDataFromUrl.ts
@@ -1,4 +1,4 @@
-export default function makeImageDataFromUrl(url?: string) {
+export function makeImageDataFromUrl(url?: string) {
let fetchedData = url ? NSData.dataWithContentsOfURL(NSURL.URLWithString(url)) : undefined;
if (fetchedData) {
diff --git a/src/render.tsx b/src/render.tsx
index c190f4d3..051272bb 100644
--- a/src/render.tsx
+++ b/src/render.tsx
@@ -1,26 +1,26 @@
import * as React from 'react';
-import { fromSJSON } from './jsonUtils/sketchImpl/json-to-sketch';
-import { FileFormat1 as FileFormat } from '@sketch-hq/sketch-file-format-ts';
-import buildTree from './buildTree';
-import flexToSketchJSON from './flexToSketchJSON';
+import { fromSJSON } from './jsonUtils/sketchJson/fromSJSON';
+import { buildTree } from './buildTree';
+import { flexToSketchJSON } from './flexToSketchJSON';
import { resetLayer, resetDocument } from './resets';
import { injectSymbols } from './symbol';
-import { SketchDocumentData, SketchLayer, SketchPage, TreeNode, WrappedSketchLayer } from './types';
-import RedBox from './components/RedBox';
+import {
+ SketchDocumentData,
+ SketchLayer,
+ SketchPage,
+ TreeNode,
+ WrappedSketchLayer,
+ PlatformBridge,
+} from './types';
+import { RedBox } from './components/RedBox';
import {
getDocumentDataFromContainer,
getDocumentDataFromContext,
getDocumentData,
} from './utils/getDocument';
-import isNativeDocument from './utils/isNativeDocument';
-import isNativePage from './utils/isNativePage';
-import isNativeSymbolsPage from './utils/isNativeSymbolsPage';
-import { getSketchVersion } from './utils/getSketchVersion';
-
-export const renderToJSON = (element: React.ReactElement): FileFormat.AnyLayer => {
- const tree = buildTree(element);
- return flexToSketchJSON(tree);
-};
+import { isNativeDocument } from './utils/isNativeDocument';
+import { isNativePage } from './utils/isNativePage';
+import { isNativeSymbolsPage } from './utils/isNativeSymbolsPage';
export const renderLayers = (layers: Array, container: SketchLayer): SketchLayer => {
if (container.addLayers === undefined) {
@@ -40,14 +40,20 @@ const getDefaultPage = (): SketchLayer => {
return isNativeSymbolsPage(currentPage) ? doc.addBlankPage() : currentPage;
};
-const renderContents = (tree: TreeNode | string, container: SketchLayer): SketchLayer => {
- const json = flexToSketchJSON(tree);
+const renderContents = (bridge: PlatformBridge) => (
+ tree: TreeNode | string,
+ container: SketchLayer,
+): SketchLayer => {
+ const json = flexToSketchJSON(bridge)(tree);
const layer = fromSJSON(json, '119');
return renderLayers([layer], container);
};
-const renderPage = (tree: TreeNode, page: SketchPage): Array => {
+const renderPage = (bridge: PlatformBridge) => (
+ tree: TreeNode,
+ page: SketchPage,
+): Array => {
const children = tree.children || [];
// assume if name is set on this nested page, the intent is to overwrite
@@ -56,10 +62,13 @@ const renderPage = (tree: TreeNode, page: SketchPage): Array => {
page.setName(tree.props.name);
}
- return children.map(child => renderContents(child, page));
+ return children.map((child) => renderContents(bridge)(child, page));
};
-const renderDocument = (tree: TreeNode, documentData: SketchDocumentData): Array => {
+const renderDocument = (bridge: PlatformBridge) => (
+ tree: TreeNode,
+ documentData: SketchDocumentData,
+): Array => {
const initialPage = documentData.currentPage();
const shouldRenderInitialPage = !isNativeSymbolsPage(initialPage);
const children = tree.children || [];
@@ -70,11 +79,14 @@ const renderDocument = (tree: TreeNode, documentData: SketchDocumentData): Array
}
const page = i === 0 && shouldRenderInitialPage ? initialPage : documentData.addBlankPage();
- return renderPage(child, page);
+ return renderPage(bridge)(child, page);
});
};
-const renderTree = (tree: TreeNode, _container?: SketchLayer): SketchLayer | Array => {
+const renderTree = (bridge: PlatformBridge) => (
+ tree: TreeNode,
+ _container?: SketchLayer,
+): SketchLayer | Array => {
if (tree.type === 'sketch_document') {
if (_container && !isNativeDocument(_container)) {
throw new Error('Cannot render a Document into a child of Document');
@@ -87,7 +99,7 @@ const renderTree = (tree: TreeNode, _container?: SketchLayer): SketchLayer | Arr
}
resetDocument(doc);
- return renderDocument(tree, doc);
+ return renderDocument(bridge)(tree, doc);
}
if (isNativeDocument(_container)) {
@@ -104,18 +116,14 @@ const renderTree = (tree: TreeNode, _container?: SketchLayer): SketchLayer | Arr
resetLayer(container);
return tree.type === 'sketch_page'
- ? renderPage(tree, container)
- : renderContents(tree, container);
+ ? renderPage(bridge)(tree, container)
+ : renderContents(bridge)(tree, container);
};
-export const render = (
+export const render = (bridge: PlatformBridge) => (
element: React.ReactElement,
container?: SketchLayer | WrappedSketchLayer,
): SketchLayer | Array => {
- if (getSketchVersion() === 'NodeJS') {
- return renderToJSON(element);
- }
-
let nativeContainer: SketchLayer | undefined;
if (container && container.sketchObject) {
nativeContainer = container.sketchObject;
@@ -130,14 +138,14 @@ export const render = (
}
try {
- const tree = buildTree(element);
+ const tree = buildTree(bridge)(element);
injectSymbols(getDocumentDataFromContainer(nativeContainer));
- return renderTree(tree, nativeContainer);
+ return renderTree(bridge)(tree, nativeContainer);
} catch (err) {
console.error(err);
- const tree = buildTree();
- return renderContents(tree, nativeContainer);
+ const tree = buildTree(bridge)();
+ return renderContents(bridge)(tree, nativeContainer);
}
};
diff --git a/src/renderToJSON.ts b/src/renderToJSON.ts
new file mode 100644
index 00000000..133690d1
--- /dev/null
+++ b/src/renderToJSON.ts
@@ -0,0 +1,12 @@
+import { FileFormat1 as FileFormat } from '@sketch-hq/sketch-file-format-ts';
+import { PlatformBridge } from './types';
+import { buildTree } from './buildTree';
+import { flexToSketchJSON } from './flexToSketchJSON';
+import * as React from 'react';
+
+export const renderToJSON = (platformBridge: PlatformBridge) => (
+ element: React.ReactElement,
+): FileFormat.AnyLayer => {
+ const tree = buildTree(platformBridge)(element);
+ return flexToSketchJSON(platformBridge)(tree);
+};
diff --git a/src/renderers/ArtboardRenderer.ts b/src/renderers/ArtboardRenderer.ts
index adb1ad71..93950c76 100644
--- a/src/renderers/ArtboardRenderer.ts
+++ b/src/renderers/ArtboardRenderer.ts
@@ -1,11 +1,11 @@
import { FileFormat1 as FileFormat } from '@sketch-hq/sketch-file-format-ts';
import { generateID, makeRect, makeColorFromCSS } from '../jsonUtils/models';
-import makeResizeConstraint from '../jsonUtils/resizeConstraint';
-import SketchRenderer from './SketchRenderer';
+import { makeResizeConstraint } from '../jsonUtils/resizeConstraint';
+import { SketchRenderer } from './SketchRenderer';
import { TreeNode } from '../types';
import { Props } from '../components/Artboard';
-export default class ArtboardRenderer extends SketchRenderer {
+export class ArtboardRenderer extends SketchRenderer {
renderGroupLayer({ layout, style, props }: TreeNode): FileFormat.Artboard {
let color: FileFormat.Color | undefined;
if (style.backgroundColor !== undefined) {
diff --git a/src/renderers/ImageRenderer.ts b/src/renderers/ImageRenderer.ts
index 293a42f8..e444a87a 100644
--- a/src/renderers/ImageRenderer.ts
+++ b/src/renderers/ImageRenderer.ts
@@ -1,6 +1,6 @@
import { FileFormat1 as FileFormat } from '@sketch-hq/sketch-file-format-ts';
-import SketchRenderer from './SketchRenderer';
-import getImageDataFromURL from '../utils/getImageDataFromURL';
+import { SketchRenderer } from './SketchRenderer';
+import { getImageDataFromURL } from '../utils/getImageDataFromURL';
// import processTransform from './processTransform';
import { makeRect, makeImageFill, makeJSONDataReference, generateID } from '../jsonUtils/models';
import { makeRectShapeLayer, makeShapeGroup } from '../jsonUtils/shapeLayers';
@@ -15,7 +15,7 @@ function extractURLFromSource(source?: string | { uri?: string } | null): string
return (source || {}).uri;
}
-export default class ImageRenderer extends SketchRenderer {
+export class ImageRenderer extends SketchRenderer {
renderBackingLayers({
layout,
style,
@@ -32,7 +32,7 @@ export default class ImageRenderer extends SketchRenderer {
const url = extractURLFromSource(props.source);
- const image = getImageDataFromURL(url);
+ const image = getImageDataFromURL(this.platformBridge)(url);
const fillImage = makeJSONDataReference(image);
diff --git a/src/renderers/SketchRenderer.ts b/src/renderers/SketchRenderer.ts
index b2f70998..3fca03f2 100644
--- a/src/renderers/SketchRenderer.ts
+++ b/src/renderers/SketchRenderer.ts
@@ -1,12 +1,18 @@
import { FileFormat1 as FileFormat } from '@sketch-hq/sketch-file-format-ts';
-import layerGroup from '../jsonUtils/layerGroup';
-import hotspotLayer from '../jsonUtils/hotspotLayer';
-import { TreeNode } from '../types';
-import processTransform from '../utils/processTransform';
+import { layerGroup } from '../jsonUtils/layerGroup';
+import { hotspotLayer } from '../jsonUtils/hotspotLayer';
+import { TreeNode, PlatformBridge } from '../types';
+import { processTransform } from '../utils/processTransform';
const DEFAULT_OPACITY = 1.0;
-export default class SketchRenderer {
+export class SketchRenderer {
+ protected readonly platformBridge: PlatformBridge;
+
+ constructor(bridge: PlatformBridge) {
+ this.platformBridge = bridge;
+ }
+
getDefaultGroupName(_props: any) {
return 'Group';
}
diff --git a/src/renderers/SvgRenderer.ts b/src/renderers/SvgRenderer.ts
index ec6149f7..0b484311 100644
--- a/src/renderers/SvgRenderer.ts
+++ b/src/renderers/SvgRenderer.ts
@@ -1,6 +1,6 @@
-import ViewRenderer from './ViewRenderer';
+import { ViewRenderer } from './ViewRenderer';
import { TreeNode } from '../types';
-import makeSvgLayer from '../jsonUtils/svgLayer';
+import { makeSvgLayer } from '../jsonUtils/makeSvgLayer';
import { Props } from '../components/Svg/Svg';
const snakeExceptions = [
@@ -22,7 +22,7 @@ function toSnakeCase(string: string) {
if (snakeExceptions.indexOf(string) !== -1) {
return string;
}
- return string.replace(/([A-Z])/g, $1 => `-${$1.toLowerCase()}`);
+ return string.replace(/([A-Z])/g, ($1) => `-${$1.toLowerCase()}`);
}
function makeSvgString(el: string | TreeNode) {
@@ -61,7 +61,7 @@ function makeSvgString(el: string | TreeNode) {
return string;
}
-export default class SvgRenderer extends ViewRenderer {
+export class SvgRenderer extends ViewRenderer {
getDefaultGroupName(props: Props) {
return props.name || 'Svg';
}
diff --git a/src/renderers/SymbolInstanceRenderer.ts b/src/renderers/SymbolInstanceRenderer.ts
index 9d3d0372..36e44b04 100644
--- a/src/renderers/SymbolInstanceRenderer.ts
+++ b/src/renderers/SymbolInstanceRenderer.ts
@@ -1,5 +1,5 @@
import { FileFormat1 as FileFormat } from '@sketch-hq/sketch-file-format-ts';
-import SketchRenderer from './SketchRenderer';
+import { SketchRenderer } from './SketchRenderer';
import {
makeSymbolInstance,
makeRect,
@@ -8,7 +8,7 @@ import {
} from '../jsonUtils/models';
import { TreeNode } from '../types';
import { getSymbolMasterById, SymbolInstanceProps } from '../symbol';
-import getImageDataFromURL from '../utils/getImageDataFromURL';
+import { getImageDataFromURL } from '../utils/getImageDataFromURL';
type Override = {
type: 'symbolID' | 'stringValue' | 'layerStyle' | 'textStyle' | 'flowDestination' | 'image';
@@ -18,10 +18,10 @@ type Override = {
};
const findInGroup = (layer: FileFormat.AnyGroup, type: string): FileFormat.AnyLayer | undefined =>
- layer && layer.layers && layer.layers.find(l => l._class === type);
+ layer && layer.layers && layer.layers.find((l) => l._class === type);
const hasImageFill = (layer: FileFormat.AnyLayer): boolean =>
- !!(layer.style && layer.style.fills && layer.style.fills.some(f => f.image));
+ !!(layer.style && layer.style.fills && layer.style.fills.some((f) => f.image));
const removeDuplicateOverrides = (overrides: Array): Array => {
const seen: { [path: string]: boolean } = {};
@@ -97,11 +97,12 @@ const extractOverrides = (layers: FileFormat.AnyLayer[] = [], path?: string): Ov
return removeDuplicateOverrides(overrides);
};
-export default class SymbolInstanceRenderer extends SketchRenderer {
+export class SymbolInstanceRenderer extends SketchRenderer {
renderGroupLayer({
layout,
props,
}: TreeNode) {
+ const bridge = this.platformBridge;
const masterTree = getSymbolMasterById(props.symbolID);
if (!masterTree) {
@@ -199,7 +200,7 @@ export default class SymbolInstanceRenderer extends SketchRenderer {
makeOverride(
reference.path,
reference.type,
- makeJSONDataReference(getImageDataFromURL(overrideValue)),
+ makeJSONDataReference(getImageDataFromURL(bridge)(overrideValue)),
),
);
}
diff --git a/src/renderers/SymbolMasterRenderer.ts b/src/renderers/SymbolMasterRenderer.ts
index cec99c6f..6bed91a0 100644
--- a/src/renderers/SymbolMasterRenderer.ts
+++ b/src/renderers/SymbolMasterRenderer.ts
@@ -1,9 +1,9 @@
import { makeSymbolMaster, makeRect } from '../jsonUtils/models';
-import SketchRenderer from './SketchRenderer';
+import { SketchRenderer } from './SketchRenderer';
import { TreeNode } from '../types';
import { SymbolMasterProps } from '../symbol';
-export default class SymbolMasterRenderer extends SketchRenderer {
+export class SymbolMasterRenderer extends SketchRenderer {
renderGroupLayer({
layout,
props,
diff --git a/src/renderers/TextRenderer.ts b/src/renderers/TextRenderer.ts
index 582fc439..9176153d 100644
--- a/src/renderers/TextRenderer.ts
+++ b/src/renderers/TextRenderer.ts
@@ -1,11 +1,11 @@
-import SketchRenderer from './SketchRenderer';
+import { SketchRenderer } from './SketchRenderer';
import { TreeNode } from '../types';
-import makeTextLayer from '../jsonUtils/textLayers';
+import { makeTextLayer } from '../jsonUtils/textLayers';
import { makeRect } from '../jsonUtils/models';
-import TextStyles from '../sharedStyles/TextStyles';
+import { TextStyles } from '../sharedStyles/TextStyles';
import { Props } from '../components/Text';
-export default class TextRenderer extends SketchRenderer {
+export class TextRenderer extends SketchRenderer {
getDefaultGroupName(props: Props) {
return props.name || 'Text';
}
@@ -14,10 +14,10 @@ export default class TextRenderer extends SketchRenderer {
// Append all text nodes's content into one string if name is missing
const resolvedName = props.name
? props.name
- : props.textNodes.map(textNode => textNode.content).join('');
+ : props.textNodes.map((textNode) => textNode.content).join('');
const frame = makeRect(0, 0, layout.width, layout.height);
- const layer = makeTextLayer(
+ const layer = makeTextLayer(this.platformBridge)(
frame,
resolvedName,
props.textNodes,
@@ -26,7 +26,7 @@ export default class TextRenderer extends SketchRenderer {
props.shadows,
);
- const resolvedTextStyle = TextStyles.resolve(textStyle);
+ const resolvedTextStyle = TextStyles(() => this.platformBridge).resolve(textStyle);
if (resolvedTextStyle) {
if (!layer.style) {
layer.style = resolvedTextStyle.sketchStyle;
diff --git a/src/renderers/ViewRenderer.ts b/src/renderers/ViewRenderer.ts
index e7ea6183..ccdc43b2 100644
--- a/src/renderers/ViewRenderer.ts
+++ b/src/renderers/ViewRenderer.ts
@@ -1,10 +1,10 @@
import { FileFormat1 as FileFormat } from '@sketch-hq/sketch-file-format-ts';
-import SketchRenderer from './SketchRenderer';
+import { SketchRenderer } from './SketchRenderer';
import { makeRect } from '../jsonUtils/models';
import { makeRectShapeLayer, makeShapeGroup } from '../jsonUtils/shapeLayers';
import { TreeNode } from '../types';
import { createBorders } from '../jsonUtils/borders';
-import hasAnyDefined from '../utils/hasAnyDefined';
+import { hasAnyDefined } from '../utils/hasAnyDefined';
import { Props } from '../components/View';
const VISIBLE_STYLES = [
@@ -33,7 +33,7 @@ const VISIBLE_STYLES = [
const OVERFLOW_STYLES = ['overflow', 'overflowX', 'overflowY'];
-export default class ViewRenderer extends SketchRenderer {
+export class ViewRenderer extends SketchRenderer {
getDefaultGroupName(_props: Props) {
return 'View';
}
diff --git a/src/renderers/index.ts b/src/renderers/index.ts
index 069497b9..12da9647 100644
--- a/src/renderers/index.ts
+++ b/src/renderers/index.ts
@@ -1,7 +1,7 @@
-export { default as sketch_artboard } from './ArtboardRenderer';
-export { default as sketch_image } from './ImageRenderer';
-export { default as sketch_svg } from './SvgRenderer';
-export { default as sketch_text } from './TextRenderer';
-export { default as sketch_view } from './ViewRenderer';
-export { default as sketch_symbolinstance } from './SymbolInstanceRenderer';
-export { default as sketch_symbolmaster } from './SymbolMasterRenderer';
+export { ArtboardRenderer as sketch_artboard } from './ArtboardRenderer';
+export { ImageRenderer as sketch_image } from './ImageRenderer';
+export { SvgRenderer as sketch_svg } from './SvgRenderer';
+export { TextRenderer as sketch_text } from './TextRenderer';
+export { ViewRenderer as sketch_view } from './ViewRenderer';
+export { SymbolInstanceRenderer as sketch_symbolinstance } from './SymbolInstanceRenderer';
+export { SymbolMasterRenderer as sketch_symbolmaster } from './SymbolMasterRenderer';
diff --git a/src/resets.ts b/src/resets.ts
index 27b23808..85ffb2c4 100644
--- a/src/resets.ts
+++ b/src/resets.ts
@@ -1,6 +1,6 @@
import { SketchDocumentData, SketchPage } from './types';
-import isNativeDocument from './utils/isNativeDocument';
-import isNativeSymbolsPage from './utils/isNativeSymbolsPage';
+import { isNativeDocument } from './utils/isNativeDocument';
+import { isNativeSymbolsPage } from './utils/isNativeSymbolsPage';
export const resetLayer = (container: SketchDocumentData | SketchPage) => {
if (isNativeDocument(container)) {
diff --git a/src/sharedStyles/TextStyles.ts b/src/sharedStyles/TextStyles.ts
index 90d87abf..df4b4e5a 100644
--- a/src/sharedStyles/TextStyles.ts
+++ b/src/sharedStyles/TextStyles.ts
@@ -1,11 +1,17 @@
import { FileFormat1 as FileFormat } from '@sketch-hq/sketch-file-format-ts';
-import { SketchDocumentData, SketchDocument, WrappedSketchDocument, TextStyle } from '../types';
+import {
+ SketchDocumentData,
+ SketchDocument,
+ WrappedSketchDocument,
+ TextStyle,
+ PlatformBridge,
+} from '../types';
import { getSketchVersion } from '../utils/getSketchVersion';
-import hashStyle from '../utils/hashStyle';
+import { hashStyle } from '../utils/hashStyle';
import { getDocument } from '../utils/getDocument';
-import sharedTextStyles from '../utils/sharedTextStyles';
+import { sharedTextStyles } from '../utils/sharedTextStyles';
import { makeTextStyle } from '../jsonUtils/textLayers';
-import pick from '../utils/pick';
+import { pick } from '../utils/pick';
import { INHERITABLE_FONT_STYLES } from '../utils/constants';
type MurmurHash = string;
@@ -19,103 +25,105 @@ type RegisteredStyle = {
type StyleHash = { [key: string]: RegisteredStyle };
-let _styles: StyleHash = {};
-const _byName: { [key: string]: MurmurHash } = {};
-
-const sketchVersion = getSketchVersion();
-
-const registerStyle = (name: string, style: TextStyle) => {
- const safeStyle = pick(style, INHERITABLE_FONT_STYLES);
- const hash = hashStyle(safeStyle);
- const sketchStyle = makeTextStyle(safeStyle);
- const sharedObjectID = sharedTextStyles.addStyle(name, sketchStyle);
-
- // FIXME(gold): side effect :'(
- _byName[name] = hash;
-
- _styles[hash] = {
- cssStyle: safeStyle,
- name,
- sketchStyle,
- sharedObjectID,
- };
-};
-
type Options = {
clearExistingStyles?: boolean;
document?: SketchDocumentData | SketchDocument | WrappedSketchDocument;
};
-const create = (styles: { [key: string]: TextStyle }, options: Options = {}): StyleHash => {
- const { clearExistingStyles, document } = options;
-
- const doc = getDocument(document);
+let _styles: StyleHash = {};
+const _byName: { [key: string]: MurmurHash } = {};
- if (sketchVersion !== 'NodeJS' && sketchVersion < 50) {
- if (doc) {
- doc.showMessage('💎 Requires Sketch 50+ 💎');
+export const TextStyles = (getDefaultBridge: () => PlatformBridge) => ({
+ registerStyle(
+ name: string,
+ style: TextStyle,
+ platformBridge: PlatformBridge = getDefaultBridge(),
+ ) {
+ const safeStyle = pick(style, INHERITABLE_FONT_STYLES);
+ const hash = hashStyle(safeStyle);
+ const sketchStyle = makeTextStyle(platformBridge)(safeStyle);
+ const sharedObjectID = sharedTextStyles.addStyle(name, sketchStyle);
+
+ // FIXME(gold): side effect :'(
+ _byName[name] = hash;
+
+ _styles[hash] = {
+ cssStyle: safeStyle,
+ name,
+ sketchStyle,
+ sharedObjectID,
+ };
+ },
+
+ create(
+ styles: { [key: string]: TextStyle },
+ options: Options = {},
+ platformBridge: PlatformBridge = getDefaultBridge(),
+ ): StyleHash {
+ const { clearExistingStyles, document } = options;
+
+ const doc = getDocument(document);
+
+ const sketchVersion = getSketchVersion();
+
+ if (sketchVersion !== 'NodeJS' && sketchVersion < 50) {
+ if (doc) {
+ doc.showMessage('💎 Requires Sketch 50+ 💎');
+ }
+ return {};
}
- return {};
- }
- sharedTextStyles.setDocument(doc);
+ sharedTextStyles.setDocument(doc);
- if (clearExistingStyles) {
- _styles = {};
- sharedTextStyles.setStyles([]);
- }
-
- Object.keys(styles).forEach(name => registerStyle(name, styles[name]));
-
- return _styles;
-};
+ if (clearExistingStyles) {
+ _styles = {};
+ sharedTextStyles.setStyles([]);
+ }
-const resolve = (style?: TextStyle): RegisteredStyle | undefined => {
- if (!style) {
- return undefined;
- }
- const safeStyle = pick(style, INHERITABLE_FONT_STYLES);
- const hash = hashStyle(safeStyle);
+ Object.keys(styles).forEach((name) => this.registerStyle(name, styles[name], platformBridge));
- return _styles[hash];
-};
+ return _styles;
+ },
-const get = (
- name: string,
- document?: SketchDocumentData | SketchDocument | WrappedSketchDocument,
-): TextStyle | undefined => {
- const hash = _byName[name];
- const style = _styles[hash];
+ resolve(style?: TextStyle): RegisteredStyle | undefined {
+ if (!style) {
+ return undefined;
+ }
+ const safeStyle = pick(style, INHERITABLE_FONT_STYLES);
+ const hash = hashStyle(safeStyle);
- if (style) {
- return style.cssStyle;
- }
+ return _styles[hash];
+ },
- return sharedTextStyles.getStyle(name, document ? getDocument(document) : undefined);
-};
+ get(
+ name: string,
+ document?: SketchDocumentData | SketchDocument | WrappedSketchDocument,
+ ): TextStyle | undefined {
+ const hash = _byName[name];
+ const style = _styles[hash];
-const clear = () => {
- _styles = {};
- sharedTextStyles.setStyles([]);
-};
+ if (style) {
+ return style.cssStyle;
+ }
-const toJSON = (): FileFormat.SharedStyle[] =>
- Object.keys(_styles).map(k => ({
- _class: 'sharedStyle',
- do_objectID: _styles[k].sharedObjectID,
- name: _styles[k].name,
- value: _styles[k].sketchStyle,
- }));
-
-const styles = () => _styles;
-
-const TextStyles = {
- create,
- resolve,
- get,
- styles,
- clear,
- toJSON,
-};
+ return sharedTextStyles.getStyle(name, document ? getDocument(document) : undefined);
+ },
-export default TextStyles;
+ clear(): void {
+ _styles = {};
+ sharedTextStyles.setStyles([]);
+ },
+
+ toJSON(): FileFormat.SharedStyle[] {
+ return Object.keys(_styles).map((k) => ({
+ _class: 'sharedStyle',
+ do_objectID: _styles[k].sharedObjectID,
+ name: _styles[k].name,
+ value: _styles[k].sketchStyle,
+ }));
+ },
+
+ styles() {
+ return _styles;
+ },
+});
diff --git a/src/stylesheet/expandStyle.ts b/src/stylesheet/expandStyle.ts
index ebfe2045..b2f243b4 100644
--- a/src/stylesheet/expandStyle.ts
+++ b/src/stylesheet/expandStyle.ts
@@ -89,7 +89,7 @@ const sortProps = (propsArray: string[]) =>
/**
* Expand the shorthand properties to isolate every declaration from the others.
*/
-export default (style: RawStyle): Style => {
+export const expandStyle = (style: RawStyle): Style => {
if (!style) return style;
const propsArray = Object.keys(style);
const sortedProps = sortProps(propsArray);
diff --git a/src/stylesheet/index.ts b/src/stylesheet/index.ts
index 9deaa1ab..a81439a7 100644
--- a/src/stylesheet/index.ts
+++ b/src/stylesheet/index.ts
@@ -1,4 +1,4 @@
-import expandStyle from './expandStyle';
+import { expandStyle } from './expandStyle';
import {
RawStyle,
RawStyles,
@@ -18,7 +18,7 @@ const declarationRegistry: { [id: string]: Style } = {};
const extractRules = (style: RawStyle): Rules => {
const declarations: { [key: string]: any } = {};
- Object.keys(style).forEach(key => {
+ Object.keys(style).forEach((key) => {
if (key[0] === ':') {
// pseudo style. ignore for now.
} else if (key[0] === '@') {
@@ -46,7 +46,7 @@ const getStyle = (id: StyleId): Style => declarationRegistry[id];
const create = (styles: RawStyles): StyleSheetInstance => {
const result: StyleSheetInstance = {};
- Object.keys(styles).forEach(key => {
+ Object.keys(styles).forEach((key) => {
result[key] = registerStyle(styles[key]);
});
return result;
@@ -61,7 +61,7 @@ const mergeTransforms = (a?: Transform, b?: Transform): Transform | undefined =>
hash[key] = result.length - 1;
return hash;
}, {});
- (b || []).forEach(t => {
+ (b || []).forEach((t) => {
const key = Object.keys(t)[0];
const index = transformsInA[key];
if (index !== undefined) {
@@ -77,7 +77,7 @@ const mergeTransforms = (a?: Transform, b?: Transform): Transform | undefined =>
// special case.
// NOTE(lmr): mutates the first argument!
const mergeStyle = (a: Style, b: Style): Style => {
- Object.keys(b).forEach(key => {
+ Object.keys(b).forEach((key) => {
if (key === 'transform') {
a[key] = mergeTransforms(a[key], b[key]);
} else {
@@ -105,7 +105,7 @@ const flattenStyle = (input?: UserStyles | null): Style | undefined => {
/**
* A StyleSheet is an abstraction similar to CSS StyleSheets. WIP.
*/
-export default {
+export const StyleSheet = {
hairlineWidth: 1, // TODO(lmr): should this be something different?
absoluteFill: registerStyle({
position: 'absolute',
diff --git a/src/symbol.tsx b/src/symbol.tsx
index 7fa17995..2b958f5b 100644
--- a/src/symbol.tsx
+++ b/src/symbol.tsx
@@ -1,18 +1,18 @@
import * as React from 'react';
import * as PropTypes from 'prop-types';
import { FileFormat1 as FileFormat } from '@sketch-hq/sketch-file-format-ts';
-import { fromSJSON } from './jsonUtils/sketchImpl/json-to-sketch';
-import { toSJSON } from './jsonUtils/sketchImpl/sketch-to-json';
-import StyleSheet from './stylesheet';
+import { fromSJSON } from './jsonUtils/sketchJson/fromSJSON';
+import { toSJSON } from './jsonUtils/sketchJson/toSJSON';
+import { StyleSheet } from './stylesheet';
import { generateID } from './jsonUtils/models';
-import ViewStylePropTypes from './components/ViewStylePropTypes';
-import ResizingConstraintPropTypes from './components/ResizingConstraintPropTypes';
-import buildTree from './buildTree';
-import flexToSketchJSON from './flexToSketchJSON';
+import { ViewStylePropTypes } from './components/ViewStylePropTypes';
+import { ResizingConstraintPropTypes } from './components/ResizingConstraintPropTypes';
+import { buildTree } from './buildTree';
+import { flexToSketchJSON } from './flexToSketchJSON';
import { renderLayers } from './render';
import { resetLayer } from './resets';
import { getDocumentData } from './utils/getDocument';
-import { SketchDocumentData, SketchDocument, WrappedSketchDocument } from './types';
+import { SketchDocumentData, SketchDocument, WrappedSketchDocument, PlatformBridge } from './types';
import { getSketchVersion } from './utils/getSketchVersion';
let id = 0;
@@ -48,7 +48,7 @@ const getExistingSymbols = (documentData: SketchDocumentData) => {
const symbolsPage = getSymbolsPage(documentData);
existingSymbols = msListToArray(symbolsPage.layers())
- .map(x => {
+ .map((x) => {
const symbolJson = toSJSON(x);
if (!symbolJson || symbolJson._class !== 'symbolMaster') {
return undefined;
@@ -58,7 +58,7 @@ const getExistingSymbols = (documentData: SketchDocumentData) => {
})
.filter(exists);
- existingSymbols.forEach(symbolMaster => {
+ existingSymbols.forEach((symbolMaster) => {
if (symbolMaster._class !== 'symbolMaster') return;
if (symbolMaster.name in symbolsRegistry) return;
symbolsRegistry[symbolMaster.name] = symbolMaster;
@@ -89,7 +89,7 @@ export const injectSymbols = (
const symbolsPage = getSymbolsPage(documentData);
let left = 0;
- Object.keys(symbolsRegistry).forEach(key => {
+ Object.keys(symbolsRegistry).forEach((key) => {
const symbolMaster = symbolsRegistry[key];
symbolMaster.frame.y = 0;
symbolMaster.frame.x = left;
@@ -103,7 +103,7 @@ export const injectSymbols = (
resetLayer(symbolsPage);
renderLayers(
- Object.keys(layers).map(k => layers[k]),
+ Object.keys(layers).map((k) => layers[k]),
symbolsPage,
);
@@ -153,7 +153,7 @@ const SymbolMasterPropTypes = {
export type SymbolMasterProps = PropTypes.InferProps;
-export const makeSymbol = (
+export const makeSymbol = (bridge: PlatformBridge) => (
Component: React.ComponentType,
symbolProps: string | SymbolMasterProps,
document?: SketchDocumentData | SketchDocument | WrappedSketchDocument,
@@ -168,13 +168,13 @@ export const makeSymbol = (
const masterName =
(typeof symbolProps === 'string' ? symbolProps : (symbolProps || {}).name) ||
displayName(Component);
- const existingSymbol = existingSymbols.find(symbolMaster => symbolMaster.name === masterName);
+ const existingSymbol = existingSymbols.find((symbolMaster) => symbolMaster.name === masterName);
const symbolID = existingSymbol
? existingSymbol.symbolID
: generateID(`symbolID:${masterName}`, !!masterName);
- const symbolMaster = flexToSketchJSON(
- buildTree(
+ const symbolMaster = flexToSketchJSON(bridge)(
+ buildTree(bridge)(
symbols[k].name() === name);
+ const symbol = Object.keys(symbols).find((k) => symbols[k].name() === name);
if (!symbol) {
return undefined;
@@ -233,7 +233,7 @@ export const getSymbolMasterByName = (
document?: SketchDocumentData | SketchDocument | WrappedSketchDocument,
): FileFormat.SymbolMaster | undefined => {
const symbolID = name
- ? Object.keys(symbolsRegistry).find(key => String(symbolsRegistry[key].name) === name)
+ ? Object.keys(symbolsRegistry).find((key) => String(symbolsRegistry[key].name) === name)
: '';
if (typeof symbolID === 'undefined' && name && getSketchVersion() !== 'NodeJS') {
diff --git a/src/types/index.ts b/src/types/index.ts
index 761ebc61..2953c397 100644
--- a/src/types/index.ts
+++ b/src/types/index.ts
@@ -1,10 +1,11 @@
import * as PropTypes from 'prop-types';
-import ViewStylePropTypes, {
+import {
+ ViewStylePropTypes,
Color as ColorProp,
BorderStyle as BorderProp,
Overflow as OverflowProp,
} from '../components/ViewStylePropTypes';
-import TextStylePropTypes from '../components/TextStylePropTypes';
+import { TextStylePropTypes } from '../components/TextStylePropTypes';
// Sketchy things
export type SketchLayer = any;
@@ -119,3 +120,9 @@ export type ResizeConstraints = {
fixedHeight?: boolean;
fixedWidth?: boolean;
};
+
+export type PlatformBridge = {
+ createStringMeasurer(textNodes: TextNode[], maxWidth: number): Size;
+ findFontName(style: TextStyle): string;
+ makeImageDataFromUrl(url?: string): string;
+};
diff --git a/src/types/node-sketch-bridge.d.ts b/src/types/node-sketch-bridge.d.ts
new file mode 100644
index 00000000..3508fda4
--- /dev/null
+++ b/src/types/node-sketch-bridge.d.ts
@@ -0,0 +1 @@
+declare module 'node-sketch-bridge';
diff --git a/src/utils/Context.ts b/src/utils/Context.ts
index ad3df235..2f50655b 100644
--- a/src/utils/Context.ts
+++ b/src/utils/Context.ts
@@ -1,6 +1,6 @@
type Styles = Object;
-class Context {
+export class Context {
styles: Styles;
staged: Array;
@@ -26,5 +26,3 @@ class Context {
return this.styles;
}
}
-
-export default Context;
diff --git a/src/utils/createStringMeasurer.ts b/src/utils/createStringMeasurer.ts
index 9cbf3c32..98f6dff1 100644
--- a/src/utils/createStringMeasurer.ts
+++ b/src/utils/createStringMeasurer.ts
@@ -1,21 +1,18 @@
-import { TextNode, Size } from '../types';
-import { getSketchVersion } from './getSketchVersion';
-import sketchMethod from '../jsonUtils/sketchImpl/createStringMeasurer';
-import nodeMethod from '../jsonUtils/nodeImpl/createStringMeasurer';
+import { TextNode, Size, PlatformBridge } from '../types';
-const createStringMeasurer = (textNodes: TextNode[]) => (width: number = 0): Size => {
- // width would be obj-c NaN and the only way to check for it is by comparing
+function isNaN(num: number): boolean {
+ // If the value is obj-c NaN, the only way to check for it is by comparing
// width to itself (because NaN !== NaN)
- const _width = width !== width ? 0 : width;
+ // eslint-disable-next-line no-self-compare
+ return Number.isNaN(num) || num !== num;
+}
- if (textNodes.length > 0) {
- if (getSketchVersion() === 'NodeJS') {
- return nodeMethod(textNodes, _width);
- }
- return sketchMethod(textNodes, _width);
- }
+export const createStringMeasurer = (bridge: PlatformBridge) => (textNodes: TextNode[]) => (
+ width: number = 0,
+): Size => {
+ const sanitizedWidth = isNaN(width) ? 0 : width;
- return { width: _width, height: 0 };
+ return textNodes.length > 0
+ ? bridge.createStringMeasurer(textNodes, sanitizedWidth)
+ : { width: sanitizedWidth, height: 0 };
};
-
-export default createStringMeasurer;
diff --git a/src/utils/findFont.ts b/src/utils/findFont.ts
deleted file mode 100644
index 394a22c9..00000000
--- a/src/utils/findFont.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-import { TextStyle } from '../types';
-
-import { getSketchVersion } from './getSketchVersion';
-import sketchMethod from '../jsonUtils/sketchImpl/findFontName';
-import nodeMethod from '../jsonUtils/nodeImpl/findFontName';
-
-const findFontName = (style: TextStyle) => {
- if (getSketchVersion() === 'NodeJS') {
- return nodeMethod(style);
- }
- return sketchMethod(style);
-};
-
-export default findFontName;
diff --git a/src/utils/getImageDataFromURL.ts b/src/utils/getImageDataFromURL.ts
index e7b19312..2e5a4a4f 100644
--- a/src/utils/getImageDataFromURL.ts
+++ b/src/utils/getImageDataFromURL.ts
@@ -1,15 +1,13 @@
import sha1 from 'js-sha1';
-import { getSketchVersion } from './getSketchVersion';
-import sketchMethod from '../jsonUtils/sketchImpl/makeImageDataFromUrl';
-import nodeMethod from '../jsonUtils/nodeImpl/makeImageDataFromUrl';
+import { PlatformBridge } from '../types';
-const makeImageDataFromUrl = (url?: string): { data: string; sha1: string } => {
- const data = getSketchVersion() === 'NodeJS' ? nodeMethod(url) : sketchMethod(url);
+export const getImageDataFromURL = (bridge: PlatformBridge) => (
+ url?: string,
+): { data: string; sha1: string } => {
+ const data = bridge.makeImageDataFromUrl(url);
return {
data,
sha1: sha1(data),
};
};
-
-export default makeImageDataFromUrl;
diff --git a/src/utils/hasAnyDefined.ts b/src/utils/hasAnyDefined.ts
index 4db6cb78..22423047 100644
--- a/src/utils/hasAnyDefined.ts
+++ b/src/utils/hasAnyDefined.ts
@@ -1,4 +1,2 @@
-const hasAnyDefined = (obj: { [key: string]: unknown }, names: readonly string[]): boolean =>
- names.some(key => obj[key] !== undefined);
-
-export default hasAnyDefined;
+export const hasAnyDefined = (obj: { [key: string]: unknown }, names: readonly string[]): boolean =>
+ names.some((key) => obj[key] !== undefined);
diff --git a/src/utils/hashStyle.ts b/src/utils/hashStyle.ts
index ee0b7ef1..a698e770 100644
--- a/src/utils/hashStyle.ts
+++ b/src/utils/hashStyle.ts
@@ -1,11 +1,9 @@
import murmurHash from 'murmur2js';
-import sortObjectKeys from './sortObjectKeys';
+import { sortObjectKeys } from './sortObjectKeys';
-const hashStyle = (obj: { [key: string]: unknown }): string => {
+export const hashStyle = (obj: { [key: string]: unknown }): string => {
if (obj) {
return String(murmurHash(JSON.stringify(sortObjectKeys(obj))));
}
return '0';
};
-
-export default hashStyle;
diff --git a/src/utils/isDefined.ts b/src/utils/isDefined.ts
index d75e703f..f7612b1f 100644
--- a/src/utils/isDefined.ts
+++ b/src/utils/isDefined.ts
@@ -1 +1,2 @@
-export default (value: unknown): value is number => value !== null && typeof value !== 'undefined';
+export const isDefined = (value: unknown): value is number =>
+ value !== null && typeof value !== 'undefined';
diff --git a/src/utils/isNativeDocument.ts b/src/utils/isNativeDocument.ts
index 27c60300..67655402 100644
--- a/src/utils/isNativeDocument.ts
+++ b/src/utils/isNativeDocument.ts
@@ -1,5 +1,5 @@
import { SketchDocumentData } from '../types';
-export default (container: unknown): container is SketchDocumentData =>
+export const isNativeDocument = (container: unknown): container is SketchDocumentData =>
// @ts-ignore
container && typeof container.pages === 'function';
diff --git a/src/utils/isNativePage.ts b/src/utils/isNativePage.ts
index e3400074..94c374b7 100644
--- a/src/utils/isNativePage.ts
+++ b/src/utils/isNativePage.ts
@@ -1,3 +1,4 @@
import { SketchPage } from '../types';
-export default (container: unknown): container is SketchPage => container instanceof MSPage;
+export const isNativePage = (container: unknown): container is SketchPage =>
+ container instanceof MSPage;
diff --git a/src/utils/isNativeSymbolsPage.ts b/src/utils/isNativeSymbolsPage.ts
index 3b70d3c5..cbd0e07e 100644
--- a/src/utils/isNativeSymbolsPage.ts
+++ b/src/utils/isNativeSymbolsPage.ts
@@ -1,7 +1,5 @@
-import isNativePage from './isNativePage';
+import { isNativePage } from './isNativePage';
// NOTE: Must cast to string as page.name() returns a MSBoxedObject
-const isNativeSymbolsPage = (layer: unknown): boolean =>
+export const isNativeSymbolsPage = (layer: unknown): boolean =>
isNativePage(layer) && String(layer.name()) === 'Symbols';
-
-export default isNativeSymbolsPage;
diff --git a/src/utils/pick.ts b/src/utils/pick.ts
index a3de54ea..99307d8e 100644
--- a/src/utils/pick.ts
+++ b/src/utils/pick.ts
@@ -1,11 +1,9 @@
-function pick(obj: T, keys: readonly K[]): Pick {
+export function pick(obj: T, keys: readonly K[]): Pick {
const ret: any = {};
- keys.forEach(key => {
+ keys.forEach((key) => {
if (obj[key] !== undefined) {
ret[key] = obj[key];
}
});
return ret;
}
-
-export default pick;
diff --git a/src/utils/processTransform/index.ts b/src/utils/processTransform/index.ts
index 05291117..026359b8 100644
--- a/src/utils/processTransform/index.ts
+++ b/src/utils/processTransform/index.ts
@@ -1,6 +1,6 @@
import { LayoutInfo, ViewStyle } from '../../types';
-import parseTransformProp from './parseTransformProp';
-import parseTransformOriginProp from './parseTransformOriginProp';
+import { parseTransformProp } from './parseTransformProp';
+import { parseTransformOriginProp } from './parseTransformOriginProp';
function closeEnough(a: number, b: number) {
return Math.abs(a - b) < 0.01;
@@ -21,7 +21,7 @@ function getRotation(a: number, b: number) {
return sketchFactor * (possibleRotation + Math.PI) * rad2deg;
}
-export default function(
+export function processTransform(
layout: LayoutInfo,
props: ViewStyle,
): { rotation?: number; isFlippedVertical?: boolean; isFlippedHorizontal?: boolean } {
diff --git a/src/utils/processTransform/matrix2D.ts b/src/utils/processTransform/matrix2D.ts
index c956df00..f76a99bd 100644
--- a/src/utils/processTransform/matrix2D.ts
+++ b/src/utils/processTransform/matrix2D.ts
@@ -15,7 +15,7 @@
*
* Note the locations of b and c.
* */
-export default class Matrix2D {
+export class Matrix2D {
a: number;
b: number;
diff --git a/src/utils/processTransform/parseTransformOriginProp.ts b/src/utils/processTransform/parseTransformOriginProp.ts
index e11909a4..ec86647e 100644
--- a/src/utils/processTransform/parseTransformOriginProp.ts
+++ b/src/utils/processTransform/parseTransformOriginProp.ts
@@ -12,7 +12,10 @@ function isPercentage(token: string) {
return token.indexOf('%') !== -1;
}
-export default function(layout: LayoutInfo, _origin?: string | null): [number, number, number] {
+export function parseTransformOriginProp(
+ layout: LayoutInfo,
+ _origin?: string | null,
+): [number, number, number] {
const origin = (_origin || '').trim();
const tokens = origin.split(' ');
diff --git a/src/utils/processTransform/parseTransformProp.ts b/src/utils/processTransform/parseTransformProp.ts
index 1eaf8b6a..31aba0bc 100644
--- a/src/utils/processTransform/parseTransformProp.ts
+++ b/src/utils/processTransform/parseTransformProp.ts
@@ -1,6 +1,6 @@
// based on https://github.com/react-native-community/react-native-svg/blob/28235ea137a75097c011f11fee92bec8a97b4afa/lib/extract/extractTransform.js
import * as peg from 'pegjs';
-import Matrix2D from './matrix2D';
+import { Matrix2D } from './matrix2D';
const pooledMatrix = new Matrix2D();
@@ -180,6 +180,6 @@ function transformToMatrix(transform: string, origin: [number, number, number])
return pooledMatrix.toArray();
}
-export default function(transform: string, origin: [number, number, number]) {
+export function parseTransformProp(transform: string, origin: [number, number, number]) {
return transformToMatrix(transform, origin);
}
diff --git a/src/utils/same.ts b/src/utils/same.ts
index b988c2bf..495973f5 100644
--- a/src/utils/same.ts
+++ b/src/utils/same.ts
@@ -1,3 +1 @@
-const same = (a: any, b: any, c: any, d: any) => a === b && b === c && c === d;
-
-export default same;
+export const same = (a: any, b: any, c: any, d: any) => a === b && b === c && c === d;
diff --git a/src/utils/sharedTextStyles.ts b/src/utils/sharedTextStyles.ts
deleted file mode 100644
index 117bee6e..00000000
--- a/src/utils/sharedTextStyles.ts
+++ /dev/null
@@ -1,5 +0,0 @@
-import { getSketchVersion } from './getSketchVersion';
-import SketchStyles from '../jsonUtils/sketchImpl/sharedTextStyles';
-import NodeStyles from '../jsonUtils/nodeImpl/sharedTextStyles';
-
-export default getSketchVersion() === 'NodeJS' ? new NodeStyles() : new SketchStyles();
diff --git a/src/jsonUtils/sketchImpl/sharedTextStyles.ts b/src/utils/sharedTextStyles/index.sketch.ts
similarity index 83%
rename from src/jsonUtils/sketchImpl/sharedTextStyles.ts
rename to src/utils/sharedTextStyles/index.sketch.ts
index 26a41646..6ebb3ea1 100644
--- a/src/jsonUtils/sketchImpl/sharedTextStyles.ts
+++ b/src/utils/sharedTextStyles/index.sketch.ts
@@ -1,10 +1,10 @@
import invariant from 'invariant';
-import { fromSJSON } from './json-to-sketch';
-import { toSJSON } from './sketch-to-json';
+import { fromSJSON } from '../../jsonUtils/sketchJson/fromSJSON';
+import { toSJSON } from '../../jsonUtils/sketchJson/toSJSON';
import { FileFormat1 as FileFormat } from '@sketch-hq/sketch-file-format-ts';
import { SketchDocument, TextStyle } from '../../types';
-import { generateID } from '../models';
-import { parseTextStyle } from '../textLayers';
+import { generateID } from '../../jsonUtils/models';
+import { parseTextStyle } from '../../jsonUtils/textLayers';
class TextStyles {
_document: SketchDocument | null;
@@ -23,10 +23,7 @@ class TextStyles {
setStyles(styles: Array) {
invariant(this._document, 'Please provide a sketch document reference');
- this._document
- .documentData()
- .layerTextStyles()
- .setObjects(styles);
+ this._document.documentData().layerTextStyles().setObjects(styles);
return this;
}
@@ -70,10 +67,7 @@ class TextStyles {
invariant(doc, 'Please provide a sketch document reference');
- const sharedStyles = doc
- .documentData()
- .layerTextStyles()
- .objects();
+ const sharedStyles = doc.documentData().layerTextStyles().objects();
let foundStyle = undefined;
for (let i = 0; i < sharedStyles.length; i++) {
@@ -92,4 +86,4 @@ class TextStyles {
}
}
-export default TextStyles;
+export const sharedTextStyles = new TextStyles();
diff --git a/src/jsonUtils/nodeImpl/sharedTextStyles.ts b/src/utils/sharedTextStyles/index.ts
similarity index 82%
rename from src/jsonUtils/nodeImpl/sharedTextStyles.ts
rename to src/utils/sharedTextStyles/index.ts
index ef0abf5a..4db144c7 100644
--- a/src/jsonUtils/nodeImpl/sharedTextStyles.ts
+++ b/src/utils/sharedTextStyles/index.ts
@@ -1,6 +1,6 @@
import { FileFormat1 as FileFormat } from '@sketch-hq/sketch-file-format-ts';
import { SketchDocument, TextStyle } from '../../types';
-import { generateID } from '../models';
+import { generateID } from '../../jsonUtils/models';
class TextStyles {
setDocument(_doc?: SketchDocument) {
@@ -20,4 +20,4 @@ class TextStyles {
}
}
-export default TextStyles;
+export const sharedTextStyles = new TextStyles();
diff --git a/src/utils/sortObjectKeys.ts b/src/utils/sortObjectKeys.ts
index 3179db5d..a5e5d1a2 100644
--- a/src/utils/sortObjectKeys.ts
+++ b/src/utils/sortObjectKeys.ts
@@ -1,8 +1,6 @@
-const sortObjectKeys = (obj: T): T => {
+export const sortObjectKeys = (obj: T): T => {
const keys = Object.keys(obj).sort();
// @ts-ignore
const acc: T = {};
return keys.reduce((acc, key) => ({ ...acc, [key]: obj[key] }), acc);
};
-
-export default sortObjectKeys;
diff --git a/src/utils/zIndex.ts b/src/utils/zIndex.ts
index 3c59fba3..6f6ee70c 100644
--- a/src/utils/zIndex.ts
+++ b/src/utils/zIndex.ts
@@ -1,7 +1,7 @@
import { ReactTestRendererNode } from 'react-test-renderer';
// Sort z-index values lowest to highest
-const zIndex = (
+export const zIndex = (
nodes: (ReactTestRendererNode | string)[],
): ((ReactTestRendererNode & { oIndex: number }) | string)[] =>
nodes
@@ -29,5 +29,3 @@ const zIndex = (
: 0;
return aIndex - bIndex;
});
-
-export default zIndex;
diff --git a/tsconfig.json b/tsconfig.json
index d95c63e1..7a12bc88 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -1,6 +1,6 @@
{
"compilerOptions": {
- "target": "es5",
+ "target": "es2017",
"outDir": "lib",
"rootDir": "src",
"moduleResolution": "node",
@@ -11,18 +11,6 @@
"strict": true /* Enable all strict type-checking options. */,
- /* Additional Checks */
- "noUnusedLocals": true /* Report errors on unused locals. */,
- "noUnusedParameters": true /* Report errors on unused parameters. */,
- "noImplicitReturns": true /* Report error when not all code paths in function return a value. */,
- "noFallthroughCasesInSwitch": true /* Report errors for fallthrough cases in switch statement. */,
-
- /* Debugging Options */
- "traceResolution": false /* Report module resolution log messages. */,
- "listEmittedFiles": false /* Print names of generated files part of the compilation. */,
- "listFiles": false /* Print names of files part of the compilation. */,
- "pretty": true /* Stylize errors and messages using color and context. */,
-
"lib": ["es5", "dom"],
"types": ["jest", "node"],
"typeRoots": ["node_modules/@types", "src/types"],
diff --git a/tsconfig.module.json b/tsconfig.module.json
new file mode 100644
index 00000000..6159976f
--- /dev/null
+++ b/tsconfig.module.json
@@ -0,0 +1,9 @@
+{
+ "extends": "./tsconfig",
+ "compilerOptions": {
+ "target": "es5",
+ "outDir": "lib/module",
+ "module": "esnext"
+ },
+ "exclude": ["node_modules/**"]
+}