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

Preact X useId #3583

Merged
merged 21 commits into from Sep 3, 2022
Merged
Show file tree
Hide file tree
Changes from 16 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions compat/src/index.d.ts
Expand Up @@ -24,6 +24,7 @@ declare namespace React {
export import useDebugValue = _hooks.useDebugValue;
export import useEffect = _hooks.useEffect;
export import useImperativeHandle = _hooks.useImperativeHandle;
export import useId = _hooks.useId;
export import useLayoutEffect = _hooks.useLayoutEffect;
export import useMemo = _hooks.useMemo;
export import useReducer = _hooks.useReducer;
Expand Down
2 changes: 2 additions & 0 deletions compat/src/index.js
Expand Up @@ -9,6 +9,7 @@ import {
} from 'preact';
import {
useState,
useId,
useReducer,
useEffect,
useLayoutEffect,
Expand Down Expand Up @@ -201,6 +202,7 @@ export {
// React copies the named exports to the default one.
export default {
useState,
useId,
useReducer,
useEffect,
useLayoutEffect,
Expand Down
2 changes: 2 additions & 0 deletions hooks/src/index.d.ts
Expand Up @@ -137,3 +137,5 @@ export function useDebugValue<T>(value: T, formatter?: (value: T) => any): void;
export function useErrorBoundary(
callback?: (error: any, errorInfo: ErrorInfo) => Promise<void> | void
): [any, () => void];

export function useId(): string;
40 changes: 39 additions & 1 deletion hooks/src/index.js
@@ -1,4 +1,4 @@
import { options } from 'preact';
import { Fragment, options } from 'preact';

/** @type {number} */
let currentIndex;
Expand Down Expand Up @@ -26,8 +26,31 @@ let oldBeforeUnmount = options.unmount;
const RAF_TIMEOUT = 100;
let prevRaf;

// the current ID prefix
let mask = '';

// tracks component depth (only for the current render, so may be subtree depth)
let depth = 0;

options._diff = vnode => {
JoviDeCroock marked this conversation as resolved.
Show resolved Hide resolved
if (typeof vnode.type === 'function' && vnode.type !== Fragment) {
if (vnode._mask) {
// already visited, pick up where we left off: (fixes subtree updates)
mask = vnode._mask;
} else if (depth === 0) {
// this is the first component rendered and hasn't been seen, it's a root:
vnode._mask = mask = '';
} else {
// replace mask[depth] with the next: (basically *mask[depth-1]++)
JoviDeCroock marked this conversation as resolved.
Show resolved Hide resolved
const offset = Number(mask[depth - 1]) + 1;
vnode._mask = mask = mask.slice(0, depth - 1) + offset;
}

depth++;
mask += '0';
}
currentComponent = null;

if (oldBeforeDiff) oldBeforeDiff(vnode);
};

Expand Down Expand Up @@ -61,6 +84,11 @@ options._render = vnode => {
options.diffed = vnode => {
if (oldAfterDiff) oldAfterDiff(vnode);

if (typeof vnode.type === 'function' && vnode.type !== Fragment) {
depth--;
mask = mask.slice(0, -1);
}

const c = vnode._component;
if (c && c.__hooks) {
if (c.__hooks._pendingEffects.length) afterPaint(afterPaintEffects.push(c));
Expand Down Expand Up @@ -366,6 +394,16 @@ export function useErrorBoundary(cb) {
];
}

export function useId() {
const state = getHookState(currentIndex++, 11);
if (!state._value) {
// TODO: consider Number(currentComponent._vnode._mask + currentIndex).toString(36)
state._value = 'P' + currentComponent._vnode._mask + '-' + currentIndex;
}

return state._value;
}

/**
* After paint effects consumer.
*/
Expand Down
7 changes: 6 additions & 1 deletion hooks/src/internal.d.ts
@@ -1,7 +1,8 @@
import {
Component as PreactComponent,
PreactContext,
ErrorInfo
ErrorInfo,
VNode as PreactVNode
} from '../../src/internal';
import { Reducer } from '.';

Expand Down Expand Up @@ -37,6 +38,10 @@ export interface Component extends PreactComponent<any, any> {
__hooks?: ComponentHooks;
}

export interface VNode extends PreactVNode {
_mask?: string;
}

export type HookState =
| EffectHookState
| MemoHookState
Expand Down
91 changes: 91 additions & 0 deletions hooks/test/browser/useId.test.js
@@ -0,0 +1,91 @@
import { createElement, render } from 'preact';
import { setupScratch, teardown } from '../../../test/_util/helpers';
import { useId } from 'preact/hooks';

/** @jsx createElement */

describe('useId', () => {
/** @type {HTMLDivElement} */
let scratch;

beforeEach(() => {
scratch = setupScratch();
});

afterEach(() => {
teardown(scratch);
});

it('keeps the id consistent after an update', () => {
function Comp() {
const id = useId();
return <div id={id} />;
}

render(<Comp />, scratch);
const id = scratch.firstChild.getAttribute('id');
expect(scratch.firstChild.getAttribute('id')).to.equal(id);

render(<Comp />, scratch);
expect(scratch.firstChild.getAttribute('id')).to.equal(id);
});

it('ids are unique according to dom-depth', () => {
function Child() {
const id = useId();
const spanId = useId();
return (
<div id={id}>
<span id={spanId}>h</span>
</div>
);
}

function Comp() {
const id = useId();
return (
<div id={id}>
<Child />
</div>
);
}

render(<Comp />, scratch);
expect(scratch.innerHTML).to.equal(
'<div id="P-1"><div id="P1-1"><span id="P1-2">h</span></div></div>'
);

render(<Comp />, scratch);
expect(scratch.innerHTML).to.equal(
'<div id="P-1"><div id="P1-1"><span id="P1-2">h</span></div></div>'
);
});

it('ids are unique across siblings', () => {
function Child() {
const id = useId();
return <span id={id}>h</span>;
}

function Comp() {
const id = useId();
return (
<div id={id}>
<Child />
<Child />
<Child />
</div>
);
}

render(<Comp />, scratch);
expect(scratch.innerHTML).to.equal(
'<div id="P-1"><span id="P1-1">h</span><span id="P2-1">h</span><span id="P3-1">h</span></div>'
);

render(<Comp />, scratch);
expect(scratch.innerHTML).to.equal(
'<div id="P-1"><span id="P1-1">h</span><span id="P2-1">h</span><span id="P3-1">h</span></div>'
);
});
});