├── .gitignore
├── package.json
├── LICENSE
├── index.html
├── template.js
├── README.md
├── template.ts
└── tsconfig.json
/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules
2 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "template",
3 | "version": "1.0.0",
4 | "description": "Lightweight UI Framework",
5 | "main": "template.js",
6 | "scripts": {
7 | "build": "tsc"
8 | },
9 | "devDependencies": {
10 | "@types/node": "^20.5.4",
11 | "typescript": "^5.2.2"
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Copyright William Blankenship
2 |
3 | Redistribution and use in source and binary forms, with or without
4 | modification, are permitted provided that the following conditions are met:
5 |
6 | 1. Neither the name of the copyright holder nor the names of its
7 | contributors may be used to endorse or promote products derived from
8 | this software without specific prior written permission.
9 |
10 | THE SOFTWARE IS PROVIDED “AS IS” AND THE AUTHOR DISCLAIMS ALL
11 | WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
12 | OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE
13 | FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY
14 | DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
15 | AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
16 | OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 |
--------------------------------------------------------------------------------
/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
85 |
86 |
87 |
--------------------------------------------------------------------------------
/template.js:
--------------------------------------------------------------------------------
1 | class Template {
2 | constructor(element, style) {
3 | this.fragment = element;
4 | this.style = style;
5 | this.host = null;
6 | this.eventHandlers = {};
7 | this.elements = {};
8 | this.children = {};
9 | this.state = {};
10 | this.destroyed = false;
11 | }
12 | getElement(selector) {
13 | const element = this.elements[selector];
14 | if (element != undefined) {
15 | return element;
16 | }
17 | if (this.host == undefined || this.host.shadowRoot == undefined) {
18 | throw new Error("Template has not been mounted");
19 | }
20 | const result = this.host.shadowRoot.querySelector(selector);
21 | if (result == undefined) {
22 | throw new Error(`Element ${selector} not found`);
23 | }
24 | if (!(result instanceof HTMLElement)) {
25 | throw new Error(`${selector} did not return an HTMLElement`);
26 | }
27 | this.elements[selector] = result;
28 | return result;
29 | }
30 | setState(obj) {
31 | let changed = false;
32 | for (let key in obj) {
33 | if (this.state[key] !== obj[key]) {
34 | const value = obj[key];
35 | changed = true;
36 | if (value == undefined) {
37 | delete this.state[key];
38 | }
39 | else {
40 | this.state[key] = value;
41 | }
42 | }
43 | }
44 | if (changed) {
45 | this.emit("change", this.state);
46 | }
47 | return this;
48 | }
49 | removeChild(name) {
50 | const child = this.children[name];
51 | if (child == undefined) {
52 | return this;
53 | }
54 | child.unmount();
55 | delete this.children[name];
56 | return this;
57 | }
58 | addChild(selector, child) {
59 | if (this.children[selector] != undefined) {
60 | throw new Error("Child already mounted");
61 | }
62 | const element = this.getElement(selector);
63 | child.mount(element);
64 | this.children[selector] = child;
65 | return this;
66 | }
67 | addChildren(obj) {
68 | for (let query in obj) {
69 | const child = obj[query];
70 | if (child == undefined) {
71 | continue;
72 | }
73 | this.addChild(query, child);
74 | }
75 | return this;
76 | }
77 | getChild(query) {
78 | const child = this.children[query];
79 | if (child == undefined) {
80 | throw new Error(`Unknown child ${query}`);
81 | }
82 | return child;
83 | }
84 | mount(host) {
85 | if (this.host) {
86 | throw new Error("Already mounted");
87 | }
88 | this.host = host;
89 | this.host.innerText = "";
90 | if (!this.host.shadowRoot) {
91 | this.host.attachShadow({ mode: "open" });
92 | }
93 | if (!this.host.shadowRoot) {
94 | throw new Error("Failed to create shadow root");
95 | }
96 | this.host.shadowRoot.appendChild(this.style);
97 | this.host.shadowRoot.appendChild(this.fragment.content.cloneNode(true));
98 | return this;
99 | }
100 | unmount() {
101 | for (const query in this.children) {
102 | const child = this.children[query];
103 | if (child == undefined) {
104 | continue;
105 | }
106 | child.unmount();
107 | }
108 | if (this.host) {
109 | this.host.innerText = "";
110 | if (this.host.shadowRoot) {
111 | this.host.shadowRoot.innerHTML = "";
112 | }
113 | }
114 | this.host = null;
115 | this.eventHandlers = {};
116 | this.elements = {};
117 | this.children = {};
118 | this.state = {};
119 | this.destroyed = true;
120 | return;
121 | }
122 | on(event, handler) {
123 | const handlers = this.eventHandlers[event] || [];
124 | this.eventHandlers[event] = handlers;
125 | handlers.push(handler);
126 | return this;
127 | }
128 | emit(event, ...args) {
129 | const handlers = this.eventHandlers[event];
130 | if (handlers == undefined) {
131 | return this;
132 | }
133 | handlers.forEach((handler) => {
134 | handler(...args);
135 | });
136 | return this;
137 | }
138 | static createElement(html) {
139 | const template = document.createElement("template");
140 | template.innerHTML = html;
141 | return template;
142 | }
143 | static createStyle(css) {
144 | const style = document.createElement("style");
145 | style.textContent = css;
146 | return style;
147 | }
148 | }
149 | export default Template;
150 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Template
2 |
3 | Template is a simple JS framework for creating interactive applications.
4 |
5 | It focuses on using web-native patterns.
6 |
7 | Calling it a framework is a bit of an exaggeration, it's a single `class` that
8 | manages HTML ``s.
9 |
10 | The entire "framework" is here: [./template.ts](./template.ts)
11 |
12 | # Usage
13 |
14 | Your Hello World example:
15 |
16 | ```html
17 |
18 |
19 |
20 |
21 |
22 |
51 |
52 |
53 | ```
54 |
55 | # How it works
56 |
57 | Template uses HTML
58 | [``](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template)
59 | to create reusable components.
60 |
61 | We then "mount" a `` into an element on the page by creating a
62 | [shadow DOM](https://developer.mozilla.org/en-US/docs/Web/API/Web_components/Using_shadow_DOM).
63 |
64 | The shadow DOM encapsulates the reusable components making sure that the CSS and
65 | JS from one component can not interfere with another.
66 |
67 | Using `.addChild(selector: string, child: Template)` allows us to nest these
68 | components. The parent keeps track of all mounted children. When we unmount the
69 | parent, it will recursively unmount all children.
70 |
71 | We follow React's philosophy of state flowing down. Our components manage their
72 | own children, configuring the child's state. Children manage updating their own
73 | DOM to reflect changes in state.
74 |
75 | We also follow React's philosophy of state bubbling up. When a user interacts
76 | with a child node, the child node emits an event. The parent receives the event
77 | and decides what to do.
78 |
79 | State management, event propogation, etc. are still early and need more thought.
80 |
81 | # Build process
82 |
83 | You'll want to use a bundler like `vite`
84 |
85 | For example:
86 |
87 | `index.html`
88 |
89 | ```html
90 |
91 |
92 |
93 |
Create New Account
94 |
95 |
96 |
97 |
Pair Existing Account
98 |
99 |
100 | ```
101 |
102 | `index.css`
103 |
104 | ```css
105 | .WelcomeComponent {
106 | background-color: hsla(0, 0%, 100%, 1);
107 | border-radius: 5px;
108 | display: flex;
109 | flex-direction: row;
110 | }
111 | .button {
112 | padding: 1em;
113 | margin: 0.5em;
114 | cursor: pointer;
115 | background-color: inherit;
116 | transition: background-color linear 0.1s;
117 | border-radius: inherit;
118 | }
119 | .button:hover {
120 | background-color: hsla(0, 0%, 90%, 1);
121 | transition: background-color linear 0.1s;
122 | }
123 | ```
124 |
125 | `index.ts`
126 |
127 | ```typescript
128 | import Template from "template";
129 | import Feather from "feather-icons";
130 | import html from "./index.html?raw";
131 | import css from "./index.css?raw";
132 |
133 | const template = Template.createElement(html);
134 | const style = Template.createStyle(css);
135 |
136 | class Welcome extends Template {
137 | constructor() {
138 | super(template, style);
139 | }
140 | mount(host: HTMLElement) {
141 | super.mount(host);
142 | this.getElement(".new > .icon").innerHTML =
143 | Feather.icons["user-plus"].toSvg();
144 | this.getElement(".new").addEventListener("click", () => {
145 | this.emit("new");
146 | });
147 | this.getElement(".pair > .icon").innerHTML =
148 | Feather.icons["smartphone"].toSvg();
149 | this.getElement(".pair").addEventListener("click", () => {
150 | this.emit("pair");
151 | });
152 | return this;
153 | }
154 | }
155 |
156 | export default Welcome;
157 | ```
158 |
--------------------------------------------------------------------------------
/template.ts:
--------------------------------------------------------------------------------
1 | type EventHandlers = { [name: string]: Function[] };
2 | type State = { [name: string]: string | number | boolean };
3 | type Children = { [query: string]: Template };
4 |
5 | class Template {
6 | fragment: HTMLTemplateElement;
7 | style: HTMLStyleElement;
8 | eventHandlers: EventHandlers;
9 | elements: { [query: string]: HTMLElement };
10 | children: Children;
11 | state: { [name: string]: string | number | boolean };
12 | host: HTMLElement | null;
13 | destroyed: Boolean;
14 | constructor(element: HTMLTemplateElement, style: HTMLStyleElement) {
15 | this.fragment = element;
16 | this.style = style;
17 | this.host = null;
18 | this.eventHandlers = {};
19 | this.elements = {};
20 | this.children = {};
21 | this.state = {};
22 | this.destroyed = false;
23 | }
24 | getElement(selector: string): HTMLElement {
25 | const element = this.elements[selector];
26 | if (element != undefined) {
27 | return element;
28 | }
29 | if (this.host == undefined || this.host.shadowRoot == undefined) {
30 | throw new Error("Template has not been mounted");
31 | }
32 | const result = this.host.shadowRoot.querySelector(selector);
33 | if (result == undefined) {
34 | throw new Error(`Element ${selector} not found`);
35 | }
36 | if (!(result instanceof HTMLElement)) {
37 | throw new Error(`${selector} did not return an HTMLElement`);
38 | }
39 | this.elements[selector] = result;
40 | return result;
41 | }
42 | setState(obj: State) {
43 | let changed = false;
44 | for (let key in obj) {
45 | if (this.state[key] !== obj[key]) {
46 | const value = obj[key];
47 | changed = true;
48 | if (value == undefined) {
49 | delete this.state[key];
50 | } else {
51 | this.state[key] = value;
52 | }
53 | }
54 | }
55 | if (changed) {
56 | this.emit("change", this.state);
57 | }
58 | return this;
59 | }
60 | removeChild(name: string) {
61 | const child = this.children[name];
62 | if (child == undefined) {
63 | return this;
64 | }
65 | child.unmount();
66 | delete this.children[name];
67 | return this;
68 | }
69 | addChild(selector: string, child: Template): Template {
70 | if (this.children[selector] != undefined) {
71 | throw new Error("Child already mounted");
72 | }
73 | const element = this.getElement(selector);
74 | child.mount(element);
75 | this.children[selector] = child;
76 | return this;
77 | }
78 | addChildren(obj: Children): Template {
79 | for (let query in obj) {
80 | const child = obj[query];
81 | if (child == undefined) {
82 | continue;
83 | }
84 | this.addChild(query, child);
85 | }
86 | return this;
87 | }
88 | getChild(query: string): Template {
89 | const child = this.children[query];
90 | if (child == undefined) {
91 | throw new Error(`Unknown child ${query}`);
92 | }
93 | return child;
94 | }
95 | mount(host: HTMLElement): Template {
96 | if (this.host) {
97 | throw new Error("Already mounted");
98 | }
99 | this.host = host;
100 | this.host.innerText = "";
101 | if (!this.host.shadowRoot) {
102 | this.host.attachShadow({ mode: "open" });
103 | }
104 | if (!this.host.shadowRoot) {
105 | throw new Error("Failed to create shadow root");
106 | }
107 | this.host.shadowRoot.appendChild(this.style);
108 | this.host.shadowRoot.appendChild(this.fragment.content.cloneNode(true));
109 | return this;
110 | }
111 | unmount() {
112 | for (const query in this.children) {
113 | const child = this.children[query];
114 | if (child == undefined) {
115 | continue;
116 | }
117 | child.unmount();
118 | }
119 | if (this.host) {
120 | this.host.innerText = "";
121 | if (this.host.shadowRoot) {
122 | this.host.shadowRoot.innerHTML = "";
123 | }
124 | }
125 | this.host = null;
126 | this.eventHandlers = {};
127 | this.elements = {};
128 | this.children = {};
129 | this.state = {};
130 | this.destroyed = true;
131 | return;
132 | }
133 | on(event: string, handler: Function): Template {
134 | const handlers = this.eventHandlers[event] || [];
135 | this.eventHandlers[event] = handlers;
136 | handlers.push(handler);
137 | return this;
138 | }
139 | emit(event: string, ...args: any[]): Template {
140 | const handlers = this.eventHandlers[event];
141 | if (handlers == undefined) {
142 | return this;
143 | }
144 | handlers.forEach((handler) => {
145 | handler(...args);
146 | });
147 | return this;
148 | }
149 | static createElement(html: string): HTMLTemplateElement {
150 | const template = document.createElement("template");
151 | template.innerHTML = html;
152 | return template;
153 | }
154 | static createStyle(css: string): HTMLStyleElement {
155 | const style = document.createElement("style");
156 | style.textContent = css;
157 | return style;
158 | }
159 | }
160 |
161 | export default Template;
162 |
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | /* Visit https://aka.ms/tsconfig to read more about this file */
4 |
5 | /* Projects */
6 | // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
7 | // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
8 | // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
9 | // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
10 | // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
11 | // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
12 |
13 | /* Language and Environment */
14 | "target": "es6" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,
15 | // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
16 | // "jsx": "preserve", /* Specify what JSX code is generated. */
17 | // "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
18 | // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
19 | // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
20 | // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
21 | // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
22 | // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
23 | // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
24 | // "useDefineForClassFields": true /* Emit ECMAScript-standard-compliant class fields. */
25 | // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
26 |
27 | /* Modules */
28 | "module": "es6" /* Specify what module code is generated. */,
29 | // "rootDir": "./", /* Specify the root folder within your source files. */
30 | // "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */
31 | // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
32 | // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
33 | // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
34 | // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
35 | // "types": [], /* Specify type package names to be included without being referenced in a source file. */
36 | // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
37 | // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
38 | // "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
39 | // "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
40 | // "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
41 | // "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
42 | // "resolveJsonModule": true, /* Enable importing .json files. */
43 | // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
44 | // "noResolve": true, /* Disallow 'import's, 'require's or ''s from expanding the number of files TypeScript should add to a project. */
45 |
46 | /* JavaScript Support */
47 | // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
48 | // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
49 | // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
50 |
51 | /* Emit */
52 | // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
53 | // "declarationMap": true, /* Create sourcemaps for d.ts files. */
54 | // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
55 | // "sourceMap": true, /* Create source map files for emitted JavaScript files. */
56 | // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
57 | // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
58 | // "outDir": "./", /* Specify an output folder for all emitted files. */
59 | // "removeComments": true, /* Disable emitting comments. */
60 | // "noEmit": true, /* Disable emitting files from a compilation. */
61 | // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
62 | // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
63 | // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
64 | // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
65 | // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
66 | // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
67 | // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
68 | // "newLine": "crlf", /* Set the newline character for emitting files. */
69 | // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
70 | // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
71 | // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
72 | // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
73 | // "declarationDir": "./", /* Specify the output directory for generated declaration files. */
74 | // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
75 |
76 | /* Interop Constraints */
77 | // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
78 | // "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
79 | // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
80 | "esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */,
81 | // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
82 | "forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */,
83 |
84 | /* Type Checking */
85 | "strict": true /* Enable all strict type-checking options. */,
86 | "noImplicitAny": true /* Enable error reporting for expressions and declarations with an implied 'any' type. */,
87 | "strictNullChecks": true /* When type checking, take into account 'null' and 'undefined'. */,
88 | "strictFunctionTypes": true /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */,
89 | "strictBindCallApply": true /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */,
90 | "strictPropertyInitialization": true /* Check for class properties that are declared but not set in the constructor. */,
91 | "noImplicitThis": true /* Enable error reporting when 'this' is given the type 'any'. */,
92 | "useUnknownInCatchVariables": true /* Default catch clause variables as 'unknown' instead of 'any'. */,
93 | "alwaysStrict": true /* Ensure 'use strict' is always emitted. */,
94 | "noUnusedLocals": true /* Enable error reporting when local variables aren't read. */,
95 | "noUnusedParameters": true /* Raise an error when a function parameter isn't read. */,
96 | "exactOptionalPropertyTypes": true /* Interpret optional property types as written, rather than adding 'undefined'. */,
97 | "noImplicitReturns": true /* Enable error reporting for codepaths that do not explicitly return in a function. */,
98 | "noFallthroughCasesInSwitch": true /* Enable error reporting for fallthrough cases in switch statements. */,
99 | "noUncheckedIndexedAccess": true /* Add 'undefined' to a type when accessed using an index. */,
100 | "noImplicitOverride": true /* Ensure overriding members in derived classes are marked with an override modifier. */,
101 | "noPropertyAccessFromIndexSignature": true /* Enforces using indexed accessors for keys declared using an indexed type. */,
102 | "allowUnusedLabels": true /* Disable error reporting for unused labels. */,
103 | "allowUnreachableCode": true /* Disable error reporting for unreachable code. */,
104 |
105 | /* Completeness */
106 | "skipDefaultLibCheck": true /* Skip type checking .d.ts files that are included with TypeScript. */,
107 | "skipLibCheck": true /* Skip type checking all .d.ts files. */
108 | }
109 | }
110 |
--------------------------------------------------------------------------------