Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions docs-site/design/topBar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,14 @@ const topBarTemplate = html`<input
rel="noopener"
><Icon name="tabler:brand-github"
/></a>
<a class="topbar__icon" href="https://purestack.studio" target="_blank" rel="noopener" aria-label="PureStack Studio website">
<Icon name="tabler:stack-2"/>
<a
class="topbar__icon"
href="https://purestack.studio"
target="_blank"
rel="noopener"
aria-label="PureStack Studio website"
>
<Icon name="tabler:stack-2" />
</a>
</slot>
<SignIn
Expand Down
8 changes: 6 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "regor",
"version": "1.7.4",
"version": "1.7.5",
"description": "A reactive UI library for TypeScript and JavaScript. Connect state to HTML and SVG with direct DOM updates.",
"author": "Ahmed Yasin Koculu",
"license": "MIT",
Expand All @@ -26,7 +26,11 @@
"files": [
"dist"
],
"sideEffects": false,
"sideEffects": [
"./src/index.ts",
"./src/runtime.ts",
"./dist/*.js"
],
"repository": {
"type": "git",
"url": "git+https://github.com/PureStackStudio/Regor.git"
Expand Down
4 changes: 3 additions & 1 deletion src/app/createApp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,8 @@ export const createApp = <
prepareContext(element, config)
cleanRoot()
appendChildren(element.childNodes)
} else {
prepareContext(root, config)
}

if (config.useInterpolation) interpolate(root, config)
Expand Down Expand Up @@ -139,6 +141,6 @@ class RegorApp {
}

__bind(): void {
this.__binder.__bindDefault(this.__root)
this.__binder.__dynamicBinder.__bindRoot(this.__root)
}
}
4 changes: 4 additions & 0 deletions src/app/prepareContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ export const prepareContext = (
const root = isTemplate(template) ? template.content : template
const selector = `${toSelector(names.context)},${toSelector(names.contextAlias)},template`
for (const element of root.querySelectorAll?.(selector) ?? []) {
let ancestor: Element | null = element
while (ancestor && !ancestor.hasAttribute(names.pre))
ancestor = ancestor.parentElement
if (ancestor) continue
if (isTemplate(element)) {
prepareContext(element.content, config)
if (
Expand Down
2 changes: 2 additions & 0 deletions src/bind/ComponentBinder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -508,6 +508,7 @@ export class ComponentBinder {
const stack = this.__getChildElements(root).reverse()
while (stack.length > 0) {
const current = stack.pop() as HTMLElement
if (current.hasAttribute(this.__binder.__pre)) continue
if (current.matches(selector)) {
result.push(current)
continue
Expand All @@ -527,6 +528,7 @@ export class ComponentBinder {
const stack = this.__getChildElements(root).reverse()
while (stack.length > 0) {
const current = stack.pop() as HTMLElement
if (current.hasAttribute(binder.__pre)) continue
action(current)
if (!isNullOrWhitespace(selector) && current.matches(selector)) continue
if (current.hasAttribute(isName) || current.hasAttribute('is')) continue
Expand Down
64 changes: 49 additions & 15 deletions src/bind/DynamicBinder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,10 @@ import { setSwitchOwner } from './switch'
const noopStopObserving: StopObserving = () => {}

const mount = (nodes: ChildNode[], parent: Element): void => {
const target = isTemplate(parent) ? parent.content : parent
for (const x of nodes) {
const node = x.cloneNode(true)
parent.appendChild(node)
target.appendChild(node)
}
}

Expand All @@ -29,6 +30,50 @@ export class DynamicBinder {
this.__is = binder.__config.__builtInNames.is
}

__isContextHost(element: Element): boolean {
return (
element.hasAttribute('_rcontext') &&
!this.__binder.__componentBinder.__isComponentHost(element)
)
}

__readContext(element: Element): unknown {
const names = this.__binder.__config.__builtInNames
const expression =
element.getAttribute(names.context) ??
element.getAttribute(names.contextAlias)
const context =
expression === null
? undefined
: this.__binder.__parser
.__parse(expression, undefined, undefined, true, true)
.value()[0]
element.removeAttribute(names.context)
element.removeAttribute(names.contextAlias)
element.removeAttribute('_rcontext')
return context
}

__bindRoot(element: Element): void {
const binder = this.__binder
const names = binder.__config.__builtInNames
if (
element.hasAttribute(binder.__pre) ||
element.hasAttribute(this.__is) ||
element.hasAttribute('is') ||
(!element.hasAttribute(names.context) &&
!element.hasAttribute(names.contextAlias)) ||
binder.__componentBinder.__isComponentHost(element)
) {
binder.__bindDefault(element)
return
}
const context = this.__readContext(element)
// This parser belongs to the app, so the root scope is its base context.
if (isObject(context)) binder.__parser.__push(context)
binder.__bindDefault(element)
}

__bindAll(element: Element): boolean {
const isComponentElement = element.hasAttribute(this.__is)
if (isComponentElement || element.hasAttribute('is'))
Expand Down Expand Up @@ -129,20 +174,9 @@ export class DynamicBinder {
const value = parseResult.value
const parser = this.__binder.__parser
const capturedContext = parser.__capture()
const names = this.__binder.__config.__builtInNames
let context: unknown
if (el.hasAttribute('_rcontext')) {
const contextExpression =
el.getAttribute(names.context) ?? el.getAttribute(names.contextAlias)
if (contextExpression !== null) {
context = parser
.__parse(contextExpression, undefined, undefined, true, true)
.value()[0]
}
el.removeAttribute(names.context)
el.removeAttribute(names.contextAlias)
el.removeAttribute('_rcontext')
}
const context = el.hasAttribute('_rcontext')
? this.__readContext(el)
: undefined

const mounted = { name: '' }

Expand Down
5 changes: 4 additions & 1 deletion src/bind/IfBinder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,9 @@ export class IfBinder {
}

__bindAll(element: Element): boolean {
const isIfElement = element.hasAttribute(this.__if)
const isIfElement =
element.hasAttribute(this.__if) &&
!this.__binder.__dynamicBinder.__isContextHost(element)
if (isIfElement) this.__bind(element as HTMLElement)
const isDynamicElement =
element.hasAttribute(this.__binder.__config.__builtInNames.is) ||
Expand Down Expand Up @@ -109,6 +111,7 @@ export class IfBinder {

__bind(el: HTMLElement): void {
if (
this.__binder.__dynamicBinder.__isContextHost(el) ||
el.hasAttribute(this.__pre) ||
this.__isProcessedOrMark(el) ||
// if elements should only be mounted after for's are mounted.
Expand Down
2 changes: 2 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import './runtime'

export type {
AnyRef,
BindData,
Expand Down
21 changes: 21 additions & 0 deletions src/runtime.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { version } from '../package.json'
import { srefSymbol } from './reactivity/refSymbols'

const runtimeKey = Symbol.for('regor.runtime')
const runtimeGlobal = globalThis as typeof globalThis & {
[runtimeKey]?: { version: string; identity: symbol }
}
const loaded = runtimeGlobal[runtimeKey]

if (loaded && loaded.identity !== srefSymbol) {
const error = new Error(
`Regor ${loaded.version} is already loaded; another runtime using ${version} was imported. ` +
'Ensure the renderer and components share one Regor instance.',
)
error.name = 'RegorRuntimeMismatch'
throw error
}

if (!loaded) {
runtimeGlobal[runtimeKey] = { version, identity: srefSymbol }
}
150 changes: 150 additions & 0 deletions tests/app/context-edge-repro.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
import { expect, test, vi } from 'vitest'

import { createApp, defineComponent, drainUnbind, ref, sref } from '../../src'

test.each([':context', 'r-context'])(
'%s on the mount root preserves root identity and cleanup',
async (attribute) => {
const container = document.createElement('div')
const root = document.createElement('aside')
root.setAttribute(attribute, 'user')
root.setAttribute(':title', 'name')
root.innerHTML = '<span r-text="name"></span>'
container.appendChild(root)
const name = ref('Ada')
const context = { user: { name }, name: 'outer' }
const app = createApp(context, { element: root })
try {
expect(root.querySelector('span')?.textContent).toBe('Ada')
expect(root.getAttribute('title')).toBe('Ada')
expect(container.firstChild).toBe(root)
expect(app.context).toBe(context)
expect(context.name).toBe('outer')
name('Grace')
expect(root.querySelector('span')?.textContent).toBe('Grace')
expect(root.getAttribute('title')).toBe('Grace')
app.unbind()
name('After unbind')
expect(root.querySelector('span')?.textContent).toBe('Grace')
expect(root.getAttribute('title')).toBe('Grace')
app.unmount()
expect(container.firstChild).toBeNull()
} finally {
app.unbind()
await drainUnbind()
}
},
)

test('repro: template context preserves and binds its content with browser template semantics', async () => {
const originalCreateElement = document.createElement.bind(document)
const createElement = vi
.spyOn(document, 'createElement')
.mockImplementation((tag, options) => {
const element = originalCreateElement(tag, options)
if (
element instanceof HTMLTemplateElement &&
element.childNodes === element.content.childNodes
) {
// MiniDOM aliases these lists. Browsers keep template content separate.
Object.defineProperty(element, 'childNodes', {
value: [],
writable: true,
})
}
return element
})
const root = document.createElement('div')
const app = createApp(
{ user: { name: 'Ada' } },
{
element: root,
template:
'<template :context="user"><span r-text="name"></span></template>',
},
)
try {
expect(root.querySelector('span')?.textContent).toBe('Ada')
expect(root.querySelector('template')).toBeNull()
} finally {
app.unbind()
createElement.mockRestore()
await drainUnbind()
}
})

test('repro: r-pre leaves nested context hosts untouched', async () => {
const root = document.createElement('div')
root.innerHTML =
'<div r-pre><div :context="user"><span r-text="name"></span></div><card :context="user"></card></div>'
const originalHtml = root.innerHTML
const app = createApp(
{
user: { name: 'Ada' },
components: { card: defineComponent('<strong>bound</strong>') },
},
{ element: root },
)
try {
expect(root.innerHTML).toBe(originalHtml)
} finally {
app.unbind()
await drainUnbind()
}
})

test('r-if on a context host reacts to that context without leaking to siblings', async () => {
const root = document.createElement('div')
const visible = ref(false)
const name = ref('Ada')
const app = createApp(
{ user: { visible, name }, visible: true, name: 'outer' },
{
element: root,
template:
'<div :context="user" r-if="visible"><span r-text="name"></span></div><b r-text="name"></b>',
},
)
try {
expect(root.querySelector('span')).toBeNull()
visible(true)
expect(root.querySelector('span')?.textContent).toBe('Ada')
expect(root.querySelector('b')?.textContent).toBe('outer')
name('Grace')
expect(root.querySelector('span')?.textContent).toBe('Grace')
visible(false)
expect(root.querySelector('span')).toBeNull()
visible(true)
expect(root.querySelector('span')?.textContent).toBe('Grace')
} finally {
app.unbind()
await drainUnbind()
}
})

test('row context works with r-for and a reactive r-if on the same host', async () => {
const root = document.createElement('div')
const ada = { name: 'Ada', visible: ref(true) }
const grace = { name: 'Grace', visible: ref(false) }
const rows = sref([ada, grace])
const app = createApp(
{ rows },
{
element: root,
template:
'<div r-for="row in rows" :context="row" r-if="visible"><span r-text="name"></span></div>',
},
)
try {
const names = () =>
[...root.querySelectorAll('span')].map((element) => element.textContent)
expect(names()).toEqual(['Ada'])
grace.visible(true)
expect(names()).toEqual(['Ada', 'Grace'])
ada.visible(false)
expect(names()).toEqual(['Grace'])
} finally {
app.unbind()
await drainUnbind()
}
})
Loading
Loading