Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

hotfix: contexts #545

Merged
merged 6 commits into from
Aug 21, 2023
Merged
Show file tree
Hide file tree
Changes from 5 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
382 changes: 247 additions & 135 deletions packages/compiler/react/transform.ts

Large diffs are not rendered by default.

5 changes: 4 additions & 1 deletion packages/compiler/react/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,14 @@ export interface Shared {

export interface Dynamics {
cache: Set<string>;
props?: t.Expression;
data: {
id: t.Identifier;
value: t.Expression | null;
}[];
deferred: (() => void)[];
unoptimizable: boolean;
portalInfo: {
index: number;
id: t.Identifier;
};
}
2 changes: 1 addition & 1 deletion packages/kitchen-sink/README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Million.js Kitchen Sink 🧑‍🍳

Hey! We're actively recruiting cooks 🧑‍🍳 to help assemble a list of examples of Million + your favorite React library.
Hey! We're actively recruiting cooks 🧑‍🍳 to help assemble a list of examples of Million + your favorite React library. [View it live at sink.million.dev](https://sink.million.dev)

## Getting Started

Expand Down
26 changes: 26 additions & 0 deletions packages/kitchen-sink/src/examples/context.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { useState, createContext, useContext } from 'react';
import { block } from 'million/react';

const ThemeContext = createContext('light');

const Context = block(() => {
const theme = useContext(ThemeContext);

return (
<div style={{ color: theme === 'light' ? 'black' : 'white' }}>{theme}</div>
);
});

const App = block(() => {
const [theme, setTheme] = useState('light');

return (
<ThemeContext.Provider value={theme}>
<button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
<Context />
</button>
</ThemeContext.Provider>
);
});

export default App;
14 changes: 9 additions & 5 deletions packages/million/block.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,8 +142,8 @@ export class Block extends AbstractBlock {
}
if (!el[TEXT_NODE_CACHE]) el[TEXT_NODE_CACHE] = new Array(l);

if (typeof value === 'function') {
const scopeEl = value(null);
if (value && typeof value === 'object' && 'foreign' in value) {
const scopeEl = value.current;
el[TEXT_NODE_CACHE][k] = scopeEl;
insertBefore$.call(el, scopeEl, childAt(el, edit.i!));
continue;
Expand Down Expand Up @@ -231,14 +231,18 @@ export class Block extends AbstractBlock {
oldValue.p(newChildBlock);
continue;
}
if (typeof newValue === 'function') {
if (
newValue &&
typeof newValue === 'object' &&
'foreign' in newValue
) {
const scopeEl = el[TEXT_NODE_CACHE][k];
if ('unstable' in newValue && oldValue !== newValue) {
const newScopeEl = newValue(null);
const newScopeEl = newValue.current;
el[TEXT_NODE_CACHE][k] = newScopeEl;
replaceChild$.call(el, newScopeEl, scopeEl);
} else {
newValue(scopeEl);
newValue.current = scopeEl;
}

continue;
Expand Down
4 changes: 2 additions & 2 deletions packages/react-server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,15 +35,15 @@ export const block = <P extends MillionProps>(
};
}, []);

if (!ready || !blockFactory || !props.__props) {
if (!ready || !blockFactory) {
if (options.ssr === false) return null;
return createElement<P>(
RENDER_SCOPE,
null,
// During compilation we will attach a .original for the component and
// pass __props as the props to the component. This references
// the original component for SSR.
createElement((options.original as any) || Component, props.__props),
createElement(Component, props as any),
);
}

Expand Down
6 changes: 4 additions & 2 deletions packages/react/block.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { queueMicrotask$ } from '../million/dom';
import { processProps, unwrap } from './utils';
import { Effect, RENDER_SCOPE, REGISTRY, SVG_RENDER_SCOPE } from './constants';
import type { ComponentType, Ref } from 'react';
import type { Options, MillionProps } from '../types';
import type { Options, MillionProps, MillionPortal } from '../types';

export const block = <P extends MillionProps>(
fn: ComponentType<P> | null,
Expand All @@ -26,8 +26,9 @@ export const block = <P extends MillionProps>(
) => {
const ref = useRef<HTMLElement>(null);
const patch = useRef<((props: P) => void) | null>(null);
const portalRef = useRef<MillionPortal[]>([]);

props = processProps(props, forwardedRef);
props = processProps(props, forwardedRef, portalRef.current);
patch.current?.(props);

const effect = useCallback(() => {
Expand All @@ -53,6 +54,7 @@ export const block = <P extends MillionProps>(
null,
marker,
createElement(Effect, { effect }),
...portalRef.current.map((p) => p.portal),
);

return vnode;
Expand Down
16 changes: 14 additions & 2 deletions packages/react/for.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,12 @@ import { renderReactScope } from './utils';
import { RENDER_SCOPE, REGISTRY, SVG_RENDER_SCOPE } from './constants';
import type { Block } from '../million';
import type { MutableRefObject } from 'react';
import type { ArrayCache, MillionArrayProps, MillionProps } from '../types';
import type {
ArrayCache,
MillionArrayProps,
MillionPortal,
MillionProps,
} from '../types';

const MillionArray = <T>({
each,
Expand Down Expand Up @@ -70,6 +75,7 @@ const createChildren = <T>(
memo?: boolean,
): Block[] => {
const children = Array(each.length);
const portalRef = useRef<MillionPortal[]>([]);
const currentCache = cache.current;
for (let i = 0, l = each.length; i < l; ++i) {
if (memo && currentCache.each && currentCache.each[i] === each[i]) {
Expand Down Expand Up @@ -101,7 +107,13 @@ const createChildren = <T>(
const currentBlock = (props: MillionProps) => {
return block(
{
scope: renderReactScope(createElement(vnode.type, props)),
scope: renderReactScope(
createElement(vnode.type, props),
false,
portalRef.current,
i,
false,
),
},
vnode.key ? String(vnode.key) : undefined,
);
Expand Down
67 changes: 37 additions & 30 deletions packages/react/utils.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,31 @@
import { Fragment, createElement, isValidElement, version } from 'react';
import { REACT_ROOT, REGISTRY, RENDER_SCOPE } from './constants';
import { Fragment, createElement, isValidElement } from 'react';
import { createPortal } from 'react-dom';
import { REGISTRY, RENDER_SCOPE } from './constants';
import type { ComponentProps, ReactNode, Ref } from 'react';
import type { VNode } from '../million';
import type { MillionPortal } from '../types';

// TODO: access perf impact of this
export const processProps = (props: ComponentProps<any>, ref: Ref<any>) => {
export const processProps = (
props: ComponentProps<any>,
ref: Ref<any>,
portals: MillionPortal[],
) => {
const processedProps: ComponentProps<any> = { ref };

let currentIndex = 0;

for (const key in props) {
const value = props[key];
if (isValidElement(value)) {
processedProps[key] = renderReactScope(value);
processedProps[key] = renderReactScope(
value,
false,
portals,
currentIndex++,
false,
);

continue;
}
processedProps[key] = props[key];
Expand All @@ -19,8 +34,15 @@ export const processProps = (props: ComponentProps<any>, ref: Ref<any>) => {
return processedProps;
};

export const renderReactScope = (vnode: ReactNode, unstable?: boolean) => {
if (typeof window === 'undefined') {
export const renderReactScope = (
vnode: ReactNode,
unstable: boolean,
portals: MillionPortal[],
currentIndex: number,
server: boolean,
) => {
const el = portals[currentIndex]?.current;
if (typeof window === 'undefined' || (server && !el)) {
return createElement(
RENDER_SCOPE,
{ suppressHydrationWarning: true },
Expand All @@ -42,32 +64,17 @@ export const renderReactScope = (vnode: ReactNode, unstable?: boolean) => {
}
}

const scope = (el: HTMLElement | null) => {
let root;
const parent = el ?? document.createElement(RENDER_SCOPE);
if (version.startsWith('18')) {
import('react-dom/client')
.then((res) => {
root =
REACT_ROOT in parent
? parent[REACT_ROOT]
: (parent[REACT_ROOT] = res.createRoot(parent));
root.render(vnode);
})
.catch((e) => {
// eslint-disable-next-line no-console
console.error(e);
});
} else {
root = parent[REACT_ROOT];
root.render(vnode);
}
return parent;
const current = el ?? document.createElement(RENDER_SCOPE);
const reactPortal = createPortal(vnode, current);
const millionPortal = {
foreign: true as const,
current,
portal: reactPortal,
unstable,
};
portals[currentIndex] = millionPortal;

if (unstable) scope.unstable = true;

return scope;
return millionPortal;
};

export const unwrap = (vnode: JSX.Element | null): VNode => {
Expand Down
9 changes: 8 additions & 1 deletion packages/types/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { block as createBlock } from '../million';
import type { ComponentType } from 'react';
import type { ComponentType, ReactPortal } from 'react';

export type MillionProps = Record<string, any>;

Expand Down Expand Up @@ -28,3 +28,10 @@ export interface ArrayCache<T> {
mounted?: boolean | null;
block?: ReturnType<typeof createBlock>;
}

export interface MillionPortal {
foreign: true;
current: HTMLElement;
portal: ReactPortal;
unstable?: boolean;
}
14 changes: 11 additions & 3 deletions website/pages/_meta.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,17 +15,25 @@
"type": "page",
"title": "Blog"
},
"foundation": {
"showcase": {
"type": "page",
"title": "Foundation",
"title": "Showcase",
"theme": {
"typesetting": "article"
"typesetting": "article",
"layout": "full"
}
},
"more": {
"title": "More",
"type": "menu",
"items": {
"foundation": {
"type": "page",
"title": "Foundation",
"theme": {
"typesetting": "article"
}
},
"research": {
"title": "Research",
"href": "https://dl.acm.org/doi/10.1145/3555776.3577683",
Expand Down
62 changes: 62 additions & 0 deletions website/pages/showcase.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
---
title: Showcase
---

import { Card, Cards } from 'nextra/components';

{<h1 className="mt-10 mb-4 text-center text-[2.5rem] font-bold tracking-tight">Showcase</h1>}

{<p className="mb-16 text-center text-lg text-gray-500 dark:text-gray-400">Projects powered by Million.js.</p>}

<Cards>
<ShowcaseCard title="Wyze" href="https://wyze.com/">
<>![Wyze preview](./showcase/wyze.png)</>
</ShowcaseCard>
<ShowcaseCard title="Dona AI" href="https://dona.ai/">
<>![Dona AI preview](./showcase/dona-ai.jpeg)</>
</ShowcaseCard>
<ShowcaseCard title="T4 Stack" href="https://t4stack.com/">
<>![T4 Stack preview](./showcase/t4stack.png)</>
</ShowcaseCard>
<ShowcaseCard title="VeganCheck.me" href="https://vegancheck.me/">
<>![VeganCheck.me preview](./showcase/vegancheck.png)</>
</ShowcaseCard>
<ShowcaseCard
title="Windows 11 Web"
href="/~https://github.com/PiyushSuthar/Windows-11-Web"
>
<>![Windows 11 Web preview](./showcase/windows-11-web.jpeg)</>
</ShowcaseCard>
<ShowcaseCard
title="jahir.dev"
href="/~https://github.com/jahirfiquitiva/jahir.dev"
>
<>![jahir.dev preview](./showcase/jahir-dev.png)</>
</ShowcaseCard>
<ShowcaseCard title="LogLib" href="https://www.loglib.io/">
<>![LogLib preview](./showcase/loglib.png)</>
</ShowcaseCard>
<ShowcaseCard title="Comty" href="/~https://github.com/ragestudio/comty">
<>![Comty preview](./showcase/comty.svg)</>
</ShowcaseCard>
</Cards>

export const ShowcaseCard = Object.assign(
// Copy card component and add default props
Card.bind(),
{
displayName: 'ShowcaseCard',
defaultProps: {
image: true,
arrow: true,
target: '_blank',
},
},
);

<style global jsx>{`
img {
aspect-ratio: 12/6.3;
object-fit: cover;
}
`}</style>
Loading