├── .yarnrc ├── src ├── d │ └── browser-env.ts ├── directive │ ├── index.ts │ ├── subscribe.ts │ ├── shadow.ts │ ├── shadow.test.ts │ └── subscribe.test.ts ├── lib │ ├── is-node-env.ts │ ├── define.ts │ ├── element.ts │ └── test.ts ├── index.test.ts └── index.ts ├── .prettierignore ├── renovate.json ├── .prettierrc.json ├── .editorconfig ├── tsconfig.json ├── .github └── workflows │ └── main.yml ├── .eslintrc.json ├── rollup.config.js ├── LICENSE ├── .gitignore ├── eslint.config.mjs ├── package.json ├── README.md └── CODE_OF_CONDUCT.md /.yarnrc: -------------------------------------------------------------------------------- 1 | network-timeout 60000 2 | -------------------------------------------------------------------------------- /src/d/browser-env.ts: -------------------------------------------------------------------------------- 1 | declare module 'browser-env' 2 | -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | **/*.js 3 | **/*.d.ts 4 | -------------------------------------------------------------------------------- /renovate.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": ["config:base"], 3 | "automerge": true 4 | } 5 | -------------------------------------------------------------------------------- /.prettierrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "semi": false, 3 | "singleQuote": true, 4 | "useTabs": true 5 | } 6 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | indent_style = tab 5 | end_of_line = lf 6 | charset = utf-8 7 | trim_trailing_whitespace = true 8 | insert_final_newline = true 9 | -------------------------------------------------------------------------------- /src/directive/index.ts: -------------------------------------------------------------------------------- 1 | import { type Part } from 'lit-html' 2 | import { shadow } from './shadow' 3 | import { subscribe } from './subscribe' 4 | 5 | export type DirectiveFunction = (part: Part) => void 6 | 7 | export { shadow, subscribe } 8 | -------------------------------------------------------------------------------- /src/lib/is-node-env.ts: -------------------------------------------------------------------------------- 1 | const result = 2 | typeof process !== 'undefined' && 3 | typeof process.release !== 'undefined' && 4 | typeof process.release.name !== 'undefined' && 5 | typeof global !== 'undefined' 6 | 7 | export const isNodeEnv = (): boolean => result 8 | -------------------------------------------------------------------------------- /src/lib/define.ts: -------------------------------------------------------------------------------- 1 | import { type UllrElement } from './element' 2 | import { when } from 'ramda' 3 | 4 | export const define = when( 5 | (el: typeof UllrElement) => 6 | typeof customElements !== 'undefined' && 7 | customElements.get(el.is) === undefined, 8 | (el) => { 9 | customElements.define(el.is, el) 10 | }, 11 | ) 12 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es2015", 4 | "lib": ["es2015", "es2016", "es2017", "dom"], 5 | "moduleResolution": "node", 6 | "allowSyntheticDefaultImports": true, 7 | "strictNullChecks": true, 8 | "declaration": true, 9 | "outDir": "dist", 10 | "rootDir": ".", 11 | "module": "esnext", 12 | "plugins": [ 13 | { 14 | "name": "typescript-lit-html-plugin" 15 | } 16 | ] 17 | }, 18 | "include": ["src/**/*", "eslint.config.mjs"], 19 | "exclude": [] 20 | } 21 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: [push] 4 | 5 | jobs: 6 | build: 7 | runs-on: ubuntu-latest 8 | 9 | strategy: 10 | matrix: 11 | node-version: [20.x] 12 | 13 | steps: 14 | - uses: actions/checkout@v1 15 | 16 | - name: Use Node.js ${{ matrix.node-version }} 17 | uses: actions/setup-node@v1 18 | with: 19 | node-version: ${{ matrix.node-version }} 20 | 21 | - name: install deps 22 | run: npm ci 23 | 24 | - name: lint 25 | run: npm run lint 26 | 27 | - name: test 28 | run: npm test 29 | -------------------------------------------------------------------------------- /src/lib/element.ts: -------------------------------------------------------------------------------- 1 | import { render as _render, type TemplateResult } from 'lit-html' 2 | 3 | export const render = (template: TemplateResult, el: HTMLElement): void => { 4 | _render( 5 | template, 6 | (() => { 7 | if (el.shadowRoot === undefined || el.shadowRoot === null) { 8 | return el.attachShadow({ mode: 'open' }) 9 | } 10 | 11 | return el.shadowRoot 12 | })(), 13 | ) 14 | } 15 | 16 | export class UllrElement extends HTMLElement { 17 | connected: boolean 18 | static get is(): string { 19 | return '' 20 | } 21 | 22 | connectedCallback(): void { 23 | this.connected = true 24 | } 25 | 26 | disconnectedCallback(): void { 27 | this.connected = false 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "env": { 3 | "browser": true, 4 | "mocha": true 5 | }, 6 | "parser": "@typescript-eslint/parser", 7 | "parserOptions": { 8 | "project": "./tsconfig.json", 9 | "tsconfigRootDir": "." 10 | }, 11 | "plugins": ["@typescript-eslint"], 12 | "extends": [ 13 | "eslint:recommended", 14 | "plugin:@typescript-eslint/eslint-recommended", 15 | "plugin:@typescript-eslint/recommended", 16 | "xo", 17 | "xo-typescript", 18 | "prettier" 19 | ], 20 | "overrides": [ 21 | { 22 | "files": ["**/*.ts"], 23 | "rules": { "@typescript-eslint/no-redeclare": "off" } 24 | }, 25 | { 26 | "files": ["**/*.test.ts"], 27 | "rules": { 28 | "@typescript-eslint/no-non-null-assertion": "off" 29 | } 30 | } 31 | ] 32 | } 33 | -------------------------------------------------------------------------------- /rollup.config.js: -------------------------------------------------------------------------------- 1 | import resolve from '@rollup/plugin-node-resolve' 2 | import commonjs from '@rollup/plugin-commonjs' 3 | import typescript from '@rollup/plugin-typescript' 4 | import multiEntry from '@rollup/plugin-multi-entry' 5 | import dts from 'rollup-plugin-dts' 6 | 7 | export default [ 8 | { 9 | input: ['src/**/*.test.ts'], 10 | output: { 11 | file: 'dist/test.js', 12 | format: 'umd' 13 | }, 14 | plugins: [ 15 | typescript(), 16 | commonjs({ 17 | include: 'node_modules/**' 18 | }), 19 | resolve(), 20 | multiEntry() 21 | ] 22 | }, 23 | { 24 | input: ['src/**/*.ts', '!**/*.test.ts'], 25 | output: [ 26 | { 27 | file: 'dist/index.mjs', 28 | format: 'es', 29 | }, 30 | { 31 | file: 'dist/index.js', 32 | format: 'cjs', 33 | }, 34 | ], 35 | plugins: [multiEntry(), typescript()], 36 | }, 37 | { 38 | input: ['dist/**/*.d.ts', '!**/*.test.d.ts', '!**/d/*'], 39 | output: [{ file: 'dist/ullr.d.ts', format: 'es' }], 40 | plugins: [multiEntry(), dts()], 41 | }, 42 | ] 43 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 aggre 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 | -------------------------------------------------------------------------------- /src/lib/test.ts: -------------------------------------------------------------------------------- 1 | // Tslint:disable:no-unnecessary-type-annotation 2 | export const sleep = async (time: number): Promise => 3 | new Promise( 4 | (resolve: (value?: void | PromiseLike | undefined) => void): void => { 5 | setTimeout(resolve, time) 6 | }, 7 | ) 8 | 9 | export const slotSelector = ( 10 | element: Element | undefined, 11 | slot: string, 12 | selector: string, 13 | ): Element | undefined => { 14 | if (element === null || element === undefined) { 15 | return 16 | } 17 | 18 | const { shadowRoot } = element 19 | const slotEl = (() => { 20 | if (shadowRoot !== undefined && shadowRoot !== null) { 21 | return shadowRoot 22 | } 23 | 24 | return element 25 | })().querySelector(slot) 26 | if (slotEl === null) { 27 | return 28 | } 29 | 30 | const [assigned] = (slotEl as HTMLSlotElement).assignedNodes() 31 | const { parentElement } = assigned 32 | if (parentElement === null) { 33 | return 34 | } 35 | 36 | return parentElement.querySelector(selector) ?? undefined 37 | } 38 | 39 | export const removeExtraString = (c: string): string => 40 | c.replace(/)[\w\W])*-->/g, '').trim() 41 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | 8 | # Runtime data 9 | pids 10 | *.pid 11 | *.seed 12 | *.pid.lock 13 | 14 | # Directory for instrumented libs generated by jscoverage/JSCover 15 | lib-cov 16 | 17 | # Coverage directory used by tools like istanbul 18 | coverage 19 | 20 | # nyc test coverage 21 | .nyc_output 22 | 23 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 24 | .grunt 25 | 26 | # Bower dependency directory (https://bower.io/) 27 | bower_components 28 | 29 | # node-waf configuration 30 | .lock-wscript 31 | 32 | # Compiled binary addons (https://nodejs.org/api/addons.html) 33 | build/Release 34 | 35 | # Dependency directories 36 | node_modules/ 37 | jspm_packages/ 38 | 39 | # TypeScript v1 declaration files 40 | typings/ 41 | 42 | # Optional npm cache directory 43 | .npm 44 | 45 | # Optional eslint cache 46 | .eslintcache 47 | 48 | # Optional REPL history 49 | .node_repl_history 50 | 51 | # Output of 'npm pack' 52 | *.tgz 53 | 54 | # Yarn Integrity file 55 | .yarn-integrity 56 | 57 | # dotenv environment variables file 58 | .env 59 | 60 | # next.js build output 61 | .next 62 | 63 | # vuepress build output 64 | .vuepress/dist 65 | 66 | # Serverless directories 67 | .serverless 68 | 69 | # tsc build output 70 | **/*.js 71 | **/*.d.ts 72 | 73 | # ignore config files 74 | !rollup.config.js 75 | 76 | # rollup build output 77 | dist 78 | -------------------------------------------------------------------------------- /src/directive/subscribe.ts: -------------------------------------------------------------------------------- 1 | import { type Observable, type Subscription } from 'rxjs' 2 | import { noChange } from 'lit' 3 | import { type DirectiveResult } from 'lit/directive.js' 4 | import { AsyncDirective, directive } from 'lit/async-directive.js' 5 | import { type Templatable } from '..' 6 | 7 | type TemplateCallback = (x: T) => Templatable 8 | 9 | class Subscribe extends AsyncDirective { 10 | observable: Observable | undefined 11 | subscription: Subscription | undefined 12 | template: TemplateCallback 13 | 14 | render( 15 | observable: Observable, 16 | template: TemplateCallback, 17 | defaultContent?: Templatable, 18 | ) { 19 | this.template = template 20 | if (this.observable !== observable) { 21 | this.subscription?.unsubscribe() 22 | this.observable = observable 23 | this.subscribe(observable) 24 | } 25 | 26 | if (defaultContent) { 27 | return defaultContent 28 | } 29 | 30 | return noChange 31 | } 32 | 33 | subscribe(observable: Observable) { 34 | this.subscription = observable.subscribe((x) => { 35 | this.setValue(this.template(x)) 36 | }) 37 | } 38 | 39 | disconnected() { 40 | this.subscription?.unsubscribe() 41 | } 42 | 43 | reconnected() { 44 | this.subscribe(this.observable!) 45 | } 46 | } 47 | 48 | export const subscribe = directive(Subscribe) as ( 49 | observable: Observable, 50 | template: TemplateCallback, 51 | defaultContent?: Templatable, 52 | ) => DirectiveResult 53 | -------------------------------------------------------------------------------- /eslint.config.mjs: -------------------------------------------------------------------------------- 1 | import typescriptEslint from '@typescript-eslint/eslint-plugin' 2 | import globals from 'globals' 3 | import tsParser from '@typescript-eslint/parser' 4 | import path from 'node:path' 5 | import { fileURLToPath } from 'node:url' 6 | import js from '@eslint/js' 7 | import { FlatCompat } from '@eslint/eslintrc' 8 | 9 | const __filename = fileURLToPath(import.meta.url) 10 | const __dirname = path.dirname(__filename) 11 | const compat = new FlatCompat({ 12 | baseDirectory: __dirname, 13 | recommendedConfig: js.configs.recommended, 14 | allConfig: js.configs.all, 15 | }) 16 | 17 | export default [ 18 | { 19 | ignores: ['**/node_modules/', '**/*.js', '**/*.d.ts'], 20 | }, 21 | ...compat.extends( 22 | 'eslint:recommended', 23 | 'plugin:@typescript-eslint/eslint-recommended', 24 | 'plugin:@typescript-eslint/recommended', 25 | 'prettier', 26 | ), 27 | { 28 | plugins: { 29 | '@typescript-eslint': typescriptEslint, 30 | }, 31 | 32 | languageOptions: { 33 | globals: { 34 | ...globals.browser, 35 | ...globals.mocha, 36 | }, 37 | 38 | parser: tsParser, 39 | ecmaVersion: 5, 40 | sourceType: 'script', 41 | 42 | parserOptions: { 43 | project: './tsconfig.json', 44 | tsconfigRootDir: '.', 45 | }, 46 | }, 47 | }, 48 | { 49 | files: ['**/*.ts'], 50 | 51 | rules: { 52 | '@typescript-eslint/no-redeclare': 'off', 53 | }, 54 | }, 55 | { 56 | files: ['**/*.test.ts'], 57 | 58 | rules: { 59 | '@typescript-eslint/no-non-null-assertion': 'off', 60 | }, 61 | }, 62 | ] 63 | -------------------------------------------------------------------------------- /src/directive/shadow.ts: -------------------------------------------------------------------------------- 1 | // Tslint:disable:no-unnecessary-type-annotation 2 | import { html } from 'lit' 3 | import { Directive, type PartInfo, directive } from 'lit/directive.js' 4 | import { render, UllrElement } from '../lib/element' 5 | import { define } from '../lib/define' 6 | import { isNodeEnv } from '../lib/is-node-env' 7 | import { type Templatable } from '..' 8 | 9 | define(class extends UllrElement { 10 | _template: Templatable | undefined 11 | static get is(): string { 12 | return 'ullr-shdw' 13 | } 14 | 15 | get template(): Templatable | undefined { 16 | return this._template 17 | } 18 | 19 | set template(tmp: Templatable | undefined) { 20 | this._template = tmp 21 | this._render() 22 | } 23 | 24 | connectedCallback(): void { 25 | super.connectedCallback() 26 | this._render() 27 | } 28 | 29 | disconnectedCallback(): void { 30 | super.disconnectedCallback() 31 | } 32 | 33 | private _render(): void { 34 | if (this.template === undefined) { 35 | return 36 | } 37 | 38 | render(html`${this.template}`, this) 39 | } 40 | }) 41 | 42 | const innerTemplate = isNodeEnv() 43 | ? (inner: Templatable) => html` ${inner} ` 44 | : (inner: Templatable) => html` ` 45 | 46 | class Shadow extends Directive { 47 | prev: Templatable | undefined 48 | 49 | constructor(partInfo: PartInfo) { 50 | super(partInfo) 51 | } 52 | 53 | render(inner: Templatable) { 54 | return innerTemplate(inner) 55 | } 56 | } 57 | 58 | export const shadow = directive(Shadow) 59 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@aggre/ullr", 3 | "version": "3.2.0", 4 | "description": "Functional Web Components", 5 | "type": "module", 6 | "main": "dist/index.mjs", 7 | "exports": { 8 | "import": "./dist/index.mjs", 9 | "require": "./dist/index.js", 10 | "types": "./dist/ullr.d.ts" 11 | }, 12 | "types": "dist/ullr.d.ts", 13 | "files": [ 14 | "dist/*.mjs", 15 | "dist/*.js", 16 | "dist/*.ts", 17 | "!**/*.test.*", 18 | "!**/test.js" 19 | ], 20 | "scripts": { 21 | "test": "wtr dist/test.js --node-resolve --puppeteer && mocha dist/test.js --require ./node_modules/browser-env/register.js", 22 | "pretest": "npm run build", 23 | "build": "npm run build:ts && npm run build:rollup", 24 | "build:ts": "tsc -p ./", 25 | "build:rollup": "rollup -c", 26 | "prebuild": "npm run lint && npm run clean", 27 | "clean": "rimraf dist", 28 | "lint": "npm run lint:eslint && npm run lint:format", 29 | "lint:eslint": "eslint ./src --fix", 30 | "lint:format": "prettier --write '**/*.{ts,json,md,yml}'", 31 | "prepack": "npm run build" 32 | }, 33 | "author": "aggre", 34 | "contributors": [ 35 | "aggre (https://github.com/aggre)" 36 | ], 37 | "license": "MIT", 38 | "dependencies": { 39 | "ramda": "^0.30.1", 40 | "type-fest": "^4.26.0" 41 | }, 42 | "peerDependencies": { 43 | "lit": "^2.0.0-rc.2 || ^3.0.0", 44 | "rxjs": "^6.6.3 || ^6.6.3 || ^6.6.3 || ^7.0.0" 45 | }, 46 | "devDependencies": { 47 | "@esm-bundle/chai": "4.3.4", 48 | "@rollup/plugin-commonjs": "28.0.2", 49 | "@rollup/plugin-multi-entry": "6.0.1", 50 | "@rollup/plugin-node-resolve": "16.0.0", 51 | "@rollup/plugin-typescript": "12.1.2", 52 | "@types/mocha": "10.0.10", 53 | "@types/node": "22.10.6", 54 | "@types/ramda": "0.30.2", 55 | "@typescript-eslint/eslint-plugin": "8.20.0", 56 | "@typescript-eslint/parser": "8.20.0", 57 | "@web/test-runner": "0.19.0", 58 | "@web/test-runner-puppeteer": "0.17.0", 59 | "browser-env": "3.3.0", 60 | "eslint": "9.18.0", 61 | "eslint-config-prettier": "10.0.1", 62 | "lit": "3.2.1", 63 | "mocha": "11.0.1", 64 | "prettier": "3.4.2", 65 | "rimraf": "6.0.1", 66 | "rollup": "4.30.1", 67 | "rollup-plugin-dts": "6.1.1", 68 | "rxjs": "7.8.1", 69 | "typescript": "5.5.4", 70 | "typescript-lit-html-plugin": "0.9.0" 71 | }, 72 | "repository": { 73 | "type": "git", 74 | "url": "git+https://github.com/aggre/ullr.git" 75 | }, 76 | "bugs": { 77 | "url": "https://github.com/aggre/ullr/issues" 78 | }, 79 | "homepage": "https://github.com/aggre/ullr#readme" 80 | } 81 | -------------------------------------------------------------------------------- /src/index.test.ts: -------------------------------------------------------------------------------- 1 | import { expect } from '@esm-bundle/chai' 2 | import { type AttributeValue, createCustomElements } from './index' 3 | import { html, render, type TemplateResult } from 'lit-html' 4 | import { isNodeEnv } from './lib/is-node-env' 5 | import { removeExtraString } from './lib/test' 6 | const { document } = window 7 | 8 | if (!isNodeEnv()) { 9 | // These specs is only supported on a browser. 10 | describe('Rendering', () => { 11 | afterEach(() => { 12 | render(html``, document.body) 13 | }) 14 | 15 | describe('Rendering html', () => { 16 | it('Rendering html', () => { 17 | const template = html`

The title

` 18 | render(template, document.body) 19 | const h1 = document.body.querySelector('h1') 20 | expect(h1).to.not.equal(null) 21 | expect(h1!.innerText).to.be.equal('The title') 22 | }) 23 | }) 24 | }) 25 | 26 | describe('Custom Elements', () => { 27 | it('Create Custom Elements', () => { 28 | const template = (): TemplateResult => html`
App
` 29 | const xApp = createCustomElements(template) 30 | window.customElements.define('x-app', xApp) 31 | render(html` `, document.body) 32 | const app = document.body.querySelector('x-app') 33 | expect(app).to.not.equal(null) 34 | expect(removeExtraString(app!.shadowRoot!.innerHTML)).to.be.equal( 35 | '
App
', 36 | ) 37 | }) 38 | describe('When the second argument is provided as an array', () => { 39 | it('Re-render when changing attribute values', () => { 40 | const template = ([message, description]: readonly [ 41 | AttributeValue, 42 | AttributeValue, 43 | ]): TemplateResult => html` 44 |

${message}

45 |

${description}

46 | ` 47 | const xApp = createCustomElements(template, ['message', 'description']) 48 | const select = (p: string, c: string): Element | undefined => 49 | document.body.querySelector(p)!.shadowRoot!.querySelector(c) ?? 50 | undefined 51 | window.customElements.define('x-app-2', xApp) 52 | render(html` `, document.body) 53 | const app = document.body.querySelector('x-app-2')! 54 | app.setAttribute('message', 'Test message') 55 | app.setAttribute('description', 'Test description') 56 | expect( 57 | (select('x-app-2', 'p') as HTMLParagraphElement).innerText, 58 | ).to.be.equal('Test message') 59 | expect( 60 | (select('x-app-2', 'p + p') as HTMLParagraphElement).innerText, 61 | ).to.be.equal('Test description') 62 | }) 63 | }) 64 | }) 65 | } 66 | -------------------------------------------------------------------------------- /src/directive/shadow.test.ts: -------------------------------------------------------------------------------- 1 | import { expect } from '@esm-bundle/chai' 2 | import { html, render, type TemplateResult } from 'lit-html' 3 | import { shadow } from '.' 4 | import { isNodeEnv } from '../lib/is-node-env' 5 | import { removeExtraString } from '../lib/test' 6 | import { BehaviorSubject } from 'rxjs' 7 | import { subscribe } from './subscribe' 8 | const { document } = window 9 | 10 | const contentInShadow = (selector: string): Element => 11 | isNodeEnv() 12 | ? document.body.querySelector(`ullr-shdw > ${selector}`)! 13 | : document.body 14 | .querySelector('ullr-shdw')! 15 | .shadowRoot!.querySelector(selector)! 16 | 17 | describe('shadow directive', () => { 18 | afterEach(() => { 19 | render(html``, document.body) 20 | }) 21 | 22 | it('Render to the ShadowRoot in "ullr-shdw" element', () => { 23 | const app = (content: string): TemplateResult => html` 24 | ${shadow(html`
${content}
`)} 25 | ` 26 | render(app('App'), document.body) 27 | const main = contentInShadow('main') 28 | expect(main).to.not.equal(null) 29 | expect(removeExtraString(main.innerHTML)).to.be.equal('App') 30 | }) 31 | 32 | it('Re-render if the template different from last time', () => { 33 | const subject = new BehaviorSubject(0) 34 | 35 | render( 36 | html` ${subscribe(subject, (x) => shadow(html`
${x}
`))} `, 37 | document.body, 38 | ) 39 | expect(removeExtraString(contentInShadow('main').innerHTML)).to.be.equal( 40 | '0', 41 | ) 42 | subject.next(1) 43 | expect(removeExtraString(contentInShadow('main').innerHTML)).to.be.equal( 44 | '1', 45 | ) 46 | subject.next(2) 47 | expect(removeExtraString(contentInShadow('main').innerHTML)).to.be.equal( 48 | '2', 49 | ) 50 | }) 51 | 52 | describe('Passing content', () => { 53 | it('Pass a TemplateResult', () => { 54 | render(html` ${shadow(html`

Test

`)} `, document.body) 55 | expect(removeExtraString(contentInShadow('p').innerHTML)).to.be.equal( 56 | 'Test', 57 | ) 58 | }) 59 | 60 | it('Pass a TemplateResult containing the shadow directive', () => { 61 | render( 62 | html` ${shadow(html` ${shadow(html`

Test

`)} `)} `, 63 | document.body, 64 | ) 65 | const el = isNodeEnv() 66 | ? document.body.querySelector('ullr-shdw > ullr-shdw > p')! 67 | : (document.body 68 | .querySelector('ullr-shdw')! 69 | .shadowRoot!.querySelector('ullr-shdw')! 70 | .shadowRoot!.querySelector('p') as HTMLElement) 71 | expect(removeExtraString(el.innerHTML)).to.be.equal('Test') 72 | }) 73 | 74 | it('Pass a TemplateResult containing the subscribe directive', () => { 75 | const subject = new BehaviorSubject(0) 76 | 77 | render( 78 | html` 79 | ${shadow(html` ${subscribe(subject, (x) => html`

${x}

`)} `)} 80 | `, 81 | document.body, 82 | ) 83 | expect(removeExtraString(contentInShadow('p').innerHTML)).to.be.equal('0') 84 | subject.next(1) 85 | expect(removeExtraString(contentInShadow('p').innerHTML)).to.be.equal('1') 86 | subject.next(2) 87 | expect(removeExtraString(contentInShadow('p').innerHTML)).to.be.equal('2') 88 | }) 89 | }) 90 | }) 91 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Functional Web Components 2 | 3 | **Building Web Components with Functional Programming.** 4 | 5 | ![CI](https://github.com/aggre/ullr/workflows/CI/badge.svg) 6 | [![Published on npm](https://img.shields.io/npm/v/@aggre/ullr.svg)](https://www.npmjs.com/package/@aggre/ullr) 7 | 8 | ``` 9 | 10 | ___ ___ 11 | /__/\ / /\ 12 | \ \:\ / /::\ 13 | \ \:\ ___ ___ ___ ___ / /:/\:\ 14 | ___ \ \:\ /__/\ / /\ /__/\ / /\ / /:/~/:/ 15 | /__/\ \__\:\ \ \:\ / /:/ \ \:\ / /:/ /__/:/ /:/___ 16 | \ \:\ / /:/ \ \:\ /:/ \ \:\ /:/ \ \:\/:::::/ 17 | \ \:\ /:/ \ \:\/:/ \ \:\/:/ \ \::/~~~~ 18 | \ \:\/:/ \ \::/ \ \::/ \ \:\ 19 | \ \::/ \__\/ \__\/ \ \:\ 20 | \__\/ \__\/ 21 | 22 | ``` 23 | 24 | --- 25 | 26 | # Installation 27 | 28 | Add to a lit project: 29 | 30 | ```bash 31 | npm i @aggre/ullr 32 | ``` 33 | 34 | When creating a new project using lit as template and RxJS as the state management: 35 | 36 | ```bash 37 | npm i @aggre/ullr lit rxjs 38 | ``` 39 | 40 | Partially supports run on Node.js (with jsdom). 41 | 42 | # APIs 43 | 44 | ## `shadow` 45 | 46 | `shadow` is a lit directive. 47 | 48 | Encapsulate the template with Shadow DOM. 49 | 50 | ```ts 51 | import { html } from 'lit' 52 | import { shadow } from '@aggre/ullr' 53 | 54 | export const main = (title: string, desc: string) => 55 | shadow(html` 56 | 61 |
62 |

${title}

63 |

${desc}

64 |
65 | `) 66 | ``` 67 | 68 | | Browser | Node.js | 69 | | ------- | --------------------------------------------------------------------------------------------------- | 70 | | ✅ | 🚸
Shadow Dom isn't supported. An inside content of Shadow Dom is shown as just an innerHTML. | 71 | 72 | --- 73 | 74 | ## `subscribe` 75 | 76 | `subscribe` is a lit directive. 77 | 78 | Subscribe to `Observable` of RxJS and re-rendering with the passed callback function. 79 | 80 | When the directive part is removed or the passed observable is changed, the unused subscription will automatically `unsubscribe`. 81 | 82 | ```ts 83 | import { html } from 'lit' 84 | import { subscribe } from '@aggre/ullr' 85 | import { timer as _timer } from 'rxjs' 86 | 87 | export const timer = (initialDelay: number, period: number) => 88 | subscribe( 89 | _timer(initialDelay, period), 90 | (x) => html`

${x}

`, 91 | html`

Default content

`, 92 | ) 93 | ``` 94 | 95 | | Browser | Node.js | 96 | | ------- | ------- | 97 | | ✅ | ✅ | 98 | 99 | --- 100 | 101 | ## `createCustomElements` 102 | 103 | `createCustomElements` creates a class that can be passed to `customElements.define`. 104 | 105 | ```ts 106 | import { createCustomElements } from '@aggre/ullr' 107 | import { main } from './main' 108 | 109 | const observedAttributes = ['title', 'desc'] 110 | 111 | const template = ([title, desc]) => main(title, desc) 112 | 113 | window.customElements.define( 114 | 'x-app', 115 | createCustomElements(template, observedAttributes), 116 | ) 117 | ``` 118 | 119 | | Browser | Node.js | 120 | | ------- | ------- | 121 | | ✅ | ❌ | 122 | 123 | --- 124 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import { type TemplateResult } from 'lit' 2 | import { type DirectiveResult } from 'lit/directive' 3 | import { render, UllrElement } from './lib/element' 4 | import type { FixedLengthArray, ReadonlyTuple } from 'type-fest' 5 | 6 | export type AttributeValue = string | undefined 7 | export type Templatable = TemplateResult | DirectiveResult 8 | 9 | export function createCustomElements>( 10 | template: (props: Props) => TemplateResult, 11 | ): typeof UllrElement 12 | 13 | export function createCustomElements< 14 | Props extends ReadonlyTuple, 15 | Attrs extends FixedLengthArray, 16 | >( 17 | template: (props: Props) => TemplateResult, 18 | observedAttributes: Attrs, 19 | ): typeof UllrElement 20 | 21 | export function createCustomElements< 22 | Props extends ReadonlyTuple, 23 | Attrs extends FixedLengthArray, 24 | >( 25 | template: (props: Props) => TemplateResult, 26 | observedAttributes: Attrs, 27 | ): typeof UllrElement 28 | 29 | export function createCustomElements< 30 | Props extends ReadonlyTuple, 31 | Attrs extends FixedLengthArray, 32 | >( 33 | template: (props: Props) => TemplateResult, 34 | observedAttributes: Attrs, 35 | ): typeof UllrElement 36 | 37 | export function createCustomElements< 38 | Props extends ReadonlyTuple, 39 | Attrs extends FixedLengthArray, 40 | >( 41 | template: (props: Props) => TemplateResult, 42 | observedAttributes: Attrs, 43 | ): typeof UllrElement 44 | 45 | export function createCustomElements< 46 | Props extends ReadonlyTuple, 47 | Attrs extends FixedLengthArray, 48 | >( 49 | template: (props: Props) => TemplateResult, 50 | observedAttributes: Attrs, 51 | ): typeof UllrElement 52 | 53 | export function createCustomElements< 54 | Props extends ReadonlyTuple, 55 | Attrs extends FixedLengthArray, 56 | >( 57 | template: (props: Props) => TemplateResult, 58 | observedAttributes: Attrs, 59 | ): typeof UllrElement 60 | 61 | export function createCustomElements< 62 | Props extends ReadonlyTuple, 63 | Attrs extends FixedLengthArray, 64 | >( 65 | template: (props: Props) => TemplateResult, 66 | observedAttributes: Attrs, 67 | ): typeof UllrElement 68 | 69 | export function createCustomElements< 70 | Props extends ReadonlyTuple, 71 | Attrs extends FixedLengthArray, 72 | >( 73 | template: (props: Props) => TemplateResult, 74 | observedAttributes: Attrs, 75 | ): typeof UllrElement 76 | 77 | export function createCustomElements< 78 | Props extends ReadonlyTuple, 79 | Attrs extends FixedLengthArray, 80 | >( 81 | template: (props: Props) => TemplateResult, 82 | observedAttributes: Attrs, 83 | ): typeof UllrElement 84 | 85 | export function createCustomElements< 86 | Props extends ReadonlyTuple, 87 | Attrs extends FixedLengthArray, 88 | >( 89 | template: (props: Props) => TemplateResult, 90 | observedAttributes: Attrs, 91 | ): typeof UllrElement 92 | 93 | export function createCustomElements< 94 | Props extends ReadonlyTuple, 95 | Attrs extends FixedLengthArray, 96 | >( 97 | template: (props: Props) => TemplateResult, 98 | observedAttributes: Attrs, 99 | ): typeof UllrElement 100 | 101 | export function createCustomElements< 102 | Props extends ReadonlyTuple, 103 | Attrs extends FixedLengthArray, 104 | >( 105 | template: (props: Props) => TemplateResult, 106 | observedAttributes: Attrs, 107 | ): typeof UllrElement 108 | 109 | export function createCustomElements( 110 | template: (props: unknown) => TemplateResult, 111 | observedAttributes: [undefined] = [undefined], 112 | ): unknown { 113 | return class extends UllrElement { 114 | private _props: AttributeValue[] 115 | constructor() { 116 | super() 117 | this._props = [] 118 | } 119 | 120 | static get observedAttributes(): typeof observedAttributes { 121 | return [...observedAttributes] 122 | } 123 | 124 | attributeChangedCallback( 125 | name: string, 126 | _: string | null, 127 | next: string | null, 128 | ): void { 129 | const index = observedAttributes?.findIndex((n) => n === name) 130 | if (index !== undefined) { 131 | this._props = [...this._props] 132 | this._props[index] = next ?? undefined 133 | } 134 | 135 | if (this.connected) { 136 | this._render() 137 | } 138 | } 139 | 140 | connectedCallback(): void { 141 | super.connectedCallback() 142 | this._render() 143 | } 144 | 145 | _render(): void { 146 | render(template([...this._props]), this) 147 | } 148 | } 149 | } 150 | -------------------------------------------------------------------------------- /src/directive/subscribe.test.ts: -------------------------------------------------------------------------------- 1 | import { expect } from '@esm-bundle/chai' 2 | import { timer as _timer, BehaviorSubject } from 'rxjs' 3 | import { take, filter } from 'rxjs/operators' 4 | import { html, render } from 'lit-html' 5 | import { sleep, removeExtraString } from '../lib/test' 6 | import { subscribe } from '.' 7 | import { isNodeEnv } from '../lib/is-node-env' 8 | import { shadow } from './shadow' 9 | const { document } = window 10 | 11 | const count = new BehaviorSubject(0) 12 | 13 | describe('subscribe directive', () => { 14 | afterEach(() => { 15 | render(html``, document.body) 16 | }) 17 | 18 | it('Subscribe to observable', async () => { 19 | const timer = _timer(10, 1).pipe( 20 | filter((x) => x > 0), 21 | take(10), 22 | ) 23 | let _count = 0 24 | render( 25 | html` 26 | ${subscribe(timer, (x) => { 27 | _count += 1 28 | return html`

${x}

` 29 | })} 30 | `, 31 | document.body, 32 | ) 33 | await sleep(100) 34 | const p = document.body.querySelector('body > p')! 35 | expect(removeExtraString(p.innerHTML)).to.be.equal('10') 36 | expect(_count).to.be.equal(10) 37 | }) 38 | 39 | it('When the third argument is provided, its value is rendered as initial content', async () => { 40 | const timer = _timer(50, 1).pipe( 41 | filter((x) => x > 0), 42 | take(1), 43 | ) 44 | render( 45 | html` 46 | ${subscribe( 47 | timer, 48 | (x) => html`

${x}

`, 49 | html`

placeholder

`, 50 | )} 51 | `, 52 | document.body, 53 | ) 54 | const el = (): Element => document.body.querySelector('body > p')! 55 | expect(el().innerHTML).to.be.equal('placeholder') 56 | await sleep(100) 57 | expect(removeExtraString(el().innerHTML)).to.be.equal('1') 58 | }) 59 | 60 | it('When removed the node, unsubscribe the subscription', async () => { 61 | const timer = _timer(0, 10).pipe( 62 | filter((x) => x > 0), 63 | take(1000), 64 | ) 65 | let _count = 0 66 | render( 67 | html` 68 | ${subscribe(timer, (x) => { 69 | _count += 1 70 | return html`

${x}

` 71 | })} 72 | `, 73 | document.body, 74 | ) 75 | await sleep(20) 76 | const p = document.body.querySelector('p')! 77 | expect(removeExtraString(p.innerHTML)).to.be.equal('1') 78 | expect(_count).to.be.equal(1) 79 | render(html``, document.body) 80 | await sleep(100) 81 | expect(_count).to.be.equal(1) 82 | }) 83 | 84 | it('When changed the observable, unsubscribe the old subscription', async () => { 85 | const o1 = new BehaviorSubject(0) 86 | const o2 = new BehaviorSubject('x') 87 | const ob = new BehaviorSubject>(o1) 88 | let _x = 0 89 | render( 90 | html` 91 | ${subscribe(ob, (x) => 92 | subscribe(x, (value) => { 93 | if (typeof value === 'number') { 94 | _x = value 95 | } 96 | 97 | return html`

${value}

` 98 | }), 99 | )} 100 | `, 101 | document.body, 102 | ) 103 | o1.next(123) 104 | const p1 = document.body.querySelector('p')! 105 | expect(removeExtraString(p1.innerHTML)).to.be.equal('123') 106 | expect(_x).to.be.equal(123) 107 | 108 | // Change the observable 109 | ob.next(o2) 110 | 111 | o2.next('y') 112 | o1.next(456) 113 | const p2 = document.body.querySelector('p')! 114 | expect(removeExtraString(p2.innerHTML)).to.be.equal('y') 115 | 116 | // The old subscription is unsubscribed 117 | expect(_x).to.be.equal(123) 118 | }) 119 | 120 | describe('Passing content', () => { 121 | it('Pass a TemplateResult', () => { 122 | count.next(1) 123 | render( 124 | html` ${subscribe(count, (x) => html`

${x}

`)} `, 125 | document.body, 126 | ) 127 | const el = document.body.querySelector('p')! 128 | expect(removeExtraString(el.innerHTML)).to.be.equal('1') 129 | }) 130 | 131 | it('Pass a TemplateResult containing the subscribe directive', async () => { 132 | const subject = new BehaviorSubject(0) 133 | 134 | count.next(4) 135 | render( 136 | html` 137 | ${subscribe( 138 | count, 139 | (x) => html` 140 |

${subscribe(subject, (y) => html` ${x + y} `)}

141 | `, 142 | )} 143 | `, 144 | document.body, 145 | ) 146 | const el = (): Element => document.body.querySelector('p > span')! 147 | expect(removeExtraString(el().innerHTML)).to.be.equal('4') 148 | subject.next(1) 149 | expect(removeExtraString(el().innerHTML)).to.be.equal('5') 150 | subject.next(2) 151 | expect(removeExtraString(el().innerHTML)).to.be.equal('6') 152 | }) 153 | 154 | it('Pass a TemplateResult containing the component directive', () => { 155 | count.next(5) 156 | render( 157 | html` 158 | ${subscribe(count, (x) => html` ${shadow(html`

${x}

`)} `)} 159 | `, 160 | document.body, 161 | ) 162 | const el = isNodeEnv() 163 | ? document.body.querySelector('ullr-shdw > p')! 164 | : (document.body 165 | .querySelector('ullr-shdw')! 166 | .shadowRoot!.querySelector('p') as HTMLElement) 167 | expect(removeExtraString(el.innerHTML)).to.be.equal('5') 168 | }) 169 | }) 170 | }) 171 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | We as members, contributors, and leaders pledge to make participation in our 6 | community a harassment-free experience for everyone, regardless of age, body 7 | size, visible or invisible disability, ethnicity, sex characteristics, gender 8 | identity and expression, level of experience, education, socio-economic status, 9 | nationality, personal appearance, race, caste, color, religion, or sexual 10 | identity and orientation. 11 | 12 | We pledge to act and interact in ways that contribute to an open, welcoming, 13 | diverse, inclusive, and healthy community. 14 | 15 | ## Our Standards 16 | 17 | Examples of behavior that contributes to a positive environment for our 18 | community include: 19 | 20 | - Demonstrating empathy and kindness toward other people 21 | - Being respectful of differing opinions, viewpoints, and experiences 22 | - Giving and gracefully accepting constructive feedback 23 | - Accepting responsibility and apologizing to those affected by our mistakes, 24 | and learning from the experience 25 | - Focusing on what is best not just for us as individuals, but for the overall 26 | community 27 | 28 | Examples of unacceptable behavior include: 29 | 30 | - The use of sexualized language or imagery, and sexual attention or advances of 31 | any kind 32 | - Trolling, insulting or derogatory comments, and personal or political attacks 33 | - Public or private harassment 34 | - Publishing others' private information, such as a physical or email address, 35 | without their explicit permission 36 | - Other conduct which could reasonably be considered inappropriate in a 37 | professional setting 38 | 39 | ## Enforcement Responsibilities 40 | 41 | Community leaders are responsible for clarifying and enforcing our standards of 42 | acceptable behavior and will take appropriate and fair corrective action in 43 | response to any behavior that they deem inappropriate, threatening, offensive, 44 | or harmful. 45 | 46 | Community leaders have the right and responsibility to remove, edit, or reject 47 | comments, commits, code, wiki edits, issues, and other contributions that are 48 | not aligned to this Code of Conduct, and will communicate reasons for moderation 49 | decisions when appropriate. 50 | 51 | ## Scope 52 | 53 | This Code of Conduct applies within all community spaces, and also applies when 54 | an individual is officially representing the community in public spaces. 55 | Examples of representing our community include using an official e-mail address, 56 | posting via an official social media account, or acting as an appointed 57 | representative at an online or offline event. 58 | 59 | ## Enforcement 60 | 61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 62 | reported to the community leaders responsible for enforcement at 63 | hiroyuki.aggre@gmail.com. 64 | All complaints will be reviewed and investigated promptly and fairly. 65 | 66 | All community leaders are obligated to respect the privacy and security of the 67 | reporter of any incident. 68 | 69 | ## Enforcement Guidelines 70 | 71 | Community leaders will follow these Community Impact Guidelines in determining 72 | the consequences for any action they deem in violation of this Code of Conduct: 73 | 74 | ### 1. Correction 75 | 76 | **Community Impact**: Use of inappropriate language or other behavior deemed 77 | unprofessional or unwelcome in the community. 78 | 79 | **Consequence**: A private, written warning from community leaders, providing 80 | clarity around the nature of the violation and an explanation of why the 81 | behavior was inappropriate. A public apology may be requested. 82 | 83 | ### 2. Warning 84 | 85 | **Community Impact**: A violation through a single incident or series of 86 | actions. 87 | 88 | **Consequence**: A warning with consequences for continued behavior. No 89 | interaction with the people involved, including unsolicited interaction with 90 | those enforcing the Code of Conduct, for a specified period of time. This 91 | includes avoiding interactions in community spaces as well as external channels 92 | like social media. Violating these terms may lead to a temporary or permanent 93 | ban. 94 | 95 | ### 3. Temporary Ban 96 | 97 | **Community Impact**: A serious violation of community standards, including 98 | sustained inappropriate behavior. 99 | 100 | **Consequence**: A temporary ban from any sort of interaction or public 101 | communication with the community for a specified period of time. No public or 102 | private interaction with the people involved, including unsolicited interaction 103 | with those enforcing the Code of Conduct, is allowed during this period. 104 | Violating these terms may lead to a permanent ban. 105 | 106 | ### 4. Permanent Ban 107 | 108 | **Community Impact**: Demonstrating a pattern of violation of community 109 | standards, including sustained inappropriate behavior, harassment of an 110 | individual, or aggression toward or disparagement of classes of individuals. 111 | 112 | **Consequence**: A permanent ban from any sort of public interaction within the 113 | community. 114 | 115 | ## Attribution 116 | 117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 118 | version 2.1, available at 119 | [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1]. 120 | 121 | Community Impact Guidelines were inspired by 122 | [Mozilla's code of conduct enforcement ladder][mozilla coc]. 123 | 124 | For answers to common questions about this code of conduct, see the FAQ at 125 | [https://www.contributor-covenant.org/faq][faq]. Translations are available at 126 | [https://www.contributor-covenant.org/translations][translations]. 127 | 128 | [homepage]: https://www.contributor-covenant.org 129 | [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html 130 | [mozilla coc]: https://github.com/mozilla/diversity 131 | [faq]: https://www.contributor-covenant.org/faq 132 | [translations]: https://www.contributor-covenant.org/translations 133 | --------------------------------------------------------------------------------