Skip to content

Commit

Permalink
refactor(core): make lit portal a bit cleaner
Browse files Browse the repository at this point in the history
  • Loading branch information
pengx17 committed Dec 26, 2024
1 parent 74f954a commit 8d17ee7
Show file tree
Hide file tree
Showing 4 changed files with 22 additions and 41 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@ export {
type ElementOrFactory,
useLitPortal,
useLitPortalFactory,
} from './lite-portal';
} from './lit-portal';
Original file line number Diff line number Diff line change
Expand Up @@ -98,47 +98,28 @@ export const useLitPortalFactory = () => {
? elementOrFactory()
: elementOrFactory;
return createLitPortalAnchor(event => {
const { name, target } = event;
const id = target.portalId;

if (name === 'connectedCallback') {
setPortals(portals => [
...portals,
{
id,
portal: ReactDOM.createPortal(element, target, id),
},
]);
return;
}

if (name === 'disconnectedCallback') {
setPortals(portals => portals.filter(p => p.id !== id));
return;
}

const prevId = event.previousPortalId;

// Ignores first `willUpdate`
if (!prevId) {
return;
}

setPortals(portals => {
const portal = portals.find(p => p.id === prevId);
if (!portal) return [...portals];

// Updates `ID`
portal.id = id;

// Re-rendering
// true: `inline link`
// false: `pdf embed view`
if (rerendering) {
portal.portal = ReactDOM.createPortal(element, target, id);
const { name, target, previousPortalId } = event;
const id = target.portalId;

// skips update when
// - rerendering === false (for pdf preview etc)
// - previousPortalId is undefined (for the first willUpdate event)
if (name === 'willUpdate' && (!previousPortalId || !rerendering)) {
return portals;
}

return [...portals];
const newPortals = portals.filter(
p => p.id !== previousPortalId && p.id !== id
);
if (name === 'connectedCallback' || name === 'willUpdate') {
newPortals.push({
id,
portal: ReactDOM.createPortal(element, event.target),
});
return newPortals;
}
return newPortals;
});
});
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -357,7 +357,7 @@ export const BiDirectionalLinkPanel = () => {
{
<>
{portals.map(p => (
<Fragment key={p.portal.key}>{p.portal}</Fragment>
<Fragment key={p.id}>{p.portal}</Fragment>
))}
</>
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ const usePatchSpecs = (shared: boolean, mode: DocMode) => {
() => (
<>
{portals.map(p => (
<Fragment key={p.portal.key}>{p.portal}</Fragment>
<Fragment key={p.id}>{p.portal}</Fragment>
))}
</>
),
Expand Down

0 comments on commit 8d17ee7

Please sign in to comment.