Skip to content

Commit

Permalink
feat: testing multiple experimental perf boosting strategies
Browse files Browse the repository at this point in the history
  • Loading branch information
stipsan committed Jul 29, 2024
1 parent e8edf98 commit f8bcbfd
Show file tree
Hide file tree
Showing 71 changed files with 12,940 additions and 539 deletions.
421 changes: 421 additions & 0 deletions dev/test-studio/components/debugStyledComponents.tsx

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions dev/test-studio/sanity.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import {media} from 'sanity-plugin-media'
import {muxInput} from 'sanity-plugin-mux-input'

import {imageAssetSource} from './assetSources'
import {debugStyledComponents} from './components/debugStyledComponents'
import {
Annotation,
Block,
Expand Down Expand Up @@ -102,6 +103,7 @@ const sharedSettings = definePlugin({
badges: (prev, context) => (context.schemaType === 'author' ? [CustomBadge, ...prev] : prev),
},
plugins: [
debugStyledComponents(),
structureTool({
icon: BookIcon,
structure,
Expand Down
6 changes: 4 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
"check:deps": "pnpm --recursive --parallel exec depcheck",
"check:format": "prettier . --check",
"check:lint": "turbo run lint --continue -- --quiet",
"check:react-compiler": "eslint --no-inline-config --no-eslintrc --ext .cjs,.mjs,.js,.jsx,.ts,.tsx --parser @typescript-eslint/parser --plugin react-compiler --rule 'react-compiler/react-compiler: [warn]' --ignore-path .eslintignore.react-compiler --max-warnings 27 .",
"check:react-compiler": "eslint --no-inline-config --no-eslintrc --ext .cjs,.mjs,.js,.jsx,.ts,.tsx --parser @typescript-eslint/parser --plugin react-compiler --rule 'react-compiler/react-compiler: [warn]' --ignore-path .eslintignore.react-compiler --max-warnings 5 .",
"check:test": "run-s test -- --silent",
"check:types": "tsc && turbo run check:types --filter='./packages/*' --filter='./packages/@sanity/*'",
"chore:format:fix": "prettier --cache --write .",
Expand Down Expand Up @@ -186,7 +186,9 @@
"@npmcli/arborist": "^7.5.4",
"@sanity/ui@2": "$@sanity/ui",
"@typescript-eslint/eslint-plugin": "$@typescript-eslint/eslint-plugin",
"@typescript-eslint/parser": "$@typescript-eslint/parser"
"@typescript-eslint/parser": "$@typescript-eslint/parser",
"framer-motion": "11.3.6",
"styled-components": "npm:[email protected]"
}
},
"isSanityMonorepo": true
Expand Down
21 changes: 14 additions & 7 deletions packages/@repo/package.bundle/src/package.bundle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {version} from '../package.json'
export const defaultConfig: UserConfig = {
appType: 'custom',
define: {
'__DEV__': 'false',
'process.env.PKG_VERSION': JSON.stringify(version),
'process.env.NODE_ENV': '"production"',
'process.env': {},
Expand All @@ -23,13 +24,16 @@ export const defaultConfig: UserConfig = {
// self-externals are required here in order to ensure that the presentation
// tool and future transitive dependencies that require sanity do not
// re-include sanity in their bundle
external: ['react', 'react-dom', 'styled-components', 'sanity', '@sanity/vision'].flatMap(
(dependency) => [
dependency,
// this matches `react/jsx-runtime`, `sanity/presentation` etc
new RegExp(`^${escapeRegExp(dependency)}\\/`),
],
),
external: [
...['react', 'react-dom', 'styled-components', 'sanity', '@sanity/vision'].flatMap(
(dependency) => [
dependency,
// this matches `react/jsx-runtime`, `sanity/presentation` etc
new RegExp(`^${escapeRegExp(dependency)}\\/`),
],
),
'./checkoutPairWorker.ts',
],
output: {
exports: 'named',
dir: 'dist',
Expand All @@ -40,4 +44,7 @@ export const defaultConfig: UserConfig = {
},
},
},
worker: {
format: 'es',
},
}
3 changes: 3 additions & 0 deletions packages/@repo/package.config/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,8 @@
"types": "./src/package.config.ts",
"scripts": {
"check:types": "tsc --noEmit --skipLibCheck src/package.config.ts"
},
"dependencies": {
"@web/rollup-plugin-import-meta-assets": "2.2.1"
}
}
14 changes: 14 additions & 0 deletions packages/@repo/package.config/src/package.config.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import {defineConfig} from '@sanity/pkg-utils'
// @ts-expect-error -- missing types
import {importMetaAssets} from '@web/rollup-plugin-import-meta-assets'

export default defineConfig({
define: {
Expand Down Expand Up @@ -29,6 +31,18 @@ export default defineConfig({
legacyExports: true,
rollup: {
optimizeLodash: true,
plugins: ([t1, t2, t3, t4, t5, t6, ...plugins]) => [
t1,
t2,
t3,
t4,
t5,
t6,
importMetaAssets({
include: ['**/checkoutPair.mjs', '**/checkoutPair.ts'],
}),
...plugins,
],
},
tsconfig: 'tsconfig.lib.json',
strictOptions: {
Expand Down
1 change: 1 addition & 0 deletions packages/@sanity/vision/src/hooks/useDatasets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ export function useDatasets(client: SanityClient): string[] | Error | undefined
error: (err) => setDatasets(err),
})

// @TODO see if it's better to useObservable here
return () => datasets$.unsubscribe()
}, [client, projectId])

Expand Down
1 change: 1 addition & 0 deletions packages/sanity/.eslintignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,4 @@ presentation.js
router.js
structure.js
/migrate/*
/web-workers/*
3 changes: 3 additions & 0 deletions packages/sanity/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,6 @@
/migrate.js
/_internal.js
/cli.js

/web-workers/**/*.map
/web-workers/**/*.esm.js
4 changes: 4 additions & 0 deletions packages/sanity/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,7 @@
"scripts": {
"build": "pkg-utils build --strict --check --clean",
"build:bundle": "vite build --config package.bundle.ts",
"build:web-workers": "vite build --config package.worker.ts",
"check:types": "tsc --project tsconfig.lib.json",
"clean": "rimraf _internal.js _singletons.js _createContext.js cli.js desk.js migrate.js presentation.js router.js structure.js lib",
"coverage": "jest --coverage",
Expand Down Expand Up @@ -252,13 +253,15 @@
"rxjs": "^7.8.0",
"rxjs-exhaustmap-with-trailing": "^2.1.1",
"sanity-diff-patch": "^3.0.2",
"scheduler": "^0.23.2",
"scroll-into-view-if-needed": "^3.0.3",
"semver": "^7.3.5",
"shallow-equals": "^1.0.0",
"speakingurl": "^14.0.1",
"tar-fs": "^2.1.1",
"tar-stream": "^3.1.7",
"use-device-pixel-ratio": "^1.1.0",
"use-effect-event": "^1.0.2",
"use-hot-module-reload": "^2.0.0",
"use-sync-external-store": "^1.2.0",
"vite": "^4.5.1",
Expand Down Expand Up @@ -294,6 +297,7 @@
"@types/refractor": "^3.0.0",
"@types/resolve-from": "^4.0.0",
"@types/rimraf": "^3.0.2",
"@types/scheduler": "^0.23.0",
"@types/semver": "^6.2.3",
"@types/tar-fs": "^2.0.1",
"@vvo/tzdb": "6.137.0",
Expand Down
32 changes: 32 additions & 0 deletions packages/sanity/package.worker.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import {defineConfig, mergeConfig} from 'vite'

import {defaultConfig} from '../@repo/package.bundle/src/package.bundle'

export default defineConfig(() => {
return mergeConfig(defaultConfig, {
define: {
'window.process': 'undefined',
'window.location': 'location',
'window.console': 'console',
'window.addEventListener': 'addEventListener',
},
build: {
lib: {
entry: './src/core/store/_legacy/document/document-pair/checkoutPairWorker.ts',
fileName: 'checkoutPair',
},
rollupOptions: {
external: [],
output: {
exports: 'none',
dir: 'web-workers',
format: 'iife',
inlineDynamicImports: true,
},
},
},
worker: {
format: 'iife',
},
})
})
3 changes: 3 additions & 0 deletions packages/sanity/src/_internal/cli/server/getViteConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,9 @@ export async function getViteConfig(options: ViteOptions): Promise<InlineConfig>
'process.env.MODE': JSON.stringify(mode),
...getStudioEnvironmentVariables({prefix: 'process.env.', jsonEncode: true}),
},
worker: {
format: 'es',
},
}

if (mode === 'production') {
Expand Down
27 changes: 12 additions & 15 deletions packages/sanity/src/core/field/diff/components/FieldChange.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -81,8 +81,6 @@ export function FieldChange(
*/
const fieldPath = isArray ? change.path.slice(0, -1) : change.path

const value = useMemo(() => ({path: change.path}), [change.path])

const content = useMemo(
() =>
hidden ? null : (
Expand All @@ -101,7 +99,7 @@ export function FieldChange(
<ValueError error={change.error} />
) : (
<DiffErrorBoundary t={t}>
<DiffContext.Provider value={value}>
<DiffContext.Provider value={{path: change.path}}>
<DiffComponent
diff={change.diff}
schemaType={change.schemaType as ObjectSchemaType}
Expand Down Expand Up @@ -155,24 +153,23 @@ export function FieldChange(
</Stack>
),
[
hidden,
change,
FieldWrapper,
fieldPath,
revertHovered,
t,
value,
DiffComponent,
isComparingCurrent,
isPermissionsLoading,
permissions?.granted,
closeRevertChangesConfirmDialog,
handleRevertChanges,
confirmRevertOpen,
handleRevertChangesConfirm,
DiffComponent,
fieldPath,
FieldWrapper,
handleRevertButtonMouseEnter,
handleRevertButtonMouseLeave,
handleRevertChanges,
handleRevertChangesConfirm,
hidden,
isComparingCurrent,
isPermissionsLoading,
permissions?.granted,
readOnly,
revertHovered,
t,
],
)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import {ConnectorContext, DiffContext} from 'sanity/_singletons'
import {styled} from 'styled-components'

import {Popover} from '../../../../../../ui-components'
import {useChangeIndicatorsReportedValues} from '../../../../../changeIndicators'
import {useReportedValues} from '../../../../../changeIndicators'
import {useTranslation} from '../../../../../i18n'
import {ChangeList, DiffTooltip, useDiffAnnotationColor} from '../../../../diff'
import {type ObjectDiff} from '../../../../types'
Expand Down Expand Up @@ -131,7 +131,7 @@ function AnnnotationWithDiff({
const annotationPath = useMemo(() => prefix.concat(path), [path, prefix])
const myPath = useMemo(() => prefix.concat(markDefPath), [markDefPath, prefix])
const myValue = `field-${toString(myPath)}`
const values = useChangeIndicatorsReportedValues()
const values = useReportedValues()
const isEditing = useMemo(
() => values.filter(([p]) => p.startsWith(myValue)).length > 0,
[myValue, values],
Expand Down Expand Up @@ -162,10 +162,8 @@ function AnnnotationWithDiff({
const annotation = (diff.action !== 'unchanged' && diff.annotation) || null
const annotations = useMemo(() => (annotation ? [annotation] : []), [annotation])

const value = useMemo(() => ({path: myPath}), [myPath])

const popoverContent = (
<DiffContext.Provider value={value}>
<DiffContext.Provider value={{path: myPath}}>
<PopoverContainer padding={3}>
<div>
{emptyObject && (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import {ConnectorContext, DiffContext} from 'sanity/_singletons'
import {styled} from 'styled-components'

import {Popover} from '../../../../../../ui-components'
import {useChangeIndicatorsReportedValues} from '../../../../../changeIndicators'
import {useReportedValues} from '../../../../../changeIndicators'
import {useTranslation} from '../../../../../i18n'
import {Preview} from '../../../../../preview/components/Preview'
import {ChangeList, DiffTooltip, useDiffAnnotationColor} from '../../../../diff'
Expand Down Expand Up @@ -99,7 +99,7 @@ function InlineObjectWithDiff({
)
const myPath = prefix.concat(path)
const myValue = `field-${toString(myPath)}`
const values = useChangeIndicatorsReportedValues()
const values = useReportedValues()
const isEditing = values.filter(([p]) => p.startsWith(myValue)).length > 0

const focusPath = fullPath.slice(0, -1).concat(path).concat([FOCUS_TERMINATOR])
Expand Down Expand Up @@ -128,10 +128,8 @@ function InlineObjectWithDiff({
setOpen(false)
}, [])

const value = useMemo(() => ({path: myPath}), [myPath])

const popoverContent = (
<DiffContext.Provider value={value}>
<DiffContext.Provider value={{path: myPath}}>
<PopoverContent
diff={diff}
emptyObject={emptyObject}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {TooltipDelayGroupProvider} from '../../../../ui-components'
import {type DocumentFieldActionNode} from '../../../config'
import {FieldPresence, type FormNodePresence} from '../../../presence'
import {calcAvatarStackWidth} from '../../../presence/utils'
import {resizeObserver} from '../../../util'
import {FieldActionMenu} from '../../field'
import {type FieldCommentsProps} from '../../types'

Expand Down Expand Up @@ -182,38 +183,31 @@ export function FormFieldBaseHeader(props: FormFieldBaseHeaderProps) {
// Determine if floating card with actions should be shown
const shouldShowFloatingCard = focused || showFieldActions || hasComments

const handleSetFloatingCardElementWidth = useCallback(() => {
if (floatingCardElement) {
const {width} = floatingCardElement.getBoundingClientRect()
setFloatingCardWidth(width || 0)
}
}, [floatingCardElement])

// When a focus or blur event occurs on the floating card, we need to recalculate its width.
// This is because presence should be positioned relative to the floating card.
// We need this because we don't conditionally render the floating card and rely on CSS to
// show/hide it, and therefore the width calculation won't be triggered when the card is shown or hidden.
useEffect(() => {
if (!floatingCardElement) return undefined
return resizeObserver.observe(floatingCardElement, (event) => {
setFloatingCardWidth(event.borderBoxSize?.[0].inlineSize ?? 0)
})
}, [floatingCardElement])

const handleFocusCapture = useCallback(() => {
handleSetFloatingCardElementWidth()
setFocused(true)
}, [handleSetFloatingCardElementWidth])
}, [])

const handleBlurCapture = useCallback(() => {
handleSetFloatingCardElementWidth()
setFocused(false)
}, [handleSetFloatingCardElementWidth])

// Calculate floating card's width
useEffect(() => {
handleSetFloatingCardElementWidth()
}, [handleSetFloatingCardElementWidth, showFieldActions])
}, [])

// Calculate slot element's width
useEffect(() => {
if (slotElement) {
const {width} = slotElement.getBoundingClientRect()
setSlotWidth(width || 0)
}
if (!slotElement) return undefined
return resizeObserver.observe(slotElement, (event) => {
setSlotWidth(event.borderBoxSize?.[0].inlineSize ?? 0)
})
}, [slotElement])

// Construct the slot element if slot is provided
Expand Down
Loading

0 comments on commit f8bcbfd

Please sign in to comment.