From 3a3454756d8fb04830d6009d986d094ac1b58d03 Mon Sep 17 00:00:00 2001 From: Martin Trapp <94928215+martrapp@users.noreply.github.com> Date: Wed, 28 Aug 2024 14:05:11 +0200 Subject: [PATCH] initial --- .changeset/README.md | 8 + .changeset/config.json | 11 + .changeset/cyan-cars-explain.md | 5 + .github/FUNDING.yml | 3 + .github/ISSUE_TEMPLATE/bug-report.yml | 42 +++ .github/ISSUE_TEMPLATE/config.yml | 5 + .github/ISSUE_TEMPLATE/feature-request.yml | 19 + .github/PULL_REQUEST_TEMPLATE.md | 14 + .github/dependabot.yml | 19 + .github/workflows/publish.yml | 34 ++ .github/workflows/release.yml | 25 ++ .github/workflows/run-checks.yml | 35 ++ .github/workflows/run-tests.yml | 33 ++ .gitignore | 2 + .npmignore | 0 .prettierrc.cjs | 9 + CHANGELOG.md | 7 + README.md | 16 + bin/bundle | 9 + bin/test | 3 + eslint.config.mjs | 11 + package.json | 48 +++ src/dom-view-transisions-level2.d.ts | 21 ++ src/index.ts | 405 +++++++++++++++++++++ tsconfig.json | 110 ++++++ 25 files changed, 894 insertions(+) create mode 100644 .changeset/README.md create mode 100644 .changeset/config.json create mode 100644 .changeset/cyan-cars-explain.md create mode 100644 .github/FUNDING.yml create mode 100644 .github/ISSUE_TEMPLATE/bug-report.yml create mode 100644 .github/ISSUE_TEMPLATE/config.yml create mode 100644 .github/ISSUE_TEMPLATE/feature-request.yml create mode 100644 .github/PULL_REQUEST_TEMPLATE.md create mode 100644 .github/dependabot.yml create mode 100644 .github/workflows/publish.yml create mode 100644 .github/workflows/release.yml create mode 100644 .github/workflows/run-checks.yml create mode 100644 .github/workflows/run-tests.yml create mode 100644 .gitignore create mode 100644 .npmignore create mode 100644 .prettierrc.cjs create mode 100644 CHANGELOG.md create mode 100644 README.md create mode 100755 bin/bundle create mode 100755 bin/test create mode 100644 eslint.config.mjs create mode 100644 package.json create mode 100644 src/dom-view-transisions-level2.d.ts create mode 100644 src/index.ts create mode 100644 tsconfig.json diff --git a/.changeset/README.md b/.changeset/README.md new file mode 100644 index 0000000..e5b6d8d --- /dev/null +++ b/.changeset/README.md @@ -0,0 +1,8 @@ +# Changesets + +Hello and welcome! This folder has been automatically generated by `@changesets/cli`, a build tool that works +with multi-package repos, or single-package repos to help you version and publish your code. You can +find the full documentation for it [in our repository](https://github.com/changesets/changesets) + +We have a quick list of common questions to get you started engaging with this project in +[our documentation](https://github.com/changesets/changesets/blob/main/docs/common-questions.md) diff --git a/.changeset/config.json b/.changeset/config.json new file mode 100644 index 0000000..ae82eba --- /dev/null +++ b/.changeset/config.json @@ -0,0 +1,11 @@ +{ + "$schema": "https://unpkg.com/@changesets/config@3.0.2/schema.json", + "changelog": "@changesets/cli/changelog", + "commit": false, + "fixed": [], + "linked": [], + "access": "restricted", + "baseBranch": "main", + "updateInternalDependencies": "patch", + "ignore": [] +} diff --git a/.changeset/cyan-cars-explain.md b/.changeset/cyan-cars-explain.md new file mode 100644 index 0000000..1a3d1d6 --- /dev/null +++ b/.changeset/cyan-cars-explain.md @@ -0,0 +1,5 @@ +--- +'@vtbag/element-crossing': patch +--- + +PRovides the first version of the element crossing diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 0000000..212231a --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1,3 @@ +# These are supported funding model platforms + +github: martrapp diff --git a/.github/ISSUE_TEMPLATE/bug-report.yml b/.github/ISSUE_TEMPLATE/bug-report.yml new file mode 100644 index 0000000..599c324 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug-report.yml @@ -0,0 +1,42 @@ +name: "\U0001F41B Bug Report" +description: Report an issue or possible bug +labels: [] +assignees: [] +body: + - type: markdown + attributes: + value: | + ## Quick Checklist + Thank you for taking the time to file a bug report! Please fill out this form as completely as possible. + + ✅ I am using the **latest version of the Bag of Tricks** + ✅ I have searched all issues here to see if this has already been reported + - type: textarea + id: bug-description + attributes: + label: Describe the Bug + description: A clear and concise description of what the bug is. + validations: + required: true + - type: textarea + id: bug-expectation + attributes: + label: What's the expected result? + description: Describe what you expect to happen. + validations: + required: true + - type: input + id: bug-reproduction + attributes: + label: Link to Minimal Reproducible Example + description: '**A minimal reproduction is required** so that others can help debug your issue.' + placeholder: 'https://github.com/you/your-minimal-repo' + validations: + required: true + - type: checkboxes + id: will-pr + attributes: + label: Participation + options: + - label: I am willing to submit a pull request for this issue. + required: false diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000..3f06907 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,5 @@ +blank_issues_enabled: false +contact_links: + - name: GitHub Discussions + url: https://github.com/vtbag/element-crossing/discussions + about: Does the issue involve a lot of explanation, or are you not sure how it can be split into actionable tasks? Consider starting a discussion first. diff --git a/.github/ISSUE_TEMPLATE/feature-request.yml b/.github/ISSUE_TEMPLATE/feature-request.yml new file mode 100644 index 0000000..2faa183 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature-request.yml @@ -0,0 +1,19 @@ +name: "✨ Feature Request" +description: Want to see new functionalities? Use this link. +labels: [enhancement] +assignees: [] +body: + - type: textarea + id: feature-description + attributes: + label: Describe the Request + description: A clear and concise description of what the new feature should be. + validations: + required: true + - type: checkboxes + id: will-pr + attributes: + label: Participation + options: + - label: I am willing to contribute a PR to make this happen. + required: false diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..42a353e --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,14 @@ + +### Description + + - Summarize your changes in one or two sentences. + - Don't forget `npm changeset` + +### Tests + +- How was this change tested? + + +### Docs & Examples + +- Does your change here require changes to the vtbag-website? diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..8fdbd6e --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,19 @@ +# To get started with Dependabot version updates, you'll need to specify which +# package ecosystems to update and where the package manifests are located. +# Please see the documentation for all configuration options: +# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates + +version: 2 +updates: + + # Maintain dependencies for GitHub Actions + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "monthly" + + # Maintain dependencies for npm + - package-ecosystem: "npm" + directory: "/" + schedule: + interval: "monthly" diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml new file mode 100644 index 0000000..7e3c512 --- /dev/null +++ b/.github/workflows/publish.yml @@ -0,0 +1,34 @@ +name: Publish Package to npmjs +on: + workflow_dispatch: + inputs: + options: + description: 'Publish options' + required: true + default: '--dry-run' + type: choice + options: + - '--dry-run' + - '--provenance --access public' + - '--provenance --access public --tag preview' + +jobs: + build: + runs-on: ubuntu-latest + permissions: + contents: read + id-token: write + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: '18.x' + registry-url: 'https://registry.npmjs.org' + scope: '@vtbag' + - run: npm install -g npm + - run: npm ci + - run: npm run build + - run: npm publish ${OPTIONS} + env: + OPTIONS: ${{ inputs.options }} + NODE_AUTH_TOKEN: ${{ secrets.VTBAG_NPM_TOKEN }} diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..2963570 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,25 @@ +name: Release +on: + push: + branches: + - main +concurrency: ${{ github.workflow }}-${{ github.ref }} + +jobs: + release: + if: github.repository == 'vtbag/element-crossing' + permissions: + contents: write + pull-requests: write + name: Release + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 18 + - run: npm ci + - name: Create Release Pull Request + uses: changesets/action@v1 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/run-checks.yml b/.github/workflows/run-checks.yml new file mode 100644 index 0000000..b8d6e5c --- /dev/null +++ b/.github/workflows/run-checks.yml @@ -0,0 +1,35 @@ +name: Run Checks + +on: + workflow_dispatch: + pull_request: + branches: [ main ] + +jobs: + test: + name: Test + runs-on: ubuntu-latest + strategy: + matrix: + node-version: + - '18.x' + - '20.x' + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Setup Node + uses: actions/setup-node@v4 + with: + node-version: ${{ matrix.node-version }} + + - name: Install dependencies + run: npm ci + + - name: Prepare tests + run: npx playwright install --with-deps + + - name: Run tests + run: npm test + + \ No newline at end of file diff --git a/.github/workflows/run-tests.yml b/.github/workflows/run-tests.yml new file mode 100644 index 0000000..ffd0bae --- /dev/null +++ b/.github/workflows/run-tests.yml @@ -0,0 +1,33 @@ + +name: Run Tests + +on: + workflow_dispatch: + push: + branches: [ main ] + +jobs: + test: + name: Test + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Setup Node + uses: actions/setup-node@v4 + with: + node-version: "18" + cache: npm + cache-dependency-path: ./package-lock.json + + - name: Install dependencies + run: npm ci + - name: Build + run: npm run build + - name: Prepare tests + run: npx playwright install --with-deps + + - name: Run tests + run: npm test + diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..491fc35 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +node_modules +lib diff --git a/.npmignore b/.npmignore new file mode 100644 index 0000000..e69de29 diff --git a/.prettierrc.cjs b/.prettierrc.cjs new file mode 100644 index 0000000..7bc67c1 --- /dev/null +++ b/.prettierrc.cjs @@ -0,0 +1,9 @@ +/** @type {import("@types/prettier").Options} */ +module.exports = { + printWidth: 100, + semi: true, + singleQuote: true, + tabWidth: 2, + trailingComma: 'es5', + useTabs: true, +}; diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..03f1daa --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,7 @@ +# @vtbag/element-crossing + +## 0.0.0 - 2024-08-28 + +### Patch Changes + +- 4d89b41: Initial release diff --git a/README.md b/README.md new file mode 100644 index 0000000..c2559b6 --- /dev/null +++ b/README.md @@ -0,0 +1,16 @@ +# ElementCrossing +Preserve what matters across document transitions! + +![Build Status](https://github.com/vtbag/element-crossing/actions/workflows/run-tests.yml/badge.svg) +[![npm version](https://img.shields.io/npm/v/@vtbag/element-crossing/latest)](https://www.npmjs.com/package/@vtbag/element-crossing) +[![NPM Downloads](https://img.shields.io/npm/dw/@vtbag/element-crossing)](https://www.npmjs.com/package/@vtbag/element-crossing) + +The @vtbag website can be found at https://vtbag.pages.dev/ + +## !!! News !!! + +## What happened so far: + +## What is it? + +This library provides a robust solution for maintaining HTML elements and their associated states across cross-document view transitions. It is designed to enhance the user experience by ensuring that important elements and their current states are preserved as users navigate through different pages or documents. diff --git a/bin/bundle b/bin/bundle new file mode 100755 index 0000000..b4c03e5 --- /dev/null +++ b/bin/bundle @@ -0,0 +1,9 @@ +#! /bin/sh + +if [ "$1" = "dev" ]; then + OPTS="--sourcemap --watch" +else + OPTS="--minify" + (cd lib && rm *.js.map) >> /dev/null 2>&1 +fi +npx esbuild src/index.ts --bundle $OPTS --target=ESnext --outfile=lib/index.js diff --git a/bin/test b/bin/test new file mode 100755 index 0000000..66d2f42 --- /dev/null +++ b/bin/test @@ -0,0 +1,3 @@ +#! /bin/sh + +echo "see @vtbag/website" \ No newline at end of file diff --git a/eslint.config.mjs b/eslint.config.mjs new file mode 100644 index 0000000..65ab40d --- /dev/null +++ b/eslint.config.mjs @@ -0,0 +1,11 @@ +import globals from "globals"; +import pluginJs from "@eslint/js"; +import tseslint from "typescript-eslint"; + + +export default [ + {files: ["src/**/*.{js,mjs,cjs,ts}"]}, + {languageOptions: { globals: globals.browser }}, + pluginJs.configs.recommended, + ...tseslint.configs.recommended, +]; \ No newline at end of file diff --git a/package.json b/package.json new file mode 100644 index 0000000..cfaf4ca --- /dev/null +++ b/package.json @@ -0,0 +1,48 @@ +{ + "name": "@vtbag/element-crossing", + "version": "1.0.0", + "main": "lib/index.js", + "description": "Sites using cross-document view transitions look like SPAs but they still do full page loads on navigation. The element crossing provides a way to preserve DOM elements and data objects across page loads.", + "files": [ + "lib/index.js" + ], + "scripts": { + "dev": "bin/bundle dev", + "build": "npm run format; bin/bundle", + "format": "prettier --write src | grep -v 'unchanged)$'", + "test": "bin/test", + "changeset": "changeset", + "release": "changeset publish" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/vtbag/element-crossing.git" + }, + "keywords": [ + "view", + "transitions", + "view transition", + "view-transition", + "preserve","state", + "cross-document", + "DOM" + ], + "author": "vtbag", + "license": "ISC", + "bugs": { + "url": "https://github.com/vtbag/element-crossing/issues" + }, + "homepage": "https://vtbag.pages.dev", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/martrapp" + }, + "devDependencies": { + "@changesets/cli": "^2.27.7", + "@eslint/js": "^9.9.0", + "@types/dom-view-transitions": "^1.0.5", + "esbuild": "^0.23.0", + "prettier": "^3.3.3", + "typescript": "^5.5.4" + } +} diff --git a/src/dom-view-transisions-level2.d.ts b/src/dom-view-transisions-level2.d.ts new file mode 100644 index 0000000..1393780 --- /dev/null +++ b/src/dom-view-transisions-level2.d.ts @@ -0,0 +1,21 @@ +declare global { + interface PageSwapEvent extends Event { + viewTransition: ViewTransition; + } + + interface PageRevealEvent extends Event { + viewTransition: ViewTransition; + } + + interface WindowEventMap { + pageswap: PageSwapEvent; + pagereveal: PageRevealEvent; + } + + interface AnimationEffect { + target: HTMLElement; + pseudoElement?: string; + getKeyframes: () => Keyframe[]; + } +} +export {}; diff --git a/src/index.ts b/src/index.ts new file mode 100644 index 0000000..9df8a03 --- /dev/null +++ b/src/index.ts @@ -0,0 +1,405 @@ +//@ts-ignore +import bench from './bench.txt'; + +import { setTransitionNames } from './stylesheets'; +import { initDragging } from './dragging'; +import { showReopener, STANDBY } from './reopener'; +import { Modus, updateMessage } from './panel/modus'; +import { addFrames } from './styles'; +import { + clearVtActive, + exitViewTransition, + mayViewTransition, + setVtActive, + vtActive, +} from './panel/transition'; +import { initSlowMotion, setupSlowMotionPlay } from './panel/slow-motion'; +import { controlledPlay, initController } from './panel/full-control'; +import { + forceAnimations, + retrieveViewTransitionAnimations, + unleashAllAnimations, +} from './animations'; +import { initNames, updateImageVisibility, updateNames } from './panel/names'; +import { initFilter } from './panel/filter'; +import { twinClick } from './twin'; +import { DEBUG } from './panel/debug'; +import { initInnerPanel, mayCloseInner, mightHideMode } from './panel/inner'; +import { getModus, setModus } from './panel/modus'; + +const ORIENTATION = 'vtbag-ui-panel-orientation'; +const FRAMED = 'vtbag-ui-framed'; +const NAMED_ONLY = 'named_only'; +const titleLogo = '🔬'; + +top!.__vtbag ??= {}; +top!.__vtbag.inspectionChamber ??= {}; +const inspectionChamber = top!.__vtbag.inspectionChamber!; + +if (top === self) { + top.setTimeout(initPanel, 500); +} else { + initSpecimen(); +} + +function initSpecimen() { + const frameDocument = (inspectionChamber.frameDocument = self.document); + + self.addEventListener('pageswap', pageSwap, { once: true }); + self.addEventListener('pagereveal', prePageReveal, { once: true }); + monkeyPatchStartViewTransition(); + + function monkeyPatchStartViewTransition() { + const originalStartViewTransition = frameDocument.startViewTransition; + if ( + originalStartViewTransition.toString() !== 'function startViewTransition() { [native code] }' + ) + return; + // todo: add level 2 options + frameDocument.startViewTransition = (cb: () => void | Promise) => { + '@vtbag'; + pageSwap(); + inspectionChamber.viewTransition = originalStartViewTransition.call( + frameDocument, + async () => { + await Promise.resolve(); + await cb(); + pageReveal(); + } + ); + return inspectionChamber.viewTransition; + }; + } +} + +function pageSwap() { + DEBUG && console.log('pageSwap'); + inspectionChamber.glow?.cancel(); + addFrames(false, false); +} + +function prePageReveal(e: Event) { + inspectionChamber.viewTransition = + ('viewTransition' in e && (e.viewTransition as ViewTransition)) || undefined; + pageReveal(); +} +function pageReveal() { + DEBUG && console.log('pageReveal'); + if (inspectionChamber.viewTransition) { + forceAnimations(); + beforeUpdateCallbackDone(); + } +} + +function beforeUpdateCallbackDone() { + setVtActive(); + const root = top!.document.documentElement; + const viewTransition = inspectionChamber.viewTransition!; + const modusFunction: Record void> = { + bypass: () => {}, + 'slow-motion': setupSlowMotionPlay, + 'full-control': controlledPlay, + compare: () => {}, + }; + const modus = getModus(); + + viewTransition.updateCallbackDone.catch(() => {}); + + viewTransition.ready + .then(async () => { + if (modus && modus !== 'bypass') { + const canvas = top!.document.querySelector('#canvas')!; + const timeoutId = top!.setTimeout(() => (canvas.style.zIndex = '1000'), 300); + try { + await retrieveViewTransitionAnimations(); + addFrames( + !!top!.document.querySelector('#vtbag-ui-framed')?.checked, + !!top!.document.querySelector('#vtbag-ui-named-only')?.checked + ); + inspectionChamber.twin!.ownerDocument.addEventListener('click', twinClick); + } finally { + top!.clearTimeout(timeoutId); + top!.document.querySelector('#canvas')!.style.zIndex = ''; + } + modusFunction[modus](); + } + top!.history.replaceState(history.state, '', self.location.href); + top!.document.title = titleLogo + ' ' + self.document.title; + }) + .finally(() => {}); + + viewTransition!.finished.finally(() => { + clearVtActive(); + inspectionChamber.viewTransition = undefined; + inspectionChamber.frameDocument?.querySelector('#vtbag-twin--view-transition')?.remove(); + unleashAllAnimations(); + inspectionChamber.animations = undefined; + inspectionChamber.longestAnimation = undefined; + addFrames( + !!top!.document.querySelector('#vtbag-ui-framed')?.checked, + !!top!.document.querySelector('#vtbag-ui-named-only')?.checked + ); + updateNames(setTransitionNames()); + updateImageVisibility(); + top!.document.querySelector('#vtbag-ui-slo-mo-progress')!.innerText = ''; + top!.document.querySelector('#vtbag-ui-animations')!.innerText = ''; + !getModus() && top!.document.querySelector('#vtbag-ui-modi li input')?.click(); + inspectionChamber.frameDocument!.addEventListener('click', innerClick); + mayCloseInner(); + }); +} + +function setBackgroundAccent() { + const root = top!.document.documentElement; + root.style.setProperty( + '--vtbag-background-accent', + root.style.colorScheme.startsWith('dark') ? '#4E545D' : '#c6d1d7' + ); +} + +function setTutorialMode() { + const toggle = top!.document.querySelector('#vtbag-tutorial-mode')!; + toggle.checked = localStorage.getItem('vtbag-tutorial-mode') !== 'false'; + toggle.addEventListener('change', () => { + localStorage.setItem('vtbag-tutorial-mode', '' + toggle.checked); + const openedMessages = top!.document.querySelector( + '#vtbag-ui-inner-panel #vtbag-ui-messages h4' + ); + const closedMessages = top!.document.querySelector( + '#vtbag-ui-panel #vtbag-ui-messages h4' + ); + if (!toggle.checked && openedMessages) { + openedMessages.click(); + } + if (toggle.checked && closedMessages) { + closedMessages.click(); + } + }); +} + +async function initPanel() { + if (top!.document.querySelector('#vtbag-ui-panel')) return; + + const root = top!.document.documentElement; + if (top!.sessionStorage.getItem(STANDBY) === 'true') { + showReopener(); + return; + } + const colorScheme = top!.getComputedStyle(root).colorScheme; + const docTitle = top!.document.title; + const icon = top!.document.querySelector('link[rel="icon"]')?.outerHTML ?? ''; + + const page = bench + .replace( + '', + `` + ) + .replace('', `${titleLogo} ${docTitle}`) + .replace(``, icon); + + top!.addEventListener('resize', setOrientation); + root.innerHTML = page; + root.style.colorScheme = colorScheme; + setOrientation(); + setBackgroundAccent(); + setTutorialMode(); + setModus(); + const mainFrame = top!.document.querySelector('#vtbag-main-frame')!; + await new Promise((r) => (mainFrame.onload = r)); + + if (!top!.document.startViewTransition) { + top!.document.querySelector('#vtbag-ui-messages')!.innerHTML = ` +

