├── playground
├── .npmrc
├── public
│ ├── robots.txt
│ ├── favicon.ico
│ └── og-image.jpg
├── tsconfig.json
├── server
│ └── tsconfig.json
├── .gitignore
├── nuxt.config.ts
├── package.json
├── app.vue
├── assets
│ └── global.css
├── utils
│ └── head.ts
└── components
│ ├── WithContainer.vue
│ └── Header.vue
├── pnpm-workspace.yaml
├── .husky
└── pre-commit
├── packages
└── vue-use-fixed-header
│ ├── .gitignore
│ ├── src
│ ├── index.ts
│ ├── constants.ts
│ ├── utils.ts
│ ├── types.ts
│ └── useFixedHeader.ts
│ ├── cypress
│ └── support
│ │ ├── styles.css
│ │ ├── component-index.html
│ │ ├── constants.ts
│ │ ├── component.ts
│ │ └── commands.ts
│ ├── cypress.config.ts
│ ├── tsconfig.json
│ ├── tests
│ ├── pointer.cy.ts
│ ├── styles.cy.ts
│ ├── reduced-motion.cy.ts
│ ├── components
│ │ ├── WindowScroll.vue
│ │ ├── Watch.vue
│ │ └── ContainerScroll.vue
│ ├── page-load.cy.ts
│ ├── watch.cy.ts
│ └── resize.cy.ts
│ ├── index.html
│ ├── vite.config.ts
│ └── package.json
├── .vscode
└── extensions.json
├── CONTRIBUTING.md
├── .prettierrc
├── .gitignore
├── .github
└── workflows
│ ├── firefox-tests.yml
│ ├── chrome-tests.yml
│ └── publish.yml
├── package.json
├── LICENSE
├── README.md
└── CODE_OF_CONDUCT.md
/playground/.npmrc:
--------------------------------------------------------------------------------
1 | shamefully-hoist=true
--------------------------------------------------------------------------------
/playground/public/robots.txt:
--------------------------------------------------------------------------------
1 | User-agent: *
2 | Disallow:
--------------------------------------------------------------------------------
/playground/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "./.nuxt/tsconfig.json"
3 | }
4 |
--------------------------------------------------------------------------------
/pnpm-workspace.yaml:
--------------------------------------------------------------------------------
1 | packages:
2 | - 'packages/*'
3 | - 'playground'
4 |
--------------------------------------------------------------------------------
/playground/server/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "../.nuxt/tsconfig.server.json"
3 | }
4 |
--------------------------------------------------------------------------------
/.husky/pre-commit:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 | . "$(dirname -- "$0")/_/husky.sh"
3 |
4 | npx lint-staged
5 |
--------------------------------------------------------------------------------
/packages/vue-use-fixed-header/.gitignore:
--------------------------------------------------------------------------------
1 | README.md
2 |
3 | LICENSE
4 |
5 | vite.config.ts.timestamp*
6 |
--------------------------------------------------------------------------------
/.vscode/extensions.json:
--------------------------------------------------------------------------------
1 | {
2 | "recommendations": ["Vue.volar", "Vue.vscode-typescript-vue-plugin"]
3 | }
4 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | Please refer to [smastrom/contributing](https://github.com/smastrom/contributing/blob/main/README.md).
2 |
--------------------------------------------------------------------------------
/playground/public/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/smastrom/vue-use-fixed-header/HEAD/playground/public/favicon.ico
--------------------------------------------------------------------------------
/playground/public/og-image.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/smastrom/vue-use-fixed-header/HEAD/playground/public/og-image.jpg
--------------------------------------------------------------------------------
/packages/vue-use-fixed-header/src/index.ts:
--------------------------------------------------------------------------------
1 | export { useFixedHeader } from './useFixedHeader'
2 |
3 | export * from './types'
4 |
--------------------------------------------------------------------------------
/.prettierrc:
--------------------------------------------------------------------------------
1 | {
2 | "tabWidth": 3,
3 | "semi": false,
4 | "singleQuote": true,
5 | "useTabs": false,
6 | "printWidth": 100
7 | }
8 |
--------------------------------------------------------------------------------
/packages/vue-use-fixed-header/cypress/support/styles.css:
--------------------------------------------------------------------------------
1 | html,
2 | body {
3 | margin: 0;
4 | padding: 0;
5 | }
6 |
7 | * {
8 | box-sizing: border-box;
9 | }
10 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | pnpm-debug.log*
2 |
3 | .vscode
4 | *.sublime-workspace
5 | *.sublime-project
6 |
7 | node_modules
8 | dist
9 |
10 | *.tgz
11 |
12 | .nuxt
13 | pnpm-lock.yaml
14 |
--------------------------------------------------------------------------------
/playground/.gitignore:
--------------------------------------------------------------------------------
1 | # Nuxt dev/build outputs
2 | .output
3 | .data
4 | .nuxt
5 | .nitro
6 | .cache
7 | dist
8 |
9 | # Node dependencies
10 | node_modules
11 |
12 | # Logs
13 | logs
14 | *.log
15 |
--------------------------------------------------------------------------------
/playground/nuxt.config.ts:
--------------------------------------------------------------------------------
1 | import { getHead } from './utils/head'
2 |
3 | export default defineNuxtConfig({
4 | devtools: { enabled: false },
5 | app: {
6 | head: getHead(),
7 | },
8 | nitro: {
9 | preset: 'cloudflare-pages',
10 | },
11 | css: ['@/assets/global.css'],
12 | })
13 |
--------------------------------------------------------------------------------
/packages/vue-use-fixed-header/cypress.config.ts:
--------------------------------------------------------------------------------
1 | import { defineConfig } from 'cypress'
2 |
3 | export default defineConfig({
4 | video: false,
5 | viewportWidth: 1280,
6 | viewportHeight: 720,
7 | component: {
8 | devServer: {
9 | framework: 'vue',
10 | bundler: 'vite',
11 | },
12 | },
13 | })
14 |
--------------------------------------------------------------------------------
/packages/vue-use-fixed-header/src/constants.ts:
--------------------------------------------------------------------------------
1 | export const EASING = 'cubic-bezier(0.16, 1, 0.3, 1)'
2 |
3 | export const TRANSITION_STYLES = {
4 | enterStyles: {
5 | transition: `all 0.35s ${EASING} 0s`,
6 | transform: 'translateY(0px)',
7 | },
8 | leaveStyles: {
9 | transition: `all 0.5s ${EASING} 0s`,
10 | transform: 'translateY(-101%)',
11 | },
12 | }
13 |
--------------------------------------------------------------------------------
/packages/vue-use-fixed-header/cypress/support/component-index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | Components App
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/packages/vue-use-fixed-header/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "target": "ES2015",
4 | "module": "ES2020",
5 | "moduleResolution": "Node",
6 | "strict": true,
7 | "resolveJsonModule": true,
8 | "isolatedModules": true,
9 | "esModuleInterop": true,
10 | "lib": ["ES2020", "DOM"],
11 | "skipLibCheck": true,
12 | "noEmit": true
13 | },
14 | "include": ["."]
15 | }
16 |
--------------------------------------------------------------------------------
/packages/vue-use-fixed-header/tests/pointer.cy.ts:
--------------------------------------------------------------------------------
1 | describe('Pointer', { browser: ['chrome'] }, () => {
2 | it('Should not hide header if hovering target', () => {
3 | cy.mountApp()
4 | .get('header')
5 | .realHover({ position: 'center' })
6 | .scrollDown()
7 | .get('header')
8 | .should('be.visible')
9 | })
10 |
11 | it('Should hide header if not hovering target', () => {
12 | cy.mountApp().getScrollSubject().scrollTo('bottom').get('header').should('be.visible')
13 | })
14 | })
15 |
--------------------------------------------------------------------------------
/packages/vue-use-fixed-header/tests/styles.cy.ts:
--------------------------------------------------------------------------------
1 | import { TRANSITION_STYLES } from '../src/constants'
2 |
3 | describe('Styles', () => {
4 | const { enterStyles, leaveStyles } = TRANSITION_STYLES
5 |
6 | it('Transitions are toggled properly', () => {
7 | cy.mountApp()
8 | .scrollDown()
9 | .get('header')
10 | .should('be.hidden')
11 | .checkStyles(leaveStyles)
12 |
13 | .scrollUp()
14 | .get('header')
15 | .should('be.visible')
16 | .checkStyles(enterStyles)
17 | })
18 | })
19 |
--------------------------------------------------------------------------------
/playground/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "vue-use-fixed-header-playground",
3 | "private": true,
4 | "type": "module",
5 | "scripts": {
6 | "build": "nuxt build",
7 | "dev": "nuxt dev",
8 | "generate": "nuxt generate",
9 | "preview": "nuxt preview",
10 | "postinstall": "nuxt prepare"
11 | },
12 | "dependencies": {
13 | "vue-use-fixed-header": "workspace:*"
14 | },
15 | "devDependencies": {
16 | "@nuxt/devtools": "latest",
17 | "nuxt": "^3.10.1",
18 | "vue": "^3.4.15",
19 | "vue-router": "^4.2.5"
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/packages/vue-use-fixed-header/tests/reduced-motion.cy.ts:
--------------------------------------------------------------------------------
1 | describe('prefers-reduced-motion', () => {
2 | beforeEach(() => {
3 | cy.stub(window, 'matchMedia').withArgs('(prefers-reduced-motion: reduce)').returns({
4 | matches: true,
5 | })
6 | })
7 |
8 | it('Shold not add transition', () => {
9 | cy.mountApp()
10 | .getScrollSubject()
11 | .get('header')
12 | .should('have.css', 'transition', 'all 0s ease 0s')
13 | .scrollUp()
14 | .get('header')
15 | .should('have.css', 'transition', 'all 0s ease 0s')
16 | })
17 | })
18 |
--------------------------------------------------------------------------------
/packages/vue-use-fixed-header/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | Vue Use Fixed Header | Vue 3 Fixed Header Composable
8 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/packages/vue-use-fixed-header/cypress/support/constants.ts:
--------------------------------------------------------------------------------
1 | export const isCustomContainer = Cypress.env('CONTAINER') === 'custom'
2 |
3 | export const customStyles = {
4 | enter: {
5 | transition: 'transform 0.9s ease-in-out 0s',
6 | transform: 'translateY(0px) scale(1.1)',
7 | opacity: 0.8,
8 | },
9 | leave: {
10 | transition: 'transform 0.7s ease-in-out 0s, opacity 0.7s ease-in-out 0s',
11 | transform: 'translateY(-100%) scale(1)',
12 | opacity: 0.2,
13 | },
14 | }
15 |
16 | export const VIEWPORT_HEADER_RELATIVE = isCustomContainer ? 475 : 768
17 | export const VIEWPORT_HEADER_HIDDEN = isCustomContainer ? 320 : 375
18 |
--------------------------------------------------------------------------------
/packages/vue-use-fixed-header/src/utils.ts:
--------------------------------------------------------------------------------
1 | import { onBeforeUnmount, onMounted, ref } from 'vue'
2 |
3 | export const isBrowser = typeof window !== 'undefined'
4 |
5 | export function useReducedMotion() {
6 | const isReduced = ref(false)
7 |
8 | if (!isBrowser) return isReduced
9 |
10 | const query = window.matchMedia('(prefers-reduced-motion: reduce)')
11 |
12 | const onMatch = () => (isReduced.value = query.matches)
13 |
14 | onMounted(() => {
15 | onMatch()
16 | query.addEventListener?.('change', onMatch)
17 | })
18 |
19 | onBeforeUnmount(() => {
20 | query.removeEventListener?.('change', onMatch)
21 | })
22 |
23 | return isReduced
24 | }
25 |
--------------------------------------------------------------------------------
/packages/vue-use-fixed-header/cypress/support/component.ts:
--------------------------------------------------------------------------------
1 | import { mount } from 'cypress/vue'
2 |
3 | import 'cypress-real-events'
4 |
5 | import './commands'
6 |
7 | import WindowScroll from '../../tests/components/WindowScroll.vue'
8 | import ContainerScroll from '../../tests/components/ContainerScroll.vue'
9 |
10 | import { isCustomContainer } from './constants'
11 |
12 | import './styles.css'
13 |
14 | declare global {
15 | namespace Cypress {
16 | interface Chainable {
17 | mount: typeof mount
18 | mountApp: (props?: Record) => ReturnType
19 | }
20 | }
21 | }
22 |
23 | Cypress.Commands.add('mount', mount)
24 |
25 | Cypress.Commands.add('mountApp', (props = {}) => {
26 | cy.mount(isCustomContainer ? ContainerScroll : WindowScroll, props)
27 | })
28 |
--------------------------------------------------------------------------------
/packages/vue-use-fixed-header/src/types.ts:
--------------------------------------------------------------------------------
1 | import type { Ref, ComputedRef } from 'vue'
2 |
3 | export type MaybeTemplateRef = HTMLElement | null | Ref
4 |
5 | export interface UseFixedHeaderOptions {
6 | /**
7 | * Scrolling container. Matches `document.documentElement` if `null`.
8 | *
9 | * @default null
10 | */
11 | root: MaybeTemplateRef
12 | /**
13 | * Signal without `.value` (ref or computed) to be watched
14 | * for automatic behavior toggling.
15 | *
16 | * @default null
17 | */
18 | watch: Ref | ComputedRef
19 | /**
20 | * Whether to transition `opacity` property from 0 to 1
21 | * and vice versa along with the `transform` property
22 | *
23 | * @default false
24 | */
25 | transitionOpacity: boolean | Ref | ComputedRef
26 | }
27 |
--------------------------------------------------------------------------------
/packages/vue-use-fixed-header/vite.config.ts:
--------------------------------------------------------------------------------
1 | import { defineConfig } from 'vite'
2 | import vue from '@vitejs/plugin-vue'
3 | import dts from 'vite-plugin-dts'
4 |
5 | const isFinalBundle = !process.argv.includes('--watch')
6 |
7 | export default defineConfig({
8 | build: {
9 | emptyOutDir: isFinalBundle,
10 | target: 'es2015',
11 | lib: {
12 | entry: 'src/index.ts',
13 | fileName: 'index',
14 | formats: ['es'],
15 | },
16 | rollupOptions: {
17 | external: ['vue'],
18 | output: {
19 | globals: {
20 | vue: 'Vue',
21 | },
22 | },
23 | },
24 | },
25 | esbuild: {
26 | drop: isFinalBundle ? ['console'] : [],
27 | },
28 | plugins: [
29 | dts({
30 | rollupTypes: true,
31 | }),
32 | vue(),
33 | ],
34 | })
35 |
--------------------------------------------------------------------------------
/packages/vue-use-fixed-header/tests/components/WindowScroll.vue:
--------------------------------------------------------------------------------
1 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
43 |
--------------------------------------------------------------------------------
/.github/workflows/firefox-tests.yml:
--------------------------------------------------------------------------------
1 | name: Firefox
2 |
3 | on:
4 | pull_request:
5 | push:
6 | branches:
7 | - '*'
8 | tags-ignore:
9 | - '*'
10 | workflow_call:
11 |
12 | jobs:
13 | cypress-ct:
14 | runs-on: ubuntu-latest
15 | steps:
16 | - uses: actions/checkout@v3
17 | - uses: actions/setup-node@v3
18 | with:
19 | node-version: '20'
20 | - uses: pnpm/action-setup@v2
21 | name: Install pnpm
22 | id: pnpm-install
23 | with:
24 | version: 8
25 | run_install: false
26 | - name: Install dependencies
27 | run: pnpm install
28 | - name: Window scroll
29 | run: pnpm -C packages/vue-use-fixed-header run test:firefox
30 | - name: Custom scrolling container
31 | run: pnpm -C packages/vue-use-fixed-header test:container:firefox
32 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "vue-use-fixed-header-monorepo",
3 | "private": true,
4 | "packageManager": "pnpm@8.10.2",
5 | "engines": {
6 | "node": ">=20.0.0"
7 | },
8 | "scripts": {
9 | "dev": "concurrently \"pnpm -C packages/vue-use-fixed-header run watch\" \"pnpm -C playground install && pnpm -C playground run dev --host\"",
10 | "build": "pnpm -C packages/vue-use-fixed-header run build",
11 | "build:playground": "pnpm build && pnpm -C playground run build",
12 | "test": "pnpm -C packages/vue-use-fixed-header run test",
13 | "test:gui": "pnpm -C packages/vue-use-fixed-header run test:gui",
14 | "prepare": "husky install"
15 | },
16 | "devDependencies": {
17 | "concurrently": "^8.2.2",
18 | "husky": "^8.0.3",
19 | "lint-staged": "^15.2.2",
20 | "prettier": "^3.2.5"
21 | },
22 | "lint-staged": {
23 | "*.{js,ts,vue,json,css,md}": "prettier --write"
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/.github/workflows/chrome-tests.yml:
--------------------------------------------------------------------------------
1 | name: Chrome
2 |
3 | on:
4 | pull_request:
5 | push:
6 | branches:
7 | - '*'
8 | tags-ignore:
9 | - '*'
10 | workflow_call:
11 |
12 | jobs:
13 | cypress-ct:
14 | runs-on: ubuntu-latest
15 | env:
16 | CYPRESS_RETRIES: 2
17 | steps:
18 | - uses: actions/checkout@v3
19 | - uses: actions/setup-node@v3
20 | with:
21 | node-version: '20'
22 | - uses: pnpm/action-setup@v2
23 | name: Install pnpm
24 | id: pnpm-install
25 | with:
26 | version: 8
27 | run_install: false
28 | - name: Install dependencies
29 | run: pnpm install
30 | - name: Window scroll
31 | run: pnpm -C packages/vue-use-fixed-header run test:chrome
32 | - name: Custom scrolling container
33 | run: pnpm -C packages/vue-use-fixed-header test:container:chrome
34 |
--------------------------------------------------------------------------------
/packages/vue-use-fixed-header/tests/components/Watch.vue:
--------------------------------------------------------------------------------
1 |
17 |
18 |
19 |
20 |
28 |
29 |
30 |
31 |
44 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Copyright (c) 2023 Simone Mastromattei
2 |
3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4 |
5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6 |
7 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
8 |
--------------------------------------------------------------------------------
/playground/app.vue:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
Vue Use Fixed Header
8 |
Turn your boring fixed header into a smart and beautiful one.
9 |
10 |
11 |
12 |
13 |
14 |
20 |
21 |
22 |
23 |
49 |
--------------------------------------------------------------------------------
/packages/vue-use-fixed-header/tests/page-load.cy.ts:
--------------------------------------------------------------------------------
1 | function testIstantRestoration() {
2 | return cy
3 | .mountApp()
4 | .getScrollSubject()
5 | .scrollTo('bottom', { duration: 0 })
6 | .get('header')
7 | .should('not.be.visible')
8 | }
9 |
10 | function testSmoothRestoration() {
11 | return cy.mountApp().scrollDown().get('header').should('not.be.visible')
12 | }
13 |
14 | describe('Page load', () => {
15 | it('Header is visible at top of the page', () => {
16 | cy.mountApp().get('header').should('be.visible')
17 | })
18 |
19 | describe('Header is hidden after scroll restoration', () => {
20 | it('Instant scroll', testIstantRestoration)
21 | it('Smooth scroll', testSmoothRestoration)
22 | })
23 |
24 | describe('Header is visible if scrolling up after scroll-restoration', () => {
25 | it('Instant scroll', () => {
26 | testIstantRestoration().scrollUp().get('header').should('be.visible')
27 | })
28 |
29 | it('Smooth scroll', () => {
30 | testSmoothRestoration().scrollUp().get('header').should('be.visible')
31 | })
32 | })
33 | })
34 |
--------------------------------------------------------------------------------
/packages/vue-use-fixed-header/tests/watch.cy.ts:
--------------------------------------------------------------------------------
1 | import App from './components/Watch.vue'
2 |
3 | import { ref } from 'vue'
4 | import { TRANSITION_STYLES as STYLES } from '../src/constants'
5 |
6 | describe('Watch', () => {
7 | if (!Cypress.env('CONTAINER')) {
8 | it('Toggles functionalities when reactive source changes', () => {
9 | const isRelative = ref(false)
10 |
11 | cy.mount(App, { props: { watch: isRelative } })
12 |
13 | cy.scrollDown()
14 | .get('header')
15 | .checkStyles({ ...STYLES.leaveStyles, visibility: 'hidden' })
16 | .then(() => (isRelative.value = true))
17 |
18 | cy.get('header')
19 | .should('have.attr', 'style')
20 | .and('be.eq', 'position: relative;')
21 | .then(() => (isRelative.value = false))
22 |
23 | cy.scrollUp()
24 | .get('header')
25 | .checkStyles(STYLES.enterStyles)
26 | .then(() => (isRelative.value = true))
27 |
28 | .get('header')
29 | .should('have.attr', 'style')
30 | .and('be.eq', 'position: relative;')
31 | })
32 | }
33 | })
34 |
--------------------------------------------------------------------------------
/.github/workflows/publish.yml:
--------------------------------------------------------------------------------
1 | name: Publish to NPM
2 |
3 | on:
4 | push:
5 | tags: ['v*']
6 | workflow_dispatch:
7 |
8 | jobs:
9 | chrome-tests-workflow:
10 | uses: ./.github/workflows/chrome-tests.yml
11 | firefox-tests-workflow:
12 | uses: ./.github/workflows/firefox-tests.yml
13 | publish:
14 | needs: [chrome-tests-workflow, firefox-tests-workflow]
15 | runs-on: ubuntu-latest
16 | permissions:
17 | contents: read
18 | id-token: write
19 | steps:
20 | - uses: actions/checkout@v3
21 | - uses: actions/setup-node@v3
22 | with:
23 | node-version: '20.x'
24 | registry-url: 'https://registry.npmjs.org'
25 | - uses: pnpm/action-setup@v2
26 | name: Install pnpm
27 | with:
28 | version: 8
29 | run_install: true
30 | - name: Build package
31 | run: pnpm build
32 | - name: Copy README and LICENSE
33 | run: cp README.md LICENSE packages/vue-use-fixed-header
34 | - name: Pack
35 | run: cd packages/vue-use-fixed-header && rm -rf *.tgz && npm pack
36 | - name: Publish
37 | run: cd packages/vue-use-fixed-header && npm publish *.tgz --provenance --access public
38 | env:
39 | NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
40 |
--------------------------------------------------------------------------------
/packages/vue-use-fixed-header/tests/components/ContainerScroll.vue:
--------------------------------------------------------------------------------
1 |
12 |
13 |
14 |
21 |
22 |
23 |
70 | ../../src/useFixedHeader
71 |
--------------------------------------------------------------------------------
/playground/assets/global.css:
--------------------------------------------------------------------------------
1 | :root {
2 | font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif;
3 | line-height: 1.5;
4 | background: var(--AccentBrightColor);
5 | -webkit-font-smoothing: antialiased;
6 | -moz-osx-font-smoothing: grayscale;
7 | text-rendering: optimizeLegibility;
8 | }
9 |
10 | :root {
11 | --AccentColor: #00976b;
12 | --TextColor: #494949;
13 | --WhiteColor: #fff;
14 | --AccentBrightColor: #2fe292;
15 | --AccentLightColor: #d5ece2;
16 | --AccentDarkColor: #076046;
17 | }
18 |
19 | :root {
20 | --shadow-color: 220 3% 15%;
21 | --shadow-strength: 1%;
22 | --Shadow: 0 -1px 3px 0 hsl(var(--shadow-color) / calc(var(--shadow-strength) + 2%)),
23 | 0 1px 2px -5px hsl(var(--shadow-color) / calc(var(--shadow-strength) + 2%)),
24 | 0 2px 5px -5px hsl(var(--shadow-color) / calc(var(--shadow-strength) + 4%)),
25 | 0 4px 12px -5px hsl(var(--shadow-color) / calc(var(--shadow-strength) + 5%)),
26 | 0 12px 15px -5px hsl(var(--shadow-color) / calc(var(--shadow-strength) + 7%));
27 | }
28 |
29 | * {
30 | box-sizing: border-box;
31 | }
32 |
33 | html,
34 | body,
35 | h1,
36 | h2,
37 | h3,
38 | ul,
39 | li {
40 | margin: 0;
41 | padding: 0;
42 | }
43 |
44 | .Global_VisuallyHidden {
45 | clip: rect(0 0 0 0);
46 | clip-path: inset(50%);
47 | height: 1px;
48 | overflow: hidden;
49 | position: absolute;
50 | white-space: nowrap;
51 | width: 1px;
52 | }
53 |
54 | .Global_Logo {
55 | text-transform: uppercase;
56 | line-height: 1;
57 | user-select: none;
58 | color: var(--TextColor);
59 | }
60 |
61 | .Global_Logo::first-letter {
62 | opacity: 0.15;
63 | }
64 |
--------------------------------------------------------------------------------
/packages/vue-use-fixed-header/cypress/support/commands.ts:
--------------------------------------------------------------------------------
1 | import { isCustomContainer } from './constants'
2 |
3 | import type { CSSProperties } from 'vue'
4 |
5 | import 'cypress-wait-frames'
6 |
7 | declare global {
8 | namespace Cypress {
9 | interface Chainable {
10 | getScrollSubject: () => Cypress.Chainable
11 | scrollUp: () => Cypress.Chainable
12 | scrollDown: () => Cypress.Chainable
13 | checkStyles: (styles: CSSProperties) => Cypress.Chainable
14 | resizeRoot: (newWidth: number) => Cypress.Chainable
15 | }
16 | }
17 | }
18 |
19 | Cypress.Commands.add('getScrollSubject', () => {
20 | if (isCustomContainer) return cy.get('.Scroller')
21 | return cy.window()
22 | })
23 |
24 | Cypress.Commands.add('resizeRoot', (newWidth: number) => {
25 | if (isCustomContainer) {
26 | return cy
27 | .get('.Scroller')
28 | .then(($el) => {
29 | $el.css({ width: `${newWidth}px` })
30 | })
31 | .waitFrames({
32 | subject: () => cy.get('.Scroller'),
33 | property: 'clientWidth',
34 | frames: 10,
35 | })
36 | }
37 |
38 | return cy.viewport(newWidth, newWidth).waitFrames({
39 | subject: cy.window,
40 | property: 'outerWidth',
41 | frames: 10,
42 | })
43 | })
44 |
45 | Cypress.Commands.add('scrollUp', () => cy.getScrollSubject().scrollTo('top', { duration: 300 }))
46 |
47 | Cypress.Commands.add('scrollDown', () =>
48 | cy.getScrollSubject().scrollTo('bottom', { duration: 300 })
49 | )
50 |
51 | Cypress.Commands.add('checkStyles', { prevSubject: 'element' }, (subject, styles) => {
52 | Object.entries(styles).forEach(([property, value]) => {
53 | cy.wrap(subject).should('have.attr', 'style').and('include', `${property}: ${value}`)
54 | })
55 | })
56 |
--------------------------------------------------------------------------------
/playground/utils/head.ts:
--------------------------------------------------------------------------------
1 | const siteName = 'Vue Use Fixed Header'
2 | const description = 'Turn your boring fixed header into a smart one with three lines of code.'
3 |
4 | export function getHead() {
5 | return {
6 | title: `${siteName} - ${description}`,
7 | link: [
8 | {
9 | rel: 'icon',
10 | href: '/favicon.ico',
11 | },
12 | ],
13 | htmlAttrs: {
14 | lang: 'en',
15 | },
16 | meta: [
17 | {
18 | hid: 'description',
19 | name: 'description',
20 | content: description,
21 | },
22 | {
23 | hid: 'og:title',
24 | property: 'og:title',
25 | content: `${siteName} - ${description}`,
26 | },
27 | {
28 | hid: 'og:description',
29 | property: 'og:description',
30 | content: description,
31 | },
32 | {
33 | hid: 'og:image',
34 | property: 'og:image',
35 | content: '/og-image.jpg',
36 | },
37 | {
38 | hid: 'og:url',
39 | property: 'og:url',
40 | content: 'https://vue-use-fixed-header.pages.dev',
41 | },
42 | {
43 | hid: 'twitter:title',
44 | name: 'twitter:title',
45 | content: `${siteName} - ${description}`,
46 | },
47 | {
48 | hid: 'twitter:description',
49 | name: 'twitter:description',
50 | content: description,
51 | },
52 |
53 | {
54 | hid: 'twitter:image',
55 | name: 'twitter:image',
56 | content: '/og-image.jpg',
57 | },
58 | {
59 | hid: 'twitter:card',
60 | name: 'twitter:card',
61 | content: 'summary_large_image',
62 | },
63 | ],
64 | }
65 | }
66 |
--------------------------------------------------------------------------------
/packages/vue-use-fixed-header/tests/resize.cy.ts:
--------------------------------------------------------------------------------
1 | import {
2 | VIEWPORT_HEADER_RELATIVE as RELATIVE,
3 | VIEWPORT_HEADER_HIDDEN as HIDDEN,
4 | } from '../cypress/support/constants'
5 |
6 | import { TRANSITION_STYLES } from '../src/constants'
7 |
8 | const ITERATIONS = 10
9 | const FIXED = RELATIVE * 2
10 |
11 | describe('Functionalies are disabled', () => {
12 | it('Resizing from `position: fixed` to `position: relative`', () => {
13 | cy.mountApp()
14 |
15 | for (let i = 0; i < ITERATIONS; i++) {
16 | cy.resizeRoot(FIXED).resizeRoot(RELATIVE)
17 | }
18 |
19 | cy.scrollDown()
20 | cy.get('header')
21 | .invoke('attr', 'style')
22 | .then((style) => {
23 | expect(style).to.be.oneOf([null, undefined, ''])
24 | })
25 | })
26 |
27 | it('Resizing from `position: fixed` to `display: none`', () => {
28 | cy.mountApp().resizeRoot(HIDDEN)
29 |
30 | for (let i = 0; i < ITERATIONS; i++) {
31 | cy.resizeRoot(FIXED).resizeRoot(HIDDEN)
32 | }
33 |
34 | cy.scrollDown()
35 | cy.get('header')
36 | .invoke('attr', 'style')
37 | .then((style) => {
38 | expect(style).to.be.oneOf([null, undefined, ''])
39 | })
40 | })
41 | })
42 |
43 | describe('Functionalies are enabled', () => {
44 | it('Resizing from `position: relative` to `position: fixed`', () => {
45 | cy.mountApp()
46 |
47 | for (let i = 0; i < ITERATIONS; i++) {
48 | cy.resizeRoot(RELATIVE).resizeRoot(FIXED)
49 | }
50 |
51 | cy.scrollDown()
52 | cy.get('header').should('be.hidden').checkStyles(TRANSITION_STYLES.leaveStyles)
53 | })
54 |
55 | it('Resizing from `display: none` to `position: fixed`', () => {
56 | cy.mountApp()
57 |
58 | for (let i = 0; i < ITERATIONS; i++) {
59 | cy.resizeRoot(HIDDEN).resizeRoot(FIXED)
60 | }
61 |
62 | cy.scrollDown()
63 | cy.get('header').should('be.hidden').checkStyles(TRANSITION_STYLES.leaveStyles)
64 | })
65 | })
66 |
--------------------------------------------------------------------------------
/packages/vue-use-fixed-header/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "vue-use-fixed-header",
3 | "description": "Turn your boring fixed header into a smart one with three lines of code.",
4 | "private": false,
5 | "version": "2.0.3",
6 | "type": "module",
7 | "keywords": [
8 | "vue",
9 | "vuejs",
10 | "vue-3",
11 | "fixed-header",
12 | "use-fixed-header",
13 | "vue-composable",
14 | "vue-composables",
15 | "nuxt-3",
16 | "nuxt"
17 | ],
18 | "homepage": "https://vue-use-fixed-header.pages.dev/",
19 | "bugs": {
20 | "url": "https://github.com/smastrom/vue-use-fixed-header/issues"
21 | },
22 | "repository": {
23 | "type": "git",
24 | "url": "https://github.com/smastrom/vue-use-fixed-header.git",
25 | "directory": "packages/vue-use-fixed-header"
26 | },
27 | "license": "MIT",
28 | "author": {
29 | "name": "Simone Mastromattei",
30 | "email": "smastrom@proton.me"
31 | },
32 | "exports": {
33 | ".": {
34 | "import": "./dist/index.js",
35 | "types": "./dist/index.d.ts"
36 | }
37 | },
38 | "module": "dist/index.js",
39 | "types": "dist/index.d.ts",
40 | "files": [
41 | "dist/*"
42 | ],
43 | "scripts": {
44 | "dev": "vite",
45 | "watch": "vite build --watch",
46 | "prebuild": "cp ../../LICENSE ../../README.md .",
47 | "build": "rm -rf dist && vue-tsc && vite build",
48 | "postbuild": "pnpm pack",
49 | "test": "pnpm run test:chrome && pnpm run test:firefox && pnpm run test:container:chrome && pnpm run test:container:firefox",
50 | "test:chrome": "cypress run --component --browser chrome",
51 | "test:firefox": "cypress run --component --browser firefox",
52 | "test:container:chrome": "cypress run --component --browser chrome --env CONTAINER=\"custom\"",
53 | "test:container:firefox": "cypress run --component --browser firefox --env CONTAINER=\"custom\"",
54 | "test:gui": "cypress open --component",
55 | "test:gui:container": "cypress open --component --env CONTAINER=\"custom\""
56 | },
57 | "devDependencies": {
58 | "@types/node": "^20.11.16",
59 | "@vitejs/plugin-vue": "^5.0.3",
60 | "cypress": "^13.6.4",
61 | "cypress-real-events": "^1.11.0",
62 | "cypress-wait-frames": "^0.9.8",
63 | "typescript": "^5.3.3",
64 | "vite": "^5.0.12",
65 | "vite-plugin-dts": "^3.7.2",
66 | "vue": "^3.4.15",
67 | "vue-tsc": "^1.8.27"
68 | }
69 | }
70 |
--------------------------------------------------------------------------------
/playground/components/WithContainer.vue:
--------------------------------------------------------------------------------
1 |
14 |
15 |
16 |
37 |
38 |
39 |
107 |
--------------------------------------------------------------------------------
/playground/components/Header.vue:
--------------------------------------------------------------------------------
1 |
11 |
12 |
13 |
14 |
60 |
61 |
62 |
63 |
165 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |    
2 |
3 | # Vue Use Fixed Header
4 |
5 | Turn your boring fixed header into a smart one with three lines of code.
6 |
7 |
8 |
9 | **Demo:** [Website](https://vue-use-fixed-header.pages.dev/) — **Examples:** [Vue 3](https://stackblitz.com/edit/vitejs-vite-nc7ey2?file=index.html,src%2Fcomponents%2FPage.vue) - [Nuxt 3](https://stackblitz.com/edit/nuxt-starter-zbtjes?file=layouts%2Fdefault.vue)
10 |
11 |
12 |
13 | ## Features
14 |
15 | - **Dead simple** - Write three lines of code and you're ready to go
16 | - **Enjoyable** - When scrolling down, the header is hidden, when scrolling up, the header is shown.
17 | - **Smart** - Behaves as expected on page load, hovering, dropdown navigation, top-reached and reduced motion.
18 | - **Dynamic** - Functionalities are automatically enabled/disabled if your header turns from fixed/sticky to something else or it is hidden at different viewports
19 | - **Flexible** - Works with any scrolling container
20 |
21 |
22 |
23 | ## Installation
24 |
25 | ```bash
26 | pnpm add vue-use-fixed-header
27 | ```
28 |
29 | ```bash
30 | yarn add vue-use-fixed-header
31 | ```
32 |
33 | ```bash
34 | npm i vue-use-fixed-header
35 | ```
36 |
37 |
38 |
39 | ## Usage
40 |
41 | Pass your header's template ref to `useFixedHeader`. Then apply the returned reactive styles. That's it.
42 |
43 | ```vue
44 |
52 |
53 |
54 |
57 |
58 |
59 |
66 | ```
67 |
68 | All you have to do is to set `position: fixed` (or `sticky`) to your header. `useFixedHeader` will take care of the rest.
69 |
70 |
71 |
72 | ## Automatic behavior toggling
73 |
74 | On resize, `useFixedHeader` checks your header's `position` and `display` properties to determine whether its functionalities should be enabled or not.
75 |
76 | _Disabled_ means that no event listeners are attached and the returned styles match an empty object `{}`.
77 |
78 | ### Media queries
79 |
80 | Hence feel free to have code like this, it will just work as expected:
81 |
82 | ```css
83 | .Header {
84 | position: fixed;
85 | }
86 |
87 | /* Will be disabled */
88 | @media (max-width: 768px) {
89 | .Header {
90 | position: relative;
91 | }
92 | }
93 |
94 | /* Same */
95 | @media (max-width: 375px) {
96 | .Header {
97 | display: none;
98 | }
99 | }
100 | ```
101 |
102 | ### Advanced scenarios
103 |
104 | Let's suppose your header in some pages is not fixed/sticky and you're using some reactive logic to determine whether it should be or not.
105 |
106 | You can pass a signal to the `watch` property of `useFixedHeader` to perform a check everytime the value changes:
107 |
108 | ```vue
109 |
120 |
121 |
122 |
131 |
132 | ```
133 |
134 | `useFixedHeader` will automatically toggle functionalities when navigating to/from the _Pricing_ page.
135 |
136 | > You can pass either a `ref` or a `computed` (without `.value`).
137 |
138 |
139 |
140 | ## API
141 |
142 | ```ts
143 | declare function useFixedHeader(
144 | target: Ref | HTMLElement | null
145 | options?: UseFixedHeaderOptions
146 | ): {
147 | styles: Readonly>
148 | isEnter: ComputedRef
149 | isLeave: ComputedRef
150 | }
151 |
152 | interface UseFixedHeaderOptions {
153 | /**
154 | * Scrolling container. Matches `document.documentElement` if `null`.
155 | *
156 | * @default null
157 | */
158 | root: Ref | HTMLElement | null
159 | /**
160 | * Signal without `.value` (ref or computed) to be watched
161 | * for automatic behavior toggling.
162 | *
163 | * @default null
164 | */
165 | watch: Ref | ComputedRef
166 | /**
167 | * Whether to transition `opacity` property from 0 to 1
168 | * and vice versa along with the `transform` property
169 | *
170 | * @default false
171 | */
172 | transitionOpacity: boolean | Ref | ComputedRef
173 | }
174 | ```
175 |
176 |
177 |
178 | ## License
179 |
180 | MIT Licensed - Simone Mastromattei © 2023
181 |
--------------------------------------------------------------------------------
/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 | # Contributor Covenant Code of Conduct
2 |
3 | ## Our Pledge
4 |
5 | We as members, contributors, and leaders pledge to make participation in our
6 | community a harassment-free experience for everyone, regardless of age, body
7 | size, visible or invisible disability, ethnicity, sex characteristics, gender
8 | identity and expression, level of experience, education, socio-economic status,
9 | nationality, personal appearance, race, religion, or sexual identity
10 | and orientation.
11 |
12 | We pledge to act and interact in ways that contribute to an open, welcoming,
13 | diverse, inclusive, and healthy community.
14 |
15 | ## Our Standards
16 |
17 | Examples of behavior that contributes to a positive environment for our
18 | community include:
19 |
20 | - Demonstrating empathy and kindness toward other people
21 | - Being respectful of differing opinions, viewpoints, and experiences
22 | - Giving and gracefully accepting constructive feedback
23 | - Accepting responsibility and apologizing to those affected by our mistakes,
24 | and learning from the experience
25 | - Focusing on what is best not just for us as individuals, but for the
26 | overall community
27 |
28 | Examples of unacceptable behavior include:
29 |
30 | - The use of sexualized language or imagery, and sexual attention or
31 | advances of any kind
32 | - Trolling, insulting or derogatory comments, and personal or political attacks
33 | - Public or private harassment
34 | - Publishing others' private information, such as a physical or email
35 | address, without their explicit permission
36 | - Other conduct which could reasonably be considered inappropriate in a
37 | professional setting
38 |
39 | ## Enforcement Responsibilities
40 |
41 | Community leaders are responsible for clarifying and enforcing our standards of
42 | acceptable behavior and will take appropriate and fair corrective action in
43 | response to any behavior that they deem inappropriate, threatening, offensive,
44 | or harmful.
45 |
46 | Community leaders have the right and responsibility to remove, edit, or reject
47 | comments, commits, code, wiki edits, issues, and other contributions that are
48 | not aligned to this Code of Conduct, and will communicate reasons for moderation
49 | decisions when appropriate.
50 |
51 | ## Scope
52 |
53 | This Code of Conduct applies within all community spaces, and also applies when
54 | an individual is officially representing the community in public spaces.
55 | Examples of representing our community include using an official e-mail address,
56 | posting via an official social media account, or acting as an appointed
57 | representative at an online or offline event.
58 |
59 | ## Enforcement
60 |
61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be
62 | reported to the community leaders responsible for enforcement at
63 | [smastrom@proton.me](mailto:smastrom@proton.me).
64 | All complaints will be reviewed and investigated promptly and fairly.
65 |
66 | All community leaders are obligated to respect the privacy and security of the
67 | reporter of any incident.
68 |
69 | ## Enforcement Guidelines
70 |
71 | Community leaders will follow these Community Impact Guidelines in determining
72 | the consequences for any action they deem in violation of this Code of Conduct:
73 |
74 | ### 1. Correction
75 |
76 | **Community Impact**: Use of inappropriate language or other behavior deemed
77 | unprofessional or unwelcome in the community.
78 |
79 | **Consequence**: A private, written warning from community leaders, providing
80 | clarity around the nature of the violation and an explanation of why the
81 | behavior was inappropriate. A public apology may be requested.
82 |
83 | ### 2. Warning
84 |
85 | **Community Impact**: A violation through a single incident or series
86 | of actions.
87 |
88 | **Consequence**: A warning with consequences for continued behavior. No
89 | interaction with the people involved, including unsolicited interaction with
90 | those enforcing the Code of Conduct, for a specified period of time. This
91 | includes avoiding interactions in community spaces as well as external channels
92 | like social media. Violating these terms may lead to a temporary or
93 | permanent ban.
94 |
95 | ### 3. Temporary Ban
96 |
97 | **Community Impact**: A serious violation of community standards, including
98 | sustained inappropriate behavior.
99 |
100 | **Consequence**: A temporary ban from any sort of interaction or public
101 | communication with the community for a specified period of time. No public or
102 | private interaction with the people involved, including unsolicited interaction
103 | with those enforcing the Code of Conduct, is allowed during this period.
104 | Violating these terms may lead to a permanent ban.
105 |
106 | ### 4. Permanent Ban
107 |
108 | **Community Impact**: Demonstrating a pattern of violation of community
109 | standards, including sustained inappropriate behavior, harassment of an
110 | individual, or aggression toward or disparagement of classes of individuals.
111 |
112 | **Consequence**: A permanent ban from any sort of public interaction within
113 | the community.
114 |
115 | ## Attribution
116 |
117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage],
118 | version 2.0, available at
119 | https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
120 |
121 | Community Impact Guidelines were inspired by [Mozilla's code of conduct
122 | enforcement ladder](https://github.com/mozilla/diversity).
123 |
124 | [homepage]: https://www.contributor-covenant.org
125 |
126 | For answers to common questions about this code of conduct, see the FAQ at
127 | https://www.contributor-covenant.org/faq. Translations are available at
128 | https://www.contributor-covenant.org/translations.
129 |
--------------------------------------------------------------------------------
/packages/vue-use-fixed-header/src/useFixedHeader.ts:
--------------------------------------------------------------------------------
1 | import {
2 | shallowRef,
3 | ref,
4 | unref,
5 | watch,
6 | computed,
7 | readonly,
8 | type ComputedRef,
9 | type CSSProperties as CSS,
10 | } from 'vue'
11 |
12 | import { useReducedMotion, isBrowser } from './utils'
13 | import { TRANSITION_STYLES } from './constants'
14 |
15 | import type { UseFixedHeaderOptions, MaybeTemplateRef } from './types'
16 |
17 | enum State {
18 | READY,
19 | ENTER,
20 | LEAVE,
21 | }
22 |
23 | export function useFixedHeader(
24 | target: MaybeTemplateRef,
25 | options: Partial = {},
26 | ): {
27 | styles: Readonly
28 | isLeave: ComputedRef
29 | isEnter: ComputedRef
30 | } {
31 | // Config
32 |
33 | const { enterStyles, leaveStyles } = TRANSITION_STYLES
34 |
35 | const isReduced = useReducedMotion()
36 |
37 | // State
38 |
39 | const internal = {
40 | resizeObserver: undefined as ResizeObserver | undefined,
41 | initResizeObserver: false,
42 | isListeningScroll: false,
43 | isHovering: false,
44 | }
45 |
46 | const styles = shallowRef({})
47 | const state = ref(State.READY)
48 |
49 | const setStyles = (newStyles: CSS) => (styles.value = newStyles)
50 | const removeStyles = () => (styles.value = {})
51 | const setState = (newState: State) => (state.value = newState)
52 |
53 | // Utils
54 |
55 | function getRoot() {
56 | const _root = unref(options.root)
57 | if (_root != null) return _root
58 |
59 | return document.documentElement
60 | }
61 |
62 | const getScrollTop = () => getRoot().scrollTop
63 |
64 | function getScrollRoot() {
65 | const root = getRoot()
66 | return root === document.documentElement ? document : root
67 | }
68 |
69 | function isFixed() {
70 | const el = unref(target)
71 | if (!el) return false
72 |
73 | const { position, display } = window.getComputedStyle(el)
74 | return (position === 'fixed' || position === 'sticky') && display !== 'none'
75 | }
76 |
77 | function getHeaderHeight() {
78 | const el = unref(target)
79 | if (!el) return 0
80 |
81 | let headerHeight = el.scrollHeight
82 |
83 | const { marginTop, marginBottom } = window.getComputedStyle(el)
84 | headerHeight += Number.parseFloat(marginTop) + Number.parseFloat(marginBottom)
85 |
86 | return headerHeight
87 | }
88 |
89 | // Callbacks
90 |
91 | /**
92 | * Resize observer is added wheter or not the header is fixed/sticky
93 | * as it is in charge of toggling scroll/pointer listeners if it
94 | * turns from fixed/sticky to something else and vice-versa.
95 | */
96 | function addResizeObserver() {
97 | internal.resizeObserver = new ResizeObserver(() => {
98 | // Skip the initial call
99 | if (!internal.initResizeObserver) return (internal.initResizeObserver = true)
100 | toggleListeners()
101 | })
102 |
103 | internal.resizeObserver.observe(getRoot())
104 | }
105 |
106 | function onVisible() {
107 | if (state.value === State.ENTER) return
108 |
109 | removeTransitionListener()
110 |
111 | setStyles({
112 | ...enterStyles,
113 | ...(unref(options.transitionOpacity) ? { opacity: 1 } : {}),
114 | visibility: '' as CSS['visibility'],
115 | })
116 |
117 | setState(State.ENTER)
118 | }
119 |
120 | function onHidden() {
121 | if (state.value === State.LEAVE) return
122 |
123 | setStyles({ ...leaveStyles, ...(unref(options.transitionOpacity) ? { opacity: 0 } : {}) })
124 |
125 | setState(State.LEAVE)
126 |
127 | addTransitionListener()
128 | }
129 |
130 | // Transition Events
131 |
132 | function onTransitionEnd(e: TransitionEvent) {
133 | removeTransitionListener()
134 |
135 | if (!unref(target) || e.target !== unref(target) || e.propertyName !== 'transform') return
136 |
137 | /**
138 | * In some edge cases this might be called when the header
139 | * is visible, so we need to check the transform value.
140 | */
141 | const { transform } = window.getComputedStyle(unref(target)!)
142 | if (transform === 'matrix(1, 0, 0, 1, 0, 0)') return // translateY(0px)
143 |
144 | setStyles({
145 | ...leaveStyles,
146 | visibility: 'hidden',
147 | })
148 | }
149 |
150 | function addTransitionListener() {
151 | const el = unref(target)
152 | if (!el) return
153 |
154 | el.addEventListener('transitionend', onTransitionEnd as EventListener)
155 | }
156 |
157 | function removeTransitionListener() {
158 | const el = unref(target)
159 | if (!el) return
160 |
161 | el.removeEventListener('transitionend', onTransitionEnd as EventListener)
162 | }
163 |
164 | // Scroll Events
165 |
166 | function createScrollHandler() {
167 | let prevTop = isBrowser ? getScrollTop() : 0
168 |
169 | return () => {
170 | const scrollTop = getScrollTop()
171 |
172 | const isTopReached = scrollTop <= getHeaderHeight()
173 | const isScrollingUp = scrollTop < prevTop
174 | const isScrollingDown = scrollTop > prevTop
175 |
176 | const step = Math.abs(scrollTop - prevTop)
177 |
178 | if (isTopReached) return onVisible()
179 | if (step < 10) return
180 |
181 | if (!internal.isHovering) {
182 | if (isScrollingUp) {
183 | onVisible()
184 | } else if (isScrollingDown) {
185 | onHidden()
186 | }
187 | }
188 |
189 | prevTop = scrollTop
190 | }
191 | }
192 |
193 | const onScroll = createScrollHandler()
194 |
195 | function addScrollListener() {
196 | getScrollRoot().addEventListener('scroll', onScroll, { passive: true })
197 | internal.isListeningScroll = true
198 | }
199 |
200 | function removeScrollListener() {
201 | getScrollRoot().removeEventListener('scroll', onScroll)
202 | internal.isListeningScroll = false
203 | }
204 |
205 | // Pointer Events
206 |
207 | const onPointerEnter = () => (internal.isHovering = true)
208 | const onPointerLeave = () => (internal.isHovering = false)
209 |
210 | function addPointerListener() {
211 | unref(target)?.addEventListener('pointerenter', onPointerEnter)
212 | unref(target)?.addEventListener('pointerleave', onPointerLeave)
213 | }
214 |
215 | function removePointerListener() {
216 | unref(target)?.removeEventListener('pointerenter', onPointerEnter)
217 | unref(target)?.removeEventListener('pointerleave', onPointerLeave)
218 | }
219 |
220 | // Listeners
221 |
222 | function toggleListeners() {
223 | const isValid = isFixed()
224 |
225 | if (internal.isListeningScroll) {
226 | // If the header is not anymore fixed or sticky
227 | if (!isValid) {
228 | removeListeners()
229 | removeStyles()
230 | }
231 | // If was not listening and now is fixed or sticky
232 | } else {
233 | if (isValid) {
234 | addScrollListener()
235 | addPointerListener()
236 | }
237 | }
238 | }
239 |
240 | function removeListeners() {
241 | removeScrollListener()
242 | removePointerListener()
243 | }
244 |
245 | isBrowser &&
246 | watch(
247 | () => [unref(target), getRoot(), isReduced.value, unref(options.watch)],
248 | ([headerEl, rootEl, isReduced], _, onCleanup) => {
249 | const shouldInit = !isReduced && headerEl && (rootEl || rootEl === null)
250 |
251 | if (shouldInit) {
252 | addResizeObserver()
253 | toggleListeners()
254 | }
255 |
256 | onCleanup(() => {
257 | removeListeners()
258 | removeStyles()
259 | internal.resizeObserver?.disconnect()
260 | internal.initResizeObserver = false
261 | })
262 | },
263 | { immediate: true, flush: 'post' },
264 | )
265 |
266 | return {
267 | styles: readonly(styles),
268 | isLeave: computed(() => state.value === State.LEAVE),
269 | isEnter: computed(() => state.value === State.ENTER),
270 | }
271 | }
272 |
--------------------------------------------------------------------------------