├── .npmignore
├── .gitignore
├── demo
├── index.html
└── index.js
├── package.json
├── LICENSE
├── src
├── components.js
└── view
│ ├── index.js
│ └── styleModifiers.js
└── README.md
/.npmignore:
--------------------------------------------------------------------------------
1 | /demo
2 | /src
3 | /dist
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | /.cache
2 | /.DS_Store
3 | /dist
4 | /node_modules
5 | /public
6 | /umd
--------------------------------------------------------------------------------
/demo/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | ScriptUI
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "script-ui",
3 | "version": "0.0.1-rc1",
4 | "description": "Write React without JSX",
5 | "main": "public/index.js",
6 | "umd:main": "public/index.umd.js",
7 | "module": "public/index.module.js",
8 | "source": "src/view/index.js",
9 | "scripts": {
10 | "test": "echo \"Error: no test specified\" && exit 1",
11 | "start": "parcel demo/index.html",
12 | "prepublishOnly": "microbundle --name=ScriptUI --globals react=React"
13 | },
14 | "files": [
15 | "public"
16 | ],
17 | "author": "Andrew Nater",
18 | "license": "MIT",
19 | "repository": {
20 | "type": "git",
21 | "url": "https://github.com/anater/ScriptUI.git"
22 | },
23 | "devDependencies": {
24 | "microbundle": "^0.11.0",
25 | "parcel-bundler": "^1.12.3",
26 | "react": "^16.8.6",
27 | "react-dom": "^16.8.6",
28 | "emotion": "^10.0.14"
29 | },
30 | "peerDependencies": {
31 | "react": "^16.8.6",
32 | "react-dom": "^16.8.6",
33 | "emotion": "^10.0.14"
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) Facebook, Inc. and its affiliates.
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/demo/index.js:
--------------------------------------------------------------------------------
1 | import React from "react";
2 | import ReactDOM from "react-dom";
3 | import View from "../src/view/index";
4 | import { Flex, Text, Spacer, Button, Link } from "../src/components";
5 |
6 | const Input = props => {
7 | const newInput = View("input", { ...props, type: "text" });
8 | return newInput();
9 | };
10 |
11 | const Checkbox = (onChange, id) => {
12 | const newCheckbox = View("input", { type: "checkbox", onChange, id });
13 | return newCheckbox();
14 | };
15 |
16 | const Tasks = (tasks, onChange) => {
17 | const taskViews = tasks.map((taskText, index) =>
18 | Flex("row", "center")(
19 | Checkbox(() => onChange(index), index)
20 | .margin({
21 | vertical: "1em",
22 | right: "2em"
23 | })
24 | .modify(element => element.css({ lineHeight: 2 })),
25 | Text(taskText, "label")
26 | .set({ htmlFor: index })
27 | .font({ size: "1.3rem", lineHeight: 1.5 })
28 | .frame({ width: "100%" })
29 | ).set({ key: index })
30 | );
31 | return Flex("column")(...taskViews).frame({
32 | width: "90%",
33 | maxWidth: "30rem"
34 | });
35 | };
36 |
37 | const Counter = () => {
38 | const { useState } = React;
39 | const [count, setCount] = useState(0);
40 |
41 | return Flex("column", "center")(
42 | Link(`Count ${count}`, "https://google.com")
43 | .color("orange")
44 | .set({ target: "_blank" })
45 | .decoration("none"),
46 | Spacer(),
47 | Button(`+ 1`, () => setCount(count + 1))
48 | .radius(10)
49 | .color("white")
50 | .font({ size: "1.2rem", weight: 900 })
51 | .border("1px solid orange")
52 | .background("linear-gradient(orange, orangered)")
53 | .padding({ vertical: 10, horizontal: 20 })
54 | .shadow("0px 0px 10px rgba(0,0,0,0.1)")
55 | ).padding(20);
56 | };
57 |
58 | const Title = text =>
59 | Text(text, "h1")
60 | .font({ size: "2rem" })
61 | .margin(0);
62 |
63 | const App = () => {
64 | const [tasks, setTasks] = React.useState(["one", "two", "three"]);
65 | const [checked, setChecked] = React.useState(new Set());
66 | const handleChange = React.useCallback(
67 | checkedIndex => {
68 | const newChecked = new Set(checked);
69 | if (checked.has(checkedIndex)) {
70 | newChecked.delete(checkedIndex);
71 | } else {
72 | newChecked.add(checkedIndex);
73 | }
74 | setChecked(newChecked);
75 | },
76 | [checked]
77 | );
78 |
79 | return Flex("column", "center")(
80 | Flex("row", "baseline")(Title("testing"), Counter()),
81 | Input({ onChange: e => setTasks(tasks.concat(e.target.value)) }),
82 | Flex("row", "center")(
83 | Title("Tasks"),
84 | Text(`(${checked.size}/${tasks.length})`).margin({ left: "0.5em" })
85 | ),
86 | Tasks(tasks, handleChange)
87 | ).font({ family: "sans-serif" });
88 | };
89 |
90 | window.onload = () => {
91 | const element = View.render(App);
92 | const root = document.querySelector("#root");
93 | ReactDOM.render(element, root);
94 | };
95 |
--------------------------------------------------------------------------------
/src/components.js:
--------------------------------------------------------------------------------
1 | import View from "./view";
2 |
3 | /*
4 | Elements
5 | */
6 |
7 | export function Text(textContent, tagName) {
8 | const textView = View(tagName || "span", { className: "text" }).addModifiers({
9 | // weight
10 |
11 | lighter() {
12 | return this.font({ weight: "lighter" });
13 | },
14 |
15 | bold() {
16 | return this.font({ weight: "bold" });
17 | },
18 |
19 | bolder() {
20 | return this.font({ weight: "bolder" });
21 | },
22 |
23 | // alignment
24 | align(value) {
25 | return this.css({ textAlign: value });
26 | },
27 |
28 | left() {
29 | return this.align("left");
30 | },
31 |
32 | center() {
33 | return this.align("center");
34 | },
35 |
36 | right() {
37 | return this.align("right");
38 | },
39 |
40 | // transform
41 | uppercase() {
42 | return this.css({ textTransform: "uppercase" });
43 | },
44 |
45 | lowercase() {
46 | return this.css({ textTransform: "lowercase" });
47 | },
48 |
49 | capitalize() {
50 | return this.css({ textTransform: "capitalize" });
51 | },
52 |
53 | // spacing
54 | letterSpacing(value) {
55 | return this.css({ letterSpacing: value });
56 | },
57 |
58 | wordSpacing(value) {
59 | return this.css({ wordSpacing: value });
60 | },
61 |
62 | // decoration
63 | decoration(value) {
64 | if (typeof value === "string") {
65 | return this.css({ textDecoration: value });
66 | } else if (typeof value === "object") {
67 | return this.css({
68 | textDecorationLine: value.line,
69 | textDecorationColor: value.color,
70 | textDecorationStyle: value.style
71 | });
72 | }
73 | },
74 |
75 | underline() {
76 | return this.decoration("underline");
77 | },
78 |
79 | linethrough() {
80 | return this.decoration("line-through");
81 | }
82 | });
83 |
84 | return textView(textContent);
85 | }
86 |
87 | export function Button(textContent, onClick) {
88 | return Text(textContent, "button").set({ onClick });
89 | }
90 |
91 | export function Link(textContent, href) {
92 | return Text(textContent, "a").set({ href });
93 | }
94 |
95 | export function Spacer(size = 1) {
96 | return View("span", { role: "presentation" })()
97 | .css({ flex: size })
98 | .frame({ minWidth: `${size}em`, minHeight: `${size}em` });
99 | }
100 |
101 | export function Flex(direction, align) {
102 | if (!direction) throw new Error("no direction provided to Stack");
103 |
104 | const shortcuts = {
105 | start: "flex-start",
106 | end: "flex-end",
107 | between: "space-between",
108 | around: "space-around",
109 | evenly: "space-evenly"
110 | };
111 |
112 | const flexView = View("div").addModifiers({
113 | flex(flexDirection, flexWrap) {
114 | return this.display("flex").css({ flexDirection, flexWrap });
115 | },
116 | align(itemsValue, contentValue) {
117 | return this.css({
118 | alignItems: shortcuts[itemsValue] || itemsValue,
119 | alignContent: shortcuts[contentValue] || contentValue
120 | });
121 | },
122 | justify(value) {
123 | return this.css({
124 | justifyContent: shortcuts[value] || value
125 | });
126 | }
127 | });
128 |
129 | return (...children) =>
130 | flexView(...children)
131 | .flex(direction)
132 | .align(align)
133 | .justify(align);
134 | }
135 |
--------------------------------------------------------------------------------
/src/view/index.js:
--------------------------------------------------------------------------------
1 | import React from "react";
2 | import { css } from "emotion";
3 |
4 | import styleModifiers from "./styleModifiers";
5 |
6 | /**
7 | * Uses `type` and `props` to produce a function which accepts `children`.
8 | * When the returned function is called, it produces an element object.
9 | */
10 | export function View(type = "div", props) {
11 | /**
12 | * Creates a new `element` object with `type`, `props`, `children`. `createElement.modifiers` is the object prototype
13 | */
14 | const createElement = function(...children) {
15 | let element = Object.create(createElement.modifiers);
16 | Object.assign(element, { type, props, children });
17 | return element;
18 | };
19 | /**
20 | * Contains any custom modifiers for this element. Prototype is `View.modifiers` to enable access to all base modifiers
21 | */
22 | createElement.modifiers = Object.create(View.modifiers);
23 | /**
24 | * Merges `newModifiers` object into `createElement.modifiers`
25 | * */
26 | createElement.addModifiers = function(newModifiers = {}) {
27 | Object.assign(createElement.modifiers, newModifiers);
28 | return createElement;
29 | };
30 |
31 | return createElement;
32 | }
33 |
34 | /**
35 | * An alias for the rendering function. Default is `React.createElement`
36 | */
37 | View.renderer = React.createElement;
38 |
39 | /**
40 | * Uses `element` to produce a valid element with `View.renderer`
41 | */
42 | View.render = function(element) {
43 | if (!element) {
44 | // falsy elements are treated as false
45 | return false;
46 | } else if (typeof element === "string") {
47 | // send back the string as is
48 | return element;
49 | } else if (typeof element === "function") {
50 | // Wrap function with function which produces the rendered element
51 | // This enables usage of React Hooks inside top level elements
52 | return View.renderer(() => View.render(element()));
53 | } else if (typeof element === "object") {
54 | const { type, props, children } = element;
55 | // if we have children, render them and return a rendered element with them
56 | if (children && children.length > 0) {
57 | const renderedChildren = children.map(View.render);
58 | return View.renderer(type, props, ...renderedChildren);
59 | }
60 | // otherwise, just render with type and props
61 | return View.renderer(type, props);
62 | } else {
63 | throw new Error(
64 | `Invalid element. Expected string, function or object. Received ${element}`
65 | );
66 | }
67 | };
68 |
69 | View.modifiers = {
70 | /**
71 | * Merges `newProps` into props
72 | */
73 | set(newProps) {
74 | this.props = Object.assign(this.props || {}, newProps);
75 | return this;
76 | },
77 |
78 | /**
79 | * Passes `element` object to `modifier` function and returns the result
80 | */
81 | modify(modifier) {
82 | return modifier(this);
83 | },
84 |
85 | /**
86 | * Merges `newStyles` into the style prop
87 | */
88 | style(newStyles) {
89 | this.props.style = Object.assign(this.props.style || {}, newStyles);
90 | return this;
91 | },
92 |
93 | /**
94 | * Combine values from `...classList` to replace the className prop
95 | */
96 | class(...classList) {
97 | if (this.props && this.props.className) {
98 | classList.push(this.props.className);
99 | }
100 | return this.set({ className: classnames(classList) });
101 | },
102 |
103 | css(newStyles) {
104 | return this.class(css(newStyles));
105 | },
106 |
107 | // spread styleModifiers into base modifiers
108 | ...styleModifiers,
109 | };
110 |
111 | /**
112 | * Merges `newModifiers` object into `View.modifiers`
113 | * */
114 | View.addModifiers = function(newModifiers = {}) {
115 | Object.assign(View.modifiers, newModifiers);
116 | return View;
117 | };
118 |
119 | // HELPERS
120 |
121 | function classnames(classList = []) {
122 | const filteredClassList = classList.filter(
123 | c => c !== false && typeof c === "string" && c.length > 0
124 | );
125 | if (filteredClassList.length > 0) {
126 | return filteredClassList.join(" ");
127 | }
128 | }
129 |
130 | export default View;
--------------------------------------------------------------------------------
/src/view/styleModifiers.js:
--------------------------------------------------------------------------------
1 | function badValue(value) {
2 | throw new TypeError(
3 | `Expected value to be a string, number, or object. Received: ${value}`
4 | );
5 | }
6 |
7 | export default {
8 | color(value) {
9 | return this.css({ color: value });
10 | },
11 |
12 | background(value) {
13 | if (typeof value === "string") {
14 | return this.css({ background: value });
15 | } else if (typeof value === "object") {
16 | return this.css({
17 | backgroundAttachment: value.attachment,
18 | backgroundClip: value.clip || value.box,
19 | backgroundOrigin: value.origin || value.box,
20 | backgroundColor: value.color,
21 | backgroundImage: value.image,
22 | backgroundPosition: value.position,
23 | backgroundRepeat: value.repeat,
24 | backgroundSize: value.size,
25 | });
26 | } else {
27 | badValue(value);
28 | }
29 | },
30 |
31 | font(value) {
32 | if (typeof value === "string") {
33 | return this.css({ font: value });
34 | } else if (typeof value === "object") {
35 | return this.css({
36 | fontSize: value.size,
37 | fontFamily: value.family,
38 | fontWeight: value.weight,
39 | fontStretch: value.stretch,
40 | lineHeight: value.lineHeight
41 | });
42 | } else {
43 | badValue(value);
44 | }
45 | },
46 |
47 | display(value) {
48 | return this.css({ display: value });
49 | },
50 |
51 | zIndex(value) {
52 | return this.css({ zIndex: value });
53 | },
54 |
55 | position(value, edges) {
56 | return this.css({
57 | position: value,
58 | top: edges.top || edges.vertical,
59 | bottom: edges.bottom || edges.vertical,
60 | left: edges.left || edges.horizontal,
61 | right: edges.right || edges.horizontal,
62 | });
63 | },
64 |
65 | frame(value) {
66 | if (typeof value === "string" || typeof value === "number") {
67 | return this.css({ width: value, height: value });
68 | } else if (typeof value === "object") {
69 | return this.css({
70 | width: value.width,
71 | height: value.height,
72 | minWidth: value.minWidth,
73 | minHeight: value.minHeight,
74 | maxWidth: value.maxWidth,
75 | maxHeight: value.maxHeight
76 | });
77 | } else {
78 | badValue(value);
79 | }
80 | },
81 |
82 | border(value) {
83 | if (typeof value === "string") {
84 | return this.css({ border: value });
85 | } else if (typeof value === "object") {
86 | return this.css({
87 | border: value.all,
88 | borderTop: value.top || value.vertical,
89 | borderBottom: value.bottom || value.vertical,
90 | borderLeft: value.left || value.horizontal,
91 | borderRight: value.right || value.horizontal,
92 | borderRadius: value.radius,
93 | });
94 | } else {
95 | badValue(value);
96 | }
97 | },
98 |
99 | radius(value) {
100 | return this.border({ radius: value });
101 | },
102 |
103 | margin(value) {
104 | if (typeof value === "string" || typeof value === "number") {
105 | return this.css({ margin: value });
106 | } else if (typeof value === "object") {
107 | return this.css({
108 | marginTop: value.top || value.vertical,
109 | marginBottom: value.bottom || value.vertical,
110 | marginLeft: value.left || value.horizontal,
111 | marginRight: value.right || value.horizontal
112 | });
113 | } else {
114 | badValue(value);
115 | }
116 | },
117 |
118 | padding(value) {
119 | if (typeof value === "string" || typeof value === "number") {
120 | return this.css({ padding: value });
121 | } else if (typeof value === "object") {
122 | return this.css({
123 | paddingTop: value.top || value.vertical,
124 | paddingBottom: value.bottom || value.vertical,
125 | paddingLeft: value.left || value.horizontal,
126 | paddingRight: value.right || value.horizontal
127 | });
128 | } else {
129 | badValue(value);
130 | }
131 | },
132 |
133 | shadow(value) {
134 | return this.css({ boxShadow: value });
135 | }
136 | };
137 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # ScriptUI
2 | ScriptUI lets you write React components without JSX. It's easy to read. No build or transpilation required.
3 |
4 | [Installation](#installation) | [Usage](#usage) | [API](#api) | [Motivation](#motivation)
5 |
6 | ```javascript
7 | const Hello = View("div")(
8 | Text("Hello World")
9 | .bold()
10 | .color("red"),
11 | Button("Alert", () => alert("ScriptUI Rocks!")
12 | );
13 | ```
14 |
15 | ## Installation
16 | ScriptUI has peer dependencies: React, ReactDOM, and Emotion.
17 | Browser:
18 | ```html
19 |
20 |
21 |
22 |
23 |
24 |
25 | ```
26 |
27 | Node:
28 | ```
29 | npm install --save script-ui react react-dom emotion
30 | ```
31 |
32 | ## Usage
33 | The following demonstrates how you render your `View` with `ReactDOM.render`.
34 |
35 | Browser (Try it in [CodePen](https://codepen.io/anater/pen/jgVZpR?editors=0011#0)):
36 | ```javascript
37 | // Assuming React & ReactDOM scripts are global.
38 | const { View } = ScriptUI;
39 | const MyView = View("span")("My View");
40 | ReactDOM.render(
41 | View.render(MyView),
42 | document.querySelector("#root")
43 | );
44 | ```
45 |
46 | Node:
47 | ```javascript
48 | import View from "scriptui";
49 | import ReactDOM from "react-dom";
50 |
51 | const MyView = View("span")("My View");
52 | ReactDOM.render(
53 | View.render(MyView),
54 | document.querySelector("#root")
55 | );
56 | ```
57 |
58 | ## API
59 | `View(type: string|element, props?: object) => (...children?) => view`
60 |
61 | `element: { type, props{}, children[], …View.modifiers }`
62 |
63 | This is the core of ScriptUI. `View` is a higher order function that accepts `type` and `props` and returns a function that accepts `children`. When the returned function is called, it returns an `element` object containing type, props, children, and modifiers. You can use modifiers to apply or manipulate props through method chaining:
64 | ```javascript
65 | const Button = (label, onClick) =>
66 | View("button")(label)
67 | .set({ onClick })
68 | .background("blue")
69 | .padding("1em 0.5em")
70 | .radius("0.25em");
71 | ```
72 |
73 | ### Methods and Properties
74 | - `View.renderer: React.createElement`
75 | - The renderer is used to determine how an `element` object should be interpreted. By default, `React.createElement` is used. You can use an alternative like [Preact](https://preactjs.com), [Hyperscript](https://github.com/hyperhype/hyperscript), or write your own!
76 | - `View.render(element: string|object|function) => View.renderer()`
77 | - The render method accepts `element` objects from `View` and returns the element returned from `View.renderer`. For falsy elements, `false` is returned. String elements are returned as is.
78 | - `View.modifiers: object`
79 | - The modifiers property contains core modifier methods that are available to any element returned from a `View`.
80 | - `View.addModifiers(newModifiers: object) => void`
81 | - This method allows you to pass an object of modifier methods that can apply custom modifications. These must be instantiated before using the new modifiers.
82 | - `newModifiers` must contain functions as values and each function must return the modified object. These should be declared as [methods](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions) for proper access to `this`.
83 |
84 | ### Modifiers
85 | Modifiers apply changes to the `element` object and return the modified object. There are a few modifiers that are included for convenience.
86 | - `set(newProps: object)`
87 | - merges `newProps` into the `props` object
88 | - `modify(modifier: (object) => modifiedObject)`
89 | - uses the provided `modifier` function to apply a modification. Use this for one time or private modifiers
90 | - `style(newStyles: object)`
91 | - merges in the `newStyles` object into the `props.style` object
92 | - `class(…classNames: string)`
93 | - applies strings from `classNames` to the `className` prop
94 | - `css(newCSS: object)`
95 | - applies `newCSS` to the element using [`emotion`](https://github.com/emotion-js/emotion/tree/master/packages/emotion) to generate styles and enable CSS features like child selectors, pseudo-elements, and media queries
96 |
97 | ## Motivation
98 | Today we can build web apps more quickly than ever. But somehow it’s never been harder to do it. To use JSX in your React app, you need node, npm, babel, and webpack. Beginners have to learn all of this just to get started. I think we can do better.
99 |
100 | So I wonder: Is JSX the best we can do? Can it be easier?
101 |
102 | JSX feels like HTML. So it’s easy to understand. And it has JavaScript super powers. In almost every way, it is better than templating languages. It’s much more legible than using `React.createElement` . It has a lot going for it.
103 |
104 | That said, I find [SwiftUI](https://developer.apple.com/tutorials/swiftui) is easier to read than JSX. It’s been designed for Swift. It leverages the power of the language. That makes it more expressive and flexible. It offers insight into how to improve JavaScript UI code.
105 |
106 | We don’t have all the same tricks in JavaScript, but we can get very close. So how can we get what’s good about SwiftUI _and_ JSX?
107 |
108 | That’s where ScriptUI comes in. The goal is to build a library that is easy to understand and get started with. Reading and writing components should feel intuitive. You shouldn’t need a terminal to start creating. It should feel effortless and encourage experimentation.
109 |
110 | If you’re a fellow SwiftUI fan or don’t love all the tooling needed to write JSX, please try it. If you really like it, please share your experience or contribute to the project. Thank you for giving it a chance.
--------------------------------------------------------------------------------