I'm sorry!

Native view transitions are required to make the 🔬 Inspection Chamber work, but they are not supported by this browser.

+

Sadly have to give up.

`; + top!.document + .querySelectorAll( + '#vtbag-ui-modi, #vtbag-ui-filter, #vtbag-ui-names, #vtbag-ui-animations, #vtbag-ui-info' + ) + .forEach((e) => e.remove()); + return; + } + const frameDocument = (top!.__vtbag.inspectionChamber!.frameDocument = + mainFrame.contentDocument!); + + updateNames(setTransitionNames()); + initPanelHandlers(); + const divider = top!.document.querySelector('#divider')!; + initDragging(divider, (clientX, clientY) => { + if (root.classList.contains('vtbag-ui-column')) { + if (root.classList.contains('vtbag-ui-tl')) + root.style.setProperty( + '--vtbag-panel-width', + `calc(max(200px, ${Math.min(innerWidth - 100, clientX)}px))` + ); + else + root.style.setProperty( + '--vtbag-panel-width', + `calc(max(200px, 100vw - ${Math.max(100, clientX + 1)}px))` + ); + } else { + if (root.classList.contains('vtbag-ui-tl')) + root.style.setProperty( + '--vtbag-panel-height', + `calc(max(212px, ${Math.min(innerHeight - 100, clientY)}px))` + ); + else + root.style.setProperty( + '--vtbag-panel-height', + `calc(max(212px, 100vh - ${Math.max(100, clientY + 1)}px))` + ); + } + }); + if (localStorage.getItem('vtbag-tutorial-mode') !== 'false') { + top!.document.querySelector('#vtbag-ui-messages h4')!.click(); + } + mainFrame.animate([{ opacity: 0, transform: 'translateY(100vh)' }, { opacity: 1 }], { + duration: 500, + fill: 'forwards', + }); + frameDocument!.addEventListener('click', innerClick); +} + +function innerClick(e: MouseEvent) { + if (vtActive()) return; + const target = e.target as HTMLElement; + const vt = target.closest('[data-vtbag-transition-name]'); + if (vt) { + const name = vt.dataset.vtbagTransitionName; + top!.document.querySelectorAll('#vtbag-ui-names li').forEach((li) => { + if (li.innerText === name) { + li.click(); + if (e.ctrlKey && e.shiftKey) e.preventDefault(); + } + }); + } +} + +function setOrientation() { + const html = top!.document.documentElement; + const panelOrientation = top!.localStorage.getItem(ORIENTATION) ?? ''; + if (panelOrientation) { + panelOrientation.split(' ').forEach((c) => html.classList.add(c)); + updateTurner(); + } else { + if ( + top!.matchMedia('(orientation: landscape)').matches !== + html.classList.contains('vtbag-ui-column') + ) + switchOrientation(); + } +} + +function switchOrientation() { + // changing the snapshot containing block size skips the transition + mayViewTransition(() => { + const classes = top!.document.documentElement.classList; + exitViewTransition(); + classes.toggle('vtbag-ui-column'); + if (classes.contains('vtbag-ui-column')) { + classes.toggle('vtbag-ui-tl'); + } + top!.localStorage.setItem( + ORIENTATION, + [...classes].filter((c) => c.startsWith('vtbag-ui-')).join(' ') + ); + updateTurner(); + }, 'switch orientation'); +} +function updateTurner() { + const turner = top!.document.querySelector('#vtbag-ui-turn')!; + const classes = top!.document.documentElement.classList; + turner.innerText = '⤪⤨⤩⤧'[ + (classes.contains('vtbag-ui-column') ? 2 : 0) + (classes.contains('vtbag-ui-tl') ? 1 : 0) + ]; +} +function initPanelHandlers() { + const turner = top!.document.querySelector('#vtbag-ui-turn')!; + turner.addEventListener('click', () => switchOrientation()); + + top!.document.querySelector('#vtbag-ui-light-dark')!.addEventListener('click', () => { + const rootStyle = top!.document.documentElement.style; + top!.document.querySelector( + '#vtbag-main-frame' + )!.contentDocument!.documentElement.style.colorScheme = rootStyle.colorScheme = + rootStyle.colorScheme.startsWith('dark') ? 'light' : 'dark'; + setBackgroundAccent(); + }); + + initInnerPanel(); + + top!.document.querySelector('#vtbag-ui-standby')!.addEventListener('click', () => { + top!.sessionStorage.setItem(STANDBY, 'true'); + top!.location.reload(); + }); + top!.document.querySelector('#vtbag-ui-modi ul')!.addEventListener('change', updateModus); + + initFilter(); + initNames(); + const framedCheck = top!.document.querySelector('#vtbag-ui-framed')!; + const namedOnlyCheck = top!.document.querySelector('#vtbag-ui-named-only')!; + framedCheck.addEventListener('change', frameChange); + namedOnlyCheck.addEventListener('change', frameChange); + + function frameChange() { + const framed = framedCheck.checked; + const namedOnly = namedOnlyCheck.checked; + top!.sessionStorage.setItem(FRAMED, framed ? 'X' : ''); + top!.sessionStorage.setItem(NAMED_ONLY, namedOnly ? 'X' : ''); + addFrames(framed, namedOnly); + } + + initSlowMotion(); + initController(); + top!.document + .querySelectorAll('#vtbag-ui-control-exit, #vtbag-ui-control-play') + .forEach((e) => e.addEventListener('click', exitViewTransition)); + + top!.addEventListener('keyup', function (e) { + if (e.key === 'Escape') { + if (vtActive()) { + exitViewTransition(); + } else { + top!.sessionStorage.setItem(STANDBY, 'true'); + top!.location.reload(); + } + } + }); +} + +function updateModus() { + const checked = top!.document.querySelector('#vtbag-ui-modi ul input:checked'); + if (checked) { + const modus = checked.id.replace('vtbag-m-', '') as Modus; + if (modus !== getModus()) { + mayViewTransition(() => { + setModus(modus); + exitViewTransition(); + + top!.document.querySelector('#vtbag-ui-filter ul input')!.click(); + if (modus === 'slow-motion') { + attachFrameToggle('#vtbag-ui-slow-motion'); + } + if (modus === 'full-control') { + attachFrameToggle('#vtbag-ui-control'); + } + if (modus === 'bypass') { + attachFrameToggle('#vtbag-ui-modi'); + } + updateMessage(modus); + mightHideMode(); + }, 'update-modus'); + } + } +} + +function attachFrameToggle(divId: string) { + const framed = top!.document.querySelector('#vtbag-ui-framed')!; + const namedOnly = top!.document.querySelector('#vtbag-ui-named-only')!; + const parent = framed.parentElement; + const div = top!.document.querySelector(divId); + framed.checked = !!top!.sessionStorage.getItem(FRAMED); + namedOnly.checked = !!top!.sessionStorage.getItem(NAMED_ONLY); + addFrames(framed.checked, namedOnly.checked); + + if (parent && div && parent.parentElement !== div) div.insertAdjacentElement('beforeend', parent); +} diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..66c3f62 --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,110 @@ +{ + "include": ["src"], + "exclude": ["node_modules"], + "compilerOptions": { + /* Visit https://aka.ms/tsconfig to read more about this file */ + + /* Projects */ + // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */ + // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ + // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */ + // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */ + // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ + // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ + + /* Language and Environment */ + "target": "ESNext", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ + // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ + // "jsx": "preserve", /* Specify what JSX code is generated. */ + // "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */ + // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */ + // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */ + // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */ + // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */ + // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */ + // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ + // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ + // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */ + + /* Modules */ + "module": "ESNext", /* Specify what module code is generated. */ + // "rootDir": "./", /* Specify the root folder within your source files. */ + // "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */ + // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ + // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ + // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ + // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */ + // "types": [], /* Specify type package names to be included without being referenced in a source file. */ + // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ + // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */ + // "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */ + // "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */ + // "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */ + // "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */ + // "resolveJsonModule": true, /* Enable importing .json files. */ + // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */ + // "noResolve": true, /* Disallow 'import's, 'require's or ''s from expanding the number of files TypeScript should add to a project. */ + + /* JavaScript Support */ + // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */ + // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ + // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */ + + /* Emit */ + //"declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ + // "declarationMap": true, /* Create sourcemaps for d.ts files. */ + // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */ + // "sourceMap": true, /* Create source map files for emitted JavaScript files. */ + // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */ + // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */ + "outDir": "./lib", /* Specify an output folder for all emitted files. */ + // "removeComments": true, /* Disable emitting comments. */ + // "noEmit": true, /* Disable emitting files from a compilation. */ + // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */ + // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */ + // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */ + // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ + // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */ + // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */ + // "newLine": "crlf", /* Set the newline character for emitting files. */ + // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */ + // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */ + // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */ + // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */ + // "declarationDir": "./", /* Specify the output directory for generated declaration files. */ + + /* Interop Constraints */ + // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */ + // "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */ + // "isolatedDeclarations": true, /* Require sufficient annotation on exports so other tools can trivially generate declaration files. */ + // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ + "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */ + // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */ + "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ + + /* Type Checking */ + "strict": true, /* Enable all strict type-checking options. */ + // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */ + // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */ + // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */ + // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */ + // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */ + // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */ + // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */ + // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */ + // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */ + // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */ + // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */ + // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */ + // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */ + // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */ + // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */ + // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */ + // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */ + // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */ + + /* Completeness */ + // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ + "skipLibCheck": true /* Skip type checking all .d.ts files. */ + } +}