Best JavaScript code snippet using playwright-internal
ReactFiberHydrationContext.js
Source:ReactFiberHydrationContext.js
1/**2 * Copyright (c) Facebook, Inc. and its affiliates.3 *4 * This source code is licensed under the MIT license found in the5 * LICENSE file in the root directory of this source tree.6 *7 * @flow8 */9import type {Fiber} from './ReactFiber';10import type {11 Instance,12 TextInstance,13 HydratableInstance,14 SuspenseInstance,15 Container,16 HostContext,17} from './ReactFiberHostConfig';18import type {SuspenseState} from './ReactFiberSuspenseComponent';19import {20 HostComponent,21 HostText,22 HostRoot,23 SuspenseComponent,24} from 'shared/ReactWorkTags';25import {Deletion, Placement, Hydrating} from 'shared/ReactSideEffectTags';26import invariant from 'shared/invariant';27import {28 createFiberFromHostInstanceForDeletion,29 createFiberFromDehydratedFragment,30} from './ReactFiber';31import {32 shouldSetTextContent,33 supportsHydration,34 canHydrateInstance,35 canHydrateTextInstance,36 canHydrateSuspenseInstance,37 getNextHydratableSibling,38 getFirstHydratableChild,39 hydrateInstance,40 hydrateTextInstance,41 hydrateSuspenseInstance,42 getNextHydratableInstanceAfterSuspenseInstance,43 didNotMatchHydratedContainerTextInstance,44 didNotMatchHydratedTextInstance,45 didNotHydrateContainerInstance,46 didNotHydrateInstance,47 didNotFindHydratableContainerInstance,48 didNotFindHydratableContainerTextInstance,49 didNotFindHydratableContainerSuspenseInstance,50 didNotFindHydratableInstance,51 didNotFindHydratableTextInstance,52 didNotFindHydratableSuspenseInstance,53} from './ReactFiberHostConfig';54import {enableSuspenseServerRenderer} from 'shared/ReactFeatureFlags';55import {Never} from './ReactFiberExpirationTime';56// The deepest Fiber on the stack involved in a hydration context.57// This may have been an insertion or a hydration.58let hydrationParentFiber: null | Fiber = null;59let nextHydratableInstance: null | HydratableInstance = null;60let isHydrating: boolean = false;61function warnIfHydrating() {62 if (__DEV__) {63 if (isHydrating) {64 console.error(65 'We should not be hydrating here. This is a bug in React. Please file a bug.',66 );67 }68 }69}70function enterHydrationState(fiber: Fiber): boolean {71 if (!supportsHydration) {72 return false;73 }74 const parentInstance = fiber.stateNode.containerInfo;75 nextHydratableInstance = getFirstHydratableChild(parentInstance);76 hydrationParentFiber = fiber;77 isHydrating = true;78 return true;79}80function reenterHydrationStateFromDehydratedSuspenseInstance(81 fiber: Fiber,82 suspenseInstance: SuspenseInstance,83): boolean {84 if (!supportsHydration) {85 return false;86 }87 nextHydratableInstance = getNextHydratableSibling(suspenseInstance);88 popToNextHostParent(fiber);89 isHydrating = true;90 return true;91}92function deleteHydratableInstance(93 returnFiber: Fiber,94 instance: HydratableInstance,95) {96 if (__DEV__) {97 switch (returnFiber.tag) {98 case HostRoot:99 didNotHydrateContainerInstance(100 returnFiber.stateNode.containerInfo,101 instance,102 );103 break;104 case HostComponent:105 didNotHydrateInstance(106 returnFiber.type,107 returnFiber.memoizedProps,108 returnFiber.stateNode,109 instance,110 );111 break;112 }113 }114 const childToDelete = createFiberFromHostInstanceForDeletion();115 childToDelete.stateNode = instance;116 childToDelete.return = returnFiber;117 childToDelete.effectTag = Deletion;118 // This might seem like it belongs on progressedFirstDeletion. However,119 // these children are not part of the reconciliation list of children.120 // Even if we abort and rereconcile the children, that will try to hydrate121 // again and the nodes are still in the host tree so these will be122 // recreated.123 if (returnFiber.lastEffect !== null) {124 returnFiber.lastEffect.nextEffect = childToDelete;125 returnFiber.lastEffect = childToDelete;126 } else {127 returnFiber.firstEffect = returnFiber.lastEffect = childToDelete;128 }129}130function insertNonHydratedInstance(returnFiber: Fiber, fiber: Fiber) {131 fiber.effectTag = (fiber.effectTag & ~Hydrating) | Placement;132 if (__DEV__) {133 switch (returnFiber.tag) {134 case HostRoot: {135 const parentContainer = returnFiber.stateNode.containerInfo;136 switch (fiber.tag) {137 case HostComponent:138 const type = fiber.type;139 const props = fiber.pendingProps;140 didNotFindHydratableContainerInstance(parentContainer, type, props);141 break;142 case HostText:143 const text = fiber.pendingProps;144 didNotFindHydratableContainerTextInstance(parentContainer, text);145 break;146 case SuspenseComponent:147 didNotFindHydratableContainerSuspenseInstance(parentContainer);148 break;149 }150 break;151 }152 case HostComponent: {153 const parentType = returnFiber.type;154 const parentProps = returnFiber.memoizedProps;155 const parentInstance = returnFiber.stateNode;156 switch (fiber.tag) {157 case HostComponent:158 const type = fiber.type;159 const props = fiber.pendingProps;160 didNotFindHydratableInstance(161 parentType,162 parentProps,163 parentInstance,164 type,165 props,166 );167 break;168 case HostText:169 const text = fiber.pendingProps;170 didNotFindHydratableTextInstance(171 parentType,172 parentProps,173 parentInstance,174 text,175 );176 break;177 case SuspenseComponent:178 didNotFindHydratableSuspenseInstance(179 parentType,180 parentProps,181 parentInstance,182 );183 break;184 }185 break;186 }187 default:188 return;189 }190 }191}192function tryHydrate(fiber, nextInstance) {193 switch (fiber.tag) {194 case HostComponent: {195 const type = fiber.type;196 const props = fiber.pendingProps;197 const instance = canHydrateInstance(nextInstance, type, props);198 if (instance !== null) {199 fiber.stateNode = (instance: Instance);200 return true;201 }202 return false;203 }204 case HostText: {205 const text = fiber.pendingProps;206 const textInstance = canHydrateTextInstance(nextInstance, text);207 if (textInstance !== null) {208 fiber.stateNode = (textInstance: TextInstance);209 return true;210 }211 return false;212 }213 case SuspenseComponent: {214 if (enableSuspenseServerRenderer) {215 const suspenseInstance: null | SuspenseInstance = canHydrateSuspenseInstance(216 nextInstance,217 );218 if (suspenseInstance !== null) {219 const suspenseState: SuspenseState = {220 dehydrated: suspenseInstance,221 retryTime: Never,222 };223 fiber.memoizedState = suspenseState;224 // Store the dehydrated fragment as a child fiber.225 // This simplifies the code for getHostSibling and deleting nodes,226 // since it doesn't have to consider all Suspense boundaries and227 // check if they're dehydrated ones or not.228 const dehydratedFragment = createFiberFromDehydratedFragment(229 suspenseInstance,230 );231 dehydratedFragment.return = fiber;232 fiber.child = dehydratedFragment;233 return true;234 }235 }236 return false;237 }238 default:239 return false;240 }241}242function tryToClaimNextHydratableInstance(fiber: Fiber): void {243 if (!isHydrating) {244 return;245 }246 let nextInstance = nextHydratableInstance;247 if (!nextInstance) {248 // Nothing to hydrate. Make it an insertion.249 insertNonHydratedInstance((hydrationParentFiber: any), fiber);250 isHydrating = false;251 hydrationParentFiber = fiber;252 return;253 }254 const firstAttemptedInstance = nextInstance;255 if (!tryHydrate(fiber, nextInstance)) {256 // If we can't hydrate this instance let's try the next one.257 // We use this as a heuristic. It's based on intuition and not data so it258 // might be flawed or unnecessary.259 nextInstance = getNextHydratableSibling(firstAttemptedInstance);260 if (!nextInstance || !tryHydrate(fiber, nextInstance)) {261 // Nothing to hydrate. Make it an insertion.262 insertNonHydratedInstance((hydrationParentFiber: any), fiber);263 isHydrating = false;264 hydrationParentFiber = fiber;265 return;266 }267 // We matched the next one, we'll now assume that the first one was268 // superfluous and we'll delete it. Since we can't eagerly delete it269 // we'll have to schedule a deletion. To do that, this node needs a dummy270 // fiber associated with it.271 deleteHydratableInstance(272 (hydrationParentFiber: any),273 firstAttemptedInstance,274 );275 }276 hydrationParentFiber = fiber;277 nextHydratableInstance = getFirstHydratableChild((nextInstance: any));278}279function prepareToHydrateHostInstance(280 fiber: Fiber,281 rootContainerInstance: Container,282 hostContext: HostContext,283): boolean {284 if (!supportsHydration) {285 invariant(286 false,287 'Expected prepareToHydrateHostInstance() to never be called. ' +288 'This error is likely caused by a bug in React. Please file an issue.',289 );290 }291 const instance: Instance = fiber.stateNode;292 const updatePayload = hydrateInstance(293 instance,294 fiber.type,295 fiber.memoizedProps,296 rootContainerInstance,297 hostContext,298 fiber,299 );300 // TODO: Type this specific to this type of component.301 fiber.updateQueue = (updatePayload: any);302 // If the update payload indicates that there is a change or if there303 // is a new ref we mark this as an update.304 if (updatePayload !== null) {305 return true;306 }307 return false;308}309function prepareToHydrateHostTextInstance(fiber: Fiber): boolean {310 if (!supportsHydration) {311 invariant(312 false,313 'Expected prepareToHydrateHostTextInstance() to never be called. ' +314 'This error is likely caused by a bug in React. Please file an issue.',315 );316 }317 const textInstance: TextInstance = fiber.stateNode;318 const textContent: string = fiber.memoizedProps;319 const shouldUpdate = hydrateTextInstance(textInstance, textContent, fiber);320 if (__DEV__) {321 if (shouldUpdate) {322 // We assume that prepareToHydrateHostTextInstance is called in a context where the323 // hydration parent is the parent host component of this host text.324 const returnFiber = hydrationParentFiber;325 if (returnFiber !== null) {326 switch (returnFiber.tag) {327 case HostRoot: {328 const parentContainer = returnFiber.stateNode.containerInfo;329 didNotMatchHydratedContainerTextInstance(330 parentContainer,331 textInstance,332 textContent,333 );334 break;335 }336 case HostComponent: {337 const parentType = returnFiber.type;338 const parentProps = returnFiber.memoizedProps;339 const parentInstance = returnFiber.stateNode;340 didNotMatchHydratedTextInstance(341 parentType,342 parentProps,343 parentInstance,344 textInstance,345 textContent,346 );347 break;348 }349 }350 }351 }352 }353 return shouldUpdate;354}355function prepareToHydrateHostSuspenseInstance(fiber: Fiber): void {356 if (!supportsHydration) {357 invariant(358 false,359 'Expected prepareToHydrateHostSuspenseInstance() to never be called. ' +360 'This error is likely caused by a bug in React. Please file an issue.',361 );362 }363 let suspenseState: null | SuspenseState = fiber.memoizedState;364 let suspenseInstance: null | SuspenseInstance =365 suspenseState !== null ? suspenseState.dehydrated : null;366 invariant(367 suspenseInstance,368 'Expected to have a hydrated suspense instance. ' +369 'This error is likely caused by a bug in React. Please file an issue.',370 );371 hydrateSuspenseInstance(suspenseInstance, fiber);372}373function skipPastDehydratedSuspenseInstance(374 fiber: Fiber,375): null | HydratableInstance {376 if (!supportsHydration) {377 invariant(378 false,379 'Expected skipPastDehydratedSuspenseInstance() to never be called. ' +380 'This error is likely caused by a bug in React. Please file an issue.',381 );382 }383 let suspenseState: null | SuspenseState = fiber.memoizedState;384 let suspenseInstance: null | SuspenseInstance =385 suspenseState !== null ? suspenseState.dehydrated : null;386 invariant(387 suspenseInstance,388 'Expected to have a hydrated suspense instance. ' +389 'This error is likely caused by a bug in React. Please file an issue.',390 );391 return getNextHydratableInstanceAfterSuspenseInstance(suspenseInstance);392}393function popToNextHostParent(fiber: Fiber): void {394 let parent = fiber.return;395 while (396 parent !== null &&397 parent.tag !== HostComponent &&398 parent.tag !== HostRoot &&399 parent.tag !== SuspenseComponent400 ) {401 parent = parent.return;402 }403 hydrationParentFiber = parent;404}405function popHydrationState(fiber: Fiber): boolean {406 if (!supportsHydration) {407 return false;408 }409 if (fiber !== hydrationParentFiber) {410 // We're deeper than the current hydration context, inside an inserted411 // tree.412 return false;413 }414 if (!isHydrating) {415 // If we're not currently hydrating but we're in a hydration context, then416 // we were an insertion and now need to pop up reenter hydration of our417 // siblings.418 popToNextHostParent(fiber);419 isHydrating = true;420 return false;421 }422 const type = fiber.type;423 // If we have any remaining hydratable nodes, we need to delete them now.424 // We only do this deeper than head and body since they tend to have random425 // other nodes in them. We also ignore components with pure text content in426 // side of them.427 // TODO: Better heuristic.428 if (429 fiber.tag !== HostComponent ||430 (type !== 'head' &&431 type !== 'body' &&432 !shouldSetTextContent(type, fiber.memoizedProps))433 ) {434 let nextInstance = nextHydratableInstance;435 while (nextInstance) {436 deleteHydratableInstance(fiber, nextInstance);437 nextInstance = getNextHydratableSibling(nextInstance);438 }439 }440 popToNextHostParent(fiber);441 if (fiber.tag === SuspenseComponent) {442 nextHydratableInstance = skipPastDehydratedSuspenseInstance(fiber);443 } else {444 nextHydratableInstance = hydrationParentFiber445 ? getNextHydratableSibling(fiber.stateNode)446 : null;447 }448 return true;449}450function resetHydrationState(): void {451 if (!supportsHydration) {452 return;453 }454 hydrationParentFiber = null;455 nextHydratableInstance = null;456 isHydrating = false;457}458export {459 warnIfHydrating,460 enterHydrationState,461 reenterHydrationStateFromDehydratedSuspenseInstance,462 resetHydrationState,463 tryToClaimNextHydratableInstance,464 prepareToHydrateHostInstance,465 prepareToHydrateHostTextInstance,466 prepareToHydrateHostSuspenseInstance,467 popHydrationState,...
commissionsReducer.js
Source:commissionsReducer.js
1import axios from 'axios';2import { api, getConfig } from '../../api/apiInterfaceProvider';3import { commissionsMessages } from '../../utils/messages';4import {5 formatterDate,6 getStudentsNames,7 getTutorsNames8} from '../../utils/services/functions';9import {10 clearAlert,11 queryError,12 toggleLoading,13 hydrateAlert14} from '../login/authReducer';15const HYDRATE_APPROVED_COMMISSIONS = 'HYDRATE_APPROVED_COMMISSIONS';16const HYDRATE_TERMINATED_COMMISSIONS = 'HYDRATE_TERMINATED_COMMISSIONS';17const HYDRATE_PENDING_COMMISSIONS = 'HYDRATE_PENDING_COMMISSIONS';18const HYDRATE_COMMISSION = 'HYDRATE_COMMISSION';19const abandonedIdea = () =>20 hydrateAlert({21 message: commissionsMessages.ABANDON_SUCCESS,22 style: 'success',23 onDismiss: clearAlert24 });25const hydratePendingProjects = (data) => ({26 type: HYDRATE_PENDING_COMMISSIONS,27 data28});29const hydrateApprovedProjects = (data) => ({30 type: HYDRATE_APPROVED_COMMISSIONS,31 data32});33const hydrateTerminatedProjects = (data) => ({34 type: HYDRATE_TERMINATED_COMMISSIONS,35 data36});37const hydrateProject = (data) => ({38 type: HYDRATE_COMMISSION,39 data40});41export const rejectIdea = (projectId, memberId, postAction = () => {}) => (42 dispatch43) => {44 dispatch(toggleLoading({ loading: true }));45 const config = getConfig();46 axios47 .delete(api.abandonTutorProject(projectId, memberId), config)48 .then((res) => res.data.data)49 .then(() => {50 dispatch(toggleLoading({ loading: false }));51 dispatch(abandonedIdea());52 postAction();53 })54 .catch((error) => {55 dispatch(queryError(error));56 dispatch(toggleLoading({ loading: false }));57 });58};59export const getActiveProject = (projectId, dispatch) => {60 dispatch(toggleLoading({ loading: true }));61 const config = getConfig();62 axios63 .get(api.project(projectId), config)64 .then((res) => res.data.data)65 .then((data) => {66 dispatch(toggleLoading({ loading: false }));67 dispatch(hydrateProject(data));68 })69 .catch((error) => {70 dispatch(queryError(error));71 dispatch(toggleLoading({ loading: false }));72 });73};74export const getProject = (projectId) => (dispatch) => {75 getActiveProject(projectId, dispatch);76};77export const getProjects = (approved, terminated, career, dispatch) => {78 dispatch(toggleLoading({ loading: true }));79 const config = getConfig();80 const projectUrl = `${api.projectsForCommissions}?1=1${81 approved ? '&approved=1' : ''82 }${terminated ? '&terminated=1' : ''}${career ? `&career=${career}` : ''}`;83 axios84 .get(projectUrl, config)85 .then((res) => res.data.data)86 .then((data) => {87 dispatch(toggleLoading({ loading: false }));88 if (approved) {89 dispatch(hydrateApprovedProjects(data));90 } else if (terminated) {91 dispatch(hydrateTerminatedProjects(data));92 } else {93 dispatch(hydratePendingProjects(data));94 }95 })96 .catch((error) => {97 dispatch(toggleLoading({ loading: false }));98 dispatch(queryError(error));99 });100};101export const editPresentationData = (102 projectId,103 presentationId,104 {105 description,106 documentation_visible: documentationVisible,107 presentation_visible: presentationViisible108 }109) => (dispatch) => {110 dispatch(toggleLoading({ loading: true }));111 const config = getConfig();112 const body = {113 description,114 documentation_visible: documentationVisible,115 presentation_visible: presentationViisible116 };117 axios118 .put(api.editPresentations(presentationId), body, config)119 .then((res) => res.data.data)120 .then(() => {121 getActiveProject(projectId, dispatch);122 })123 .then(() => {124 dispatch(toggleLoading({ loading: false }));125 })126 .catch((error) => {127 dispatch(queryError(error));128 dispatch(toggleLoading({ loading: false }));129 });130};131export const approve = (projectId, careerId, postAction) => (dispatch) => {132 dispatch(toggleLoading({ loading: true }));133 const config = getConfig();134 const body = {135 career: careerId,136 status: 'accepted'137 };138 axios139 .put(api.assessment(projectId), body, config)140 .then((res) => res.data.data)141 .then(() => {142 getActiveProject(projectId, dispatch);143 postAction();144 dispatch(toggleLoading({ loading: false }));145 })146 .catch((error) => {147 dispatch(queryError(error));148 dispatch(toggleLoading({ loading: false }));149 });150};151export const reprobate = (projectId, careerId, rejectionReason, postAction) => (152 dispatch153) => {154 dispatch(toggleLoading({ loading: true }));155 const config = getConfig();156 const body = {157 career: careerId,158 status: 'rejected',159 reject_reason: rejectionReason160 };161 axios162 .put(api.assessment(projectId), body, config)163 .then((res) => res.data.data)164 .then(() => {165 getActiveProject(projectId, dispatch);166 postAction();167 dispatch(toggleLoading({ loading: false }));168 })169 .catch((error) => {170 dispatch(queryError(error));171 dispatch(toggleLoading({ loading: false }));172 });173};174export const getInitialData = (approved, terminated, career) => (dispatch) => {175 getProjects(approved, terminated, career, dispatch);176};177const fetchProjectsTable = (data) =>178 data.map((project) => ({179 id: project.id,180 name: project.name,181 description: project.description,182 students: getStudentsNames(project.Creator, project.Students),183 tutors: getTutorsNames(project.Tutor, project.Cotutors),184 careers: project.ProjectCareers.map(185 (projectCareer) => projectCareer.Career.name186 ).join(', '),187 type: project.Type.name,188 created_at: formatterDate(project.createdAt)189 }));190export default (191 state = {192 approvedProjects: [],193 pendingProjects: [],194 terminatedProjects: [],195 project: {}196 },197 action198) => {199 switch (action.type) {200 case HYDRATE_PENDING_COMMISSIONS:201 return {202 ...state,203 pendingProjects: fetchProjectsTable(action.data)204 };205 case HYDRATE_APPROVED_COMMISSIONS:206 return {207 ...state,208 approvedProjects: fetchProjectsTable(action.data)209 };210 case HYDRATE_TERMINATED_COMMISSIONS:211 return {212 ...state,213 terminatedProjects: fetchProjectsTable(action.data)214 };215 case HYDRATE_COMMISSION:216 return {217 ...state,218 project: action.data219 };220 default:221 return state;222 }...
LazyHydrate.test.js
Source:LazyHydrate.test.js
1import React from 'react'2import { mount } from 'enzyme'3import { styled } from '@mui/material/styles'4import { act } from 'react-dom/test-utils'5describe('LazyHydrate', () => {6 let isBrowser, LazyHydrate, LazyStyles, getRegistryCount, wrapper, Router7 afterEach(() => {8 wrapper && wrapper.unmount()9 })10 describe('on the server', () => {11 beforeEach(() => {12 jest.isolateModules(() => {13 isBrowser = jest.doMock('react-storefront/utils/isBrowser', () => () => false)14 const mod = require('react-storefront/LazyHydrate')15 LazyHydrate = mod.default16 LazyStyles = mod.LazyStyles17 getRegistryCount = mod.getRegistryCount18 })19 })20 it('should clear registries', () => {21 const PREFIX = 'LazyHydrate.test'22 const classes = {23 root: `${PREFIX}-root`,24 '@media (min-width: 1024px)': `${PREFIX}-@media (min-width: 1024px)`,25 }26 const Root = styled('button')(() => ({27 [`& .${classes.root}`]: {28 fontWeight: 'bold',29 'media (min-width: 1024px)': {30 width: 200,31 },32 },33 }))34 const TestComponent = () => {35 return <Root className={classes.root}>click</Root>36 }37 const hydrate = mount(38 <LazyHydrate id="test">39 <TestComponent />40 </LazyHydrate>,41 )42 expect(getRegistryCount()).toBe(1)43 wrapper = mount(44 <div>45 <LazyStyles />46 </div>,47 )48 expect(getRegistryCount()).toBe(0)49 hydrate.unmount()50 })51 it('should render children during SSR only mode', () => {52 const click = jest.fn()53 wrapper = mount(54 <LazyHydrate id="test" ssrOnly>55 <button onClick={click}>click</button>56 </LazyHydrate>,57 )58 expect(wrapper.html()).toContain('<button>click</button>')59 })60 })61 describe('in the browser', () => {62 let events, intersectionObserverCallback, intersectionObserverFallback63 beforeEach(() => {64 jest.isolateModules(() => {65 events = {}66 isBrowser = jest.doMock('react-storefront/utils/isBrowser', () => () => true)67 Router = jest.doMock('next/router', () => ({68 events: {69 on: (name, callback) => {70 events[name] = callback71 },72 },73 }))74 jest.doMock('react-storefront/hooks/useIntersectionObserver', () => {75 return (_el, callback, fallback) => {76 intersectionObserverCallback = callback77 intersectionObserverFallback = fallback78 }79 })80 const mod = require('react-storefront/LazyHydrate')81 LazyHydrate = mod.default82 LazyStyles = mod.LazyStyles83 getRegistryCount = mod.getRegistryCount84 })85 })86 it('should pass event through when hydrated', () => {87 const click = jest.fn()88 wrapper = mount(89 <LazyHydrate id="test" hydrated>90 <button onClick={click}>click</button>91 </LazyHydrate>,92 )93 wrapper.find('button').simulate('click')94 expect(click).toHaveBeenCalled()95 })96 it('should not render children in the browser during SSR only mode', () => {97 const click = jest.fn()98 wrapper = mount(99 <LazyHydrate id="test" ssrOnly>100 <button onClick={click}>click</button>101 </LazyHydrate>,102 )103 expect(wrapper.find('button').length).toBe(0)104 })105 it('should hydrate in browser once triggered', () => {106 wrapper = mount(107 <LazyHydrate id="test" hydrated={false}>108 <button>click</button>109 </LazyHydrate>,110 )111 expect(wrapper.html()).not.toContain('<button>click</button>')112 wrapper.setProps({ hydrated: true })113 expect(wrapper.html()).toContain('<button>click</button>')114 })115 it('should hydrate new elements immediately after navigation', () => {116 events.routeChangeStart()117 wrapper = mount(118 <LazyHydrate id="test" hydrated={false}>119 <button>click</button>120 </LazyHydrate>,121 )122 expect(wrapper.html()).toContain('<button>click</button>')123 })124 it('should remove the server side style sheet after hydration', () => {125 const style = document.createElement('style')126 style.setAttribute('id', 'test')127 document.head.appendChild(style)128 wrapper = mount(129 <LazyHydrate id="test" hydrated={false}>130 <button>click</button>131 </LazyHydrate>,132 )133 wrapper.setProps({ hydrated: true })134 expect(document.querySelector('style[id=test]')).toBe(null)135 })136 it('should hydrate on touch', async () => {137 wrapper = mount(138 <LazyHydrate id="test" on="touch">139 <button>click</button>140 </LazyHydrate>,141 )142 await act(async () => {143 wrapper.getDOMNode().dispatchEvent(new Event('touchstart'))144 })145 expect(wrapper.html()).toContain('<button>click</button>')146 })147 it('should hydrate on the first user interaction with the window', async () => {148 wrapper = mount(149 <LazyHydrate id="test" on="fui">150 <button>click</button>151 </LazyHydrate>,152 )153 await act(async () => {154 window.dispatchEvent(new Event('mouseover'))155 })156 expect(wrapper.html()).toContain('<button>click</button>')157 })158 it('should hydrate when visible', async () => {159 wrapper = mount(160 <LazyHydrate id="test" on="visible">161 <button>click</button>162 </LazyHydrate>,163 )164 await act(async () => {165 intersectionObserverCallback(true, jest.fn())166 })167 expect(wrapper.html()).toContain('<button>click</button>')168 })169 it('should not hydrate when not visible', async () => {170 wrapper = mount(171 <LazyHydrate id="test" on="visible">172 <button>click</button>173 </LazyHydrate>,174 )175 await act(async () => {176 intersectionObserverCallback(false, jest.fn())177 })178 expect(wrapper.html()).not.toContain('<button>click</button>')179 })180 })...
LazyHydrate.js
Source:LazyHydrate.js
...29 // (only relevant when using Preact) - see https://github.com/preactjs/preact/issues/2364#issuecomment-73695689430 const addToLazyComponents = useStore((state) => state.addToLazyComponents)31 const initHydrate = () => {32 id && addToLazyComponents(childRef?.current?.children?.[id])33 hydrate()34 }35 if (isDev && !ssrOnly && !whenIdle && !whenVisible && !on.length && !promise) {36 console.error(37 `LazyHydration: Enable atleast one trigger for hydration.\n` +38 `If you don't want to hydrate, use ssrOnly`39 )40 }41 useIsomorphicLayoutEffect(() => {42 // FIXME: hydrates instantly on page route changes because SSR HTML isn't present on route changes43 // No SSR Content44 if (!childRef.current.hasChildNodes()) {45 initHydrate()46 }47 }, [])...
PlaylistActions.js
Source:PlaylistActions.js
1import * as PlaylistAction from './constants/PlaylistActionConstants';2import { parseRSSFeed } from '../utils/playlists';3import { fetchingPlaylists } from './AppActions';4import isEmpty from 'lodash/isEmpty';5export const readFeedAndHydratePlaylist = (feedUrl, feedData = {}) => ({6 type: PlaylistAction.alias.READ_FEED_AND_HYDRATE_PLAYLIST,7 payload: {8 feedUrl,9 feedData10 }11});12const readFeedAndHydratePlaylistImpl = action => {13 let { feedUrl, feedData } = action.payload;14 return async (dispatch) => {15 if (isEmpty(feedData)) {16 try {17 feedData = await parseRSSFeed(feedUrl);18 feedData = feedData.feed;19 } catch (err) {20 console.error('[ytp] Error in readFeedAndHydratePlaylist:', err);21 throw new Error('Error in readFeedAndHydratePlaylist:' + err);22 }23 }24 dispatch(hydratePlaylist(feedData));25 };26};27export const readFeedAndHydrateAllPlaylists = feedUrls => ({28 type: PlaylistAction.alias.READ_FEED_AND_HYDRATE_ALL_PLAYLISTS,29 payload: feedUrls30});31const readFeedAndHydrateAllPlaylistsImpl = action => {32 const feedUrls = action.payload;33 return async (dispatch) => {34 dispatch(fetchingPlaylists(true));35 try {36 const promises = [];37 feedUrls.forEach(feed => {38 promises.push(parseRSSFeed(feed));39 });40 Promise.all(promises).then(feedData => {41 dispatch(fetchingPlaylists(false));42 feedData = feedData.map(data => data.feed);43 dispatch(hydrateAllPlaylists(feedData));44 });45 } catch (err) {46 console.error('[ytp] Error in readFeedAndHydrateAllPlaylists:', err);47 }48 };49};50export const hydratePlaylist = feedData => ({51 type: PlaylistAction.HYDRATE_PLAYLIST,52 payload: feedData53});54export const hydrateAllPlaylists = feedData => ({55 type: PlaylistAction.HYDRATE_ALL_PLAYLISTS,56 payload: feedData57});58export const aliases = {59 [PlaylistAction.alias.READ_FEED_AND_HYDRATE_PLAYLIST]: readFeedAndHydratePlaylistImpl,60 [PlaylistAction.alias.READ_FEED_AND_HYDRATE_ALL_PLAYLISTS]: readFeedAndHydrateAllPlaylistsImpl...
getReactStack.js
Source:getReactStack.js
1'use strict';2exports.__esModule = true;3var _hydrateFiberStack = require('./stack/hydrateFiberStack');4var _hydrateFiberStack2 = _interopRequireDefault(_hydrateFiberStack);5var _hydrateLegacyStack = require('./stack/hydrateLegacyStack');6var _hydrateLegacyStack2 = _interopRequireDefault(_hydrateLegacyStack);7var _reactUtils = require('./reactUtils');8function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }9function getReactStack(instance) {10 var rootNode = (0, _reactUtils.getInternalInstance)(instance);11 var stack = {};12 var isFiber = typeof rootNode.tag === 'number';13 if (isFiber) {14 (0, _hydrateFiberStack2.default)(rootNode, stack);15 } else {16 (0, _hydrateLegacyStack2.default)(rootNode, stack);17 }18 return stack;19} /* eslint-disable no-underscore-dangle */...
hydrate.test.js
Source:hydrate.test.js
...6 it('Testa se hydrate é uma função', () => {7 expect(typeof hydrate).toBe('function');8 });9 it('Ao receber uma string retorne a sugestão de quantos copos de água deve-se beber', () => {10 expect(hydrate('1 cerveja')).toBe('1 copo de água');11 expect(hydrate('1 cachaça, 5 cervejas e 1 copo de vinho')).toBe('7 copos de água');12 expect(hydrate('2 shots de tequila, 2 cervejas e 1 corote')).toBe('5 copos de água');13 expect(hydrate('1 copo de catuaba, 1 cervejas e 1 copo de vinho')).toBe('3 copos de água');14 expect(hydrate('4 caipirinhas e 2 cervejas')).toBe('6 copos de água');15 });...
hidratar.test.js
Source:hidratar.test.js
...6 it('Testa se hydrate é uma função', () => {7 expect(typeof hydrate).toBe('function');8 });9 it('Ao receber uma string retorne a sugestão de quantos copos de água deve-se beber', () => {10 expect(hydrate('1 cerveja')).toBe('1 copo de água');11 expect(hydrate('1 cachaça, 5 cervejas e 1 copo de vinho')).toBe('7 copos de água');12 expect(hydrate('2 shots de tequila, 2 cervejas e 1 corote')).toBe('5 copos de água');13 expect(hydrate('1 copo de catuaba, 1 cervejas e 1 copo de vinho')).toBe('3 copos de água');14 expect(hydrate('4 caipirinhas e 2 cervejas')).toBe('6 copos de água');15 });...
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.screenshot({ path: 'example.png' });7 await browser.close();8})();9const { chromium } = require('playwright');10(async () => {11 const browser = await chromium.launch();12 const context = await browser.newContext();13 const page = await context.newPage();14 await page.screenshot({ path: 'example.png' });15 await browser.close();16})();17const { chromium } = require('playwright');18(async () => {19 const browser = await chromium.launch();20 const context = await browser.newContext();21 const page = await context.newPage();22 await page.screenshot({ path: 'example.png' });23 await browser.close();24})();25const { chromium } = require('playwright');26(async () => {27 const browser = await chromium.launch();28 const context = await browser.newContext();29 const page = await context.newPage();30 await page.screenshot({ path: 'example.png' });31 await browser.close();32})();33const { chromium } = require('playwright');34(async () => {35 const browser = await chromium.launch();36 const context = await browser.newContext();37 const page = await context.newPage();38 await page.screenshot({ path: 'example.png' });39 await browser.close();40})();41const { chromium } = require('playwright');42(async () => {43 const browser = await chromium.launch();44 const context = await browser.newContext();45 const page = await context.newPage();
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const page = await browser.newPage();5 await page.screenshot({ path: 'example.png' });6 await browser.close();7})();8const { chromium } = require('playwright');9(async () => {10 const browser = await chromium.launch();11 const page = await browser.newPage();12 await page.screenshot({ path: 'example.png' });13 await browser.close();14})();15const { chromium } = require('playwright');16(async () => {17 const browser = await chromium.launch();18 const page = await browser.newPage();19 await page.screenshot({ path: 'example.png' });20 await browser.close();21})();22const { chromium } = require('playwright');23(async () => {24 const browser = await chromium.launch();25 const page = await browser.newPage();26 await page.screenshot({ path: 'example.png' });27 await browser.close();28})();29const { chromium } = require('playwright');30(async () => {31 const browser = await chromium.launch();32 const page = await browser.newPage();33 await page.screenshot({ path: 'example.png' });34 await browser.close();35})();36const { chromium } = require('playwright');37(async () => {38 const browser = await chromium.launch();39 const page = await browser.newPage();40 await page.screenshot({ path: 'example.png' });41 await browser.close();42})();43const { chromium } = require('playwright');44(async () => {45 const browser = await chromium.launch();46 const page = await browser.newPage();47 await page.screenshot({ path: 'example.png' });48 await browser.close();
Using AI Code Generation
1const { internal } = require('playwright');2const { chromium } = require('playwright-chromium');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 const newPage = await internal.hydrate(page);8})();9const { chromium } = require('playwright-chromium');10(async () => {11 const browser = await chromium.launch();12 const context = await browser.newContext();13 const page = await context.newPage();14 const newPage = await page.context().newPage();15})();16const { chromium } = require('playwright-chromium');17(async () => {18 const browser = await chromium.launch();19 const context = await browser.newContext();20 const page = await context.newPage();21 const newPage = await page._delegate.newPage();22})();23const { chromium } = require('playwright-chromium');24(async () => {25 const browser = await chromium.launch();26 const context = await browser.newContext();27 const page = await context.newPage();28 const newPage = await page._channel.newPage();29})();30const { chromium } = require('playwright-chromium');31(async () => {32 const browser = await chromium.launch();33 const context = await browser.newContext();34 const page = await context.newPage();35 const newPage = await page._browserContext.newPage();36})();37const { chromium } = require('playwright-chromium');38(async () => {39 const browser = await chromium.launch();40 const context = await browser.newContext();41 const page = await context.newPage();42 const newPage = await page._browserContext._browser.newPage();43})();44const { chromium }
Using AI Code Generation
1const { chromium } = require('playwright');2const { hydrate } = require('playwright/lib/server/supplements/recorder/recorderSupplement');3(async () => {4 const browser = await chromium.launch();5 const page = await browser.newPage();6 await hydrate(page, 'test.html');7 await browser.close();8})();
Using AI Code Generation
1const { chromium } = require('playwright');2const { hydrate } = require('playwright/lib/server/supplements/hydrate');3(async () => {4 const browser = await chromium.launch();5 const page = await browser.newPage();6 await hydrate(page, 'console.log("Hello World")');7 await browser.close();8})();9const { chromium } = require('playwright');10const { hydrate } = require('playwright/lib/server/supplements/hydrate');11(async () => {12 const browser = await chromium.launch();13 const page = await browser.newPage();14 await hydrate(page, () => {15 const h1 = document.querySelector('h1');16 h1.textContent = 'Hello World';17 return h1.textContent;18 });19 await browser.close();20})();21const { chromium } = require('playwright');22const { hydrate } = require('playwright/lib/server/s
Using AI Code Generation
1const path = require('path');2const { chromium } = require('playwright');3(async () => {4 const browser = await chromium.launch({ headless: false });5 const page = await browser.newPage();6 await page.evaluate(async () => {7 await window.playwright._internal.hydrate();8 });9 await page.screenshot({ path: path.join(__dirname, 'screenshot.png') });10 await browser.close();11})();12{13 "scripts": {14 },15 "dependencies": {16 }17}18const express = require('express');19const app = express();20app.get('/', (req, res) => {21 res.send(`22 window.addEventListener('DOMContentLoaded', () => {23 document.getElementById('root').innerHTML = '<h1>Hello World</h1><p>Rendered on Client</p>';24 });25 `);26});27app.listen(3000, () => console.log('App listening on port 3000!'));
Using AI Code Generation
1const { chromium } = require('playwright');2const { serialize, deserialize } = require('playwright/lib/client/serializers');3const { createGuid } = require('playwright/lib/utils/utils');4(async () => {5 const browser = await chromium.launch({ headless: false });6 const context = await browser.newContext();7 const page = await context.newPage();8 const serializedState = await page.evaluate(() => {9 return serialize(document);10 });11 const newPage = await context.newPage();12 await newPage.evaluate((state) => {13 return deserialize(state);14 }, serializedState);15 await newPage.close();16 await browser.close();17})();18function serialize(node) {19 const seen = new Map();20 const guid = createGuid();21 const state = {22 nodes: {23 [guid]: {24 name: node.nodeName.toLowerCase(),25 attributes: {},26 },27 },28 };29 for (let i = 0; i < node.attributes.length; i++) {30 const { name, value } = node.attributes[i];31 state.nodes[guid].attributes[name] = value;32 }33 const visit = (node, guid) => {34 for (let i = 0; i < node.childNodes.length; i++) {35 const child = node.childNodes[i];36 if (child.nodeType === Node.ELEMENT_NODE) {37 const childGuid = createGuid();38 state.nodes[guid].children.push(childGuid);39 state.nodes[childGuid] = {40 name: child.nodeName.toLowerCase(),41 attributes: {},42 };43 for (let j = 0; j < child.attributes.length; j++) {44 const { name, value } = child.attributes[j];45 state.nodes[childGuid].attributes[name] = value;46 }47 visit(child, childGuid);48 } else if (child.nodeType === Node.TEXT_NODE) {49 const childGuid = createGuid();50 state.nodes[guid].children.push(childGuid);51 state.nodes[childGuid] = {52 };53 }54 }55 };56 visit(node, guid
Using AI Code Generation
1const playwright = require('playwright');2const playwrightInternal = require('playwright/lib/server/playwright');3const { chromium } = playwright;4const { BrowserContext } = require('playwright/lib/server/chromium');5const { Page } = require('playwright/lib/server/page');6const { Frame } = require('playwright/lib/server/frame');7const { ElementHandle } = require('playwright/lib/server/elementHandler');8const { JSHandle } = require('playwright/lib/server/javascript');9(async () => {10 const browser = await chromium.launch({ headless: false });11 const context = await browser.newContext();12 const page = await context.newPage();13 const elementHandle = await page.$('input');14 const contextInternal = BrowserContext.from(context);15 const pageInternal = Page.from(page);16 const elementHandleInternal = ElementHandle.from(elementHandle);17 const frameInternal = Frame.from(elementHandleInternal._context.frame);18 const jsHandle = await elementHandleInternal.evaluateHandle((element) => element);19 const jsHandleInternal = JSHandle.from(jsHandle);20 const playwrightInternalInstance = playwrightInternal.from(contextInternal);21 const serializedResult = await playwrightInternalInstance._serializeResult(jsHandleInternal);22 console.log(serializedResult);23 const hydratedResult = await playwrightInternalInstance._deserializeResult(serializedResult);24 console.log(hydratedResult);25 await browser.close();26})();
Using AI Code Generation
1const playwright = require('playwright');2const { chromium } = playwright;3const { getTestState } = require('@playwright/test');4const { serialize, deserialize } = require('@playwright/test/lib/server/serializers');5(async () => {6 const browser = await chromium.launch();7 const context = await browser.newContext();8 const page = await context.newPage();9 const testState = getTestState();10 const serializedPage = serialize(testState, page);11 const hydratedPage = deserialize(testState, serializedPage);12 await hydratedPage.screenshot({ path: 'example.png' });13 await browser.close();14})();15const { chromium } = require('playwright');16const { it, expect, describe } = require('@playwright/test');17const { hydrate } = require('@playwright/test/lib/server/serializers');18describe('My test suite', () => {19 it('should hydrate the page', async ({ page, context, browser, testInfo }) => {20 const serializedPage = await page._serialize();21 const hydratedPage = await hydrate(testInfo, serializedPage);22 await hydratedPage.screenshot({ path: 'example.png' });23 });24});25const playwright = require('playwright');26const { chromium } = playwright;27const { getTestState } = require('@playwright/test');28const { serialize,
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!