diff --git a/.eslintignore b/.eslintignore new file mode 100644 index 00000000..7c25c8ac --- /dev/null +++ b/.eslintignore @@ -0,0 +1,14 @@ +build +app/renderer +app/static +app/bin +app/dist +app/node_modules +app/typings +assets +website +bin +dist +target +cache +schema.json \ No newline at end of file diff --git a/.eslintrc.json b/.eslintrc.json new file mode 100644 index 00000000..1fa89a98 --- /dev/null +++ b/.eslintrc.json @@ -0,0 +1,161 @@ +{ + "plugins": [ + "react", + "prettier", + "@typescript-eslint", + "eslint-comments", + "lodash", + "import" + ], + "extends": [ + "eslint:recommended", + "plugin:react/recommended", + "plugin:prettier/recommended", + "plugin:eslint-comments/recommended" + ], + "parser": "@typescript-eslint/parser", + "parserOptions": { + "sourceType": "module", + "ecmaFeatures": { + "jsx": true, + "impliedStrict": true, + "experimentalObjectRestSpread": true + }, + "allowImportExportEverywhere": true, + "project": [ + "./tsconfig.eslint.json" + ] + }, + "env": { + "es6": true, + "browser": true, + "node": true + }, + "settings": { + "react": { + "version": "detect" + }, + "import/resolver": { + "typescript": {} + }, + "import/internal-regex": "^(electron|react)$" + }, + "rules": { + "func-names": [ + "error", + "as-needed" + ], + "no-shadow": "error", + "no-extra-semi": 0, + "react/prop-types": 0, + "react/react-in-jsx-scope": 0, + "react/no-unescaped-entities": 0, + "react/jsx-no-target-blank": 0, + "react/no-string-refs": 0, + "prettier/prettier": [ + "error", + { + "printWidth": 120, + "tabWidth": 2, + "singleQuote": true, + "trailingComma": "none", + "bracketSpacing": false, + "semi": true, + "useTabs": false, + "bracketSameLine": false + } + ], + "eslint-comments/no-unused-disable": "error", + "react/no-unknown-property":[ + "error", + { + "ignore": [ + "jsx", + "global" + ] + } + ] + }, + "overrides": [ + { + "files": [ + "**.ts", + "**.tsx" + ], + "extends": [ + "plugin:@typescript-eslint/recommended", + "plugin:@typescript-eslint/recommended-requiring-type-checking", + "prettier" + ], + "rules": { + "@typescript-eslint/explicit-function-return-type": "off", + "@typescript-eslint/explicit-module-boundary-types": "off", + "@typescript-eslint/no-explicit-any": "off", + "@typescript-eslint/no-non-null-assertion": "off", + "@typescript-eslint/prefer-optional-chain": "error", + "@typescript-eslint/ban-types": "off", + "no-shadow": "off", + "@typescript-eslint/no-shadow": ["error"], + "@typescript-eslint/no-unsafe-assignment": "off", + "@typescript-eslint/no-unsafe-member-access": "off", + "@typescript-eslint/restrict-template-expressions": "off", + "@typescript-eslint/consistent-type-imports": [ "error", { "disallowTypeAnnotations": false } ], + "lodash/prop-shorthand": [ "error", "always" ], + "lodash/import-scope": [ "error", "method" ], + "lodash/collection-return": "error", + "lodash/collection-method-value": "error", + "import/no-extraneous-dependencies": "error", + "import/no-anonymous-default-export": "error", + "import/order": [ + "error", + { + "groups": [ + "builtin", + "internal", + "external", + "parent", + "sibling", + "index" + ], + "newlines-between": "always", + "alphabetize": { + "order": "asc", + "orderImportKind": "desc", + "caseInsensitive": true + } + } + ] + } + }, + { + "extends": [ + "plugin:jsonc/recommended-with-json", + "plugin:json-schema-validator/recommended" + ], + "files": [ + "*.json" + ], + "parser": "jsonc-eslint-parser", + "plugins": [ + "jsonc", + "json-schema-validator" + ], + "rules": { + "jsonc/array-element-newline": [ + "error", + "consistent" + ], + "jsonc/array-bracket-newline": [ + "error", + "consistent" + ], + "jsonc/indent": [ + "error", + 2 + ], + "prettier/prettier": "off", + "json-schema-validator/no-invalid": "error" + } + } + ] +} diff --git a/.gitattributes b/.gitattributes index 2e46fbac..97c115ec 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,2 +1,5 @@ * text=auto -*.sh eol=lf +*.js text eol=lf +*.ts text eol=lf +*.tsx text eol=lf +bin/* linguist-vendored diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 00000000..15db91f4 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,34 @@ +--- +name: Bug report +about: Create a report to help Hyper improve +title: '' +labels: '' +assignees: '' + +--- + + + + +- [ ] I am on the [latest](https://github.com/vercel/hyper/releases/latest) Hyper.app version +- [ ] I have searched the [issues](https://github.com/vercel/hyper/issues) of this repo and believe that this is not a duplicate + + + +- **OS version and name**: +- **Hyper.app version**: +- **Link of a [Gist](https://gist.github.com/) with the contents of your hyper.json**: +- **Relevant information from devtools** _(CMD+ALT+I on macOS, CTRL+SHIFT+I elsewhere)_: +- **The issue is reproducible in vanilla Hyper.app**: + +## Issue + diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 00000000..e28a3f4c --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,20 @@ +--- +name: Feature request +about: Suggest an idea/feature for Hyper +title: '' +labels: '' +assignees: '' + +--- + +**Is your feature request related to a problem? Please describe.** +A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] + +**Describe the solution you'd like** +A clear and concise description of what you want to happen. + +**Describe alternatives you've considered** +A clear and concise description of any alternative solutions or features you've considered. + +**Additional context** +Add any other context or screenshots about the feature request here. diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 00000000..20a51554 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,25 @@ +version: 2 +updates: +- package-ecosystem: npm + directory: "/" + schedule: + interval: weekly + time: '11:00' + open-pull-requests-limit: 30 + target-branch: canary + versioning-strategy: increase +- package-ecosystem: npm + directory: "/app" + schedule: + interval: weekly + time: '11:00' + open-pull-requests-limit: 30 + target-branch: canary + versioning-strategy: increase +- package-ecosystem: github-actions + directory: "/" + schedule: + interval: weekly + time: '11:00' + open-pull-requests-limit: 30 + target-branch: canary diff --git a/.github/issue_template.md b/.github/issue_template.md deleted file mode 100644 index 3a4b63d7..00000000 --- a/.github/issue_template.md +++ /dev/null @@ -1,24 +0,0 @@ - - -- [ ] I am on the [latest](https://github.com/zeit/hyper/releases/latest) Hyper.app version -- [ ] I have searched the [issues](https://github.com/zeit/hyper/issues) of this repo and believe that this is not a duplicate - - - -- **OS version and name**: -- **Hyper.app version**: -- **Link of a [Gist](https://gist.github.com/) with the contents of your .hyper.js**: -- **Relevent information from devtools** _(CMD+SHIFT+I on Mac OS, CTRL+SHIFT+I elsewhere)_: -- **The issue is reproducible in vanilla Hyper.app**: - -## Issue - diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index dd4bd28f..31a64d36 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -3,5 +3,6 @@ - To help whoever reviews your PR, it'd be extremely helpful for you to list whether your PR is ready to be merged, If there's anything left to do and if there are any related PRs - It'd also be extremely helpful to enable us to update your PR incase we need to rebase or what-not by checking `Allow edits from maintainers` +- If your PR changes some API, please make a PR for hyper website too: https://github.com/vercel/hyper-site. Thanks, again! --> diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml new file mode 100644 index 00000000..569dda76 --- /dev/null +++ b/.github/workflows/codeql-analysis.yml @@ -0,0 +1,67 @@ +# For most projects, this workflow file will not need changing; you simply need +# to commit it to your repository. +# +# You may wish to alter this file to override the set of languages analyzed, +# or to provide custom queries or build logic. +# +# ******** NOTE ******** +# We have attempted to detect the languages in your repository. Please check +# the `language` matrix defined below to confirm you have the correct set of +# supported CodeQL languages. +# +name: "CodeQL" + +on: + push: + branches: [ canary ] + pull_request: + # The branches below must be a subset of the branches above + branches: [ canary ] + schedule: + - cron: '37 6 * * 5' + +jobs: + analyze: + name: Analyze + runs-on: ubuntu-latest + + strategy: + fail-fast: false + matrix: + language: [ 'javascript' ] + # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python' ] + # Learn more: + # https://docs.github.com/en/free-pro-team@latest/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#changing-the-languages-that-are-analyzed + + steps: + - name: Checkout repository + uses: actions/checkout@v4 + + # Initializes the CodeQL tools for scanning. + - name: Initialize CodeQL + uses: github/codeql-action/init@v3 + with: + languages: ${{ matrix.language }} + # If you wish to specify custom queries, you can do so here or in a config file. + # By default, queries listed here will override any specified in a config file. + # Prefix the list here with "+" to use these queries and those in the config file. + # queries: ./path/to/local/query, your-org/your-repo/queries@main + + # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). + # If this step fails, then you should remove it and run the build manually (see below) + - name: Autobuild + uses: github/codeql-action/autobuild@v3 + + # â„šī¸ Command-line programs to run using the OS shell. + # 📚 https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun + + # âœī¸ If the Autobuild fails above, remove it and uncomment the following three lines + # and modify them (or add more) to build your code if your project + # uses a compiled language + + #- run: | + # make bootstrap + # make release + + - name: Perform CodeQL Analysis + uses: github/codeql-action/analyze@v3 diff --git a/.github/workflows/e2e_comment.yml b/.github/workflows/e2e_comment.yml new file mode 100644 index 00000000..573a4d59 --- /dev/null +++ b/.github/workflows/e2e_comment.yml @@ -0,0 +1,63 @@ +name: Comment e2e test screenshots on PR +on: + workflow_run: + workflows: ['Node CI'] + types: + - completed +jobs: + e2e_comment: + runs-on: ubuntu-latest + if: github.event.workflow_run.event == 'pull_request' + steps: + - name: Dump Workflow run info from GitHub context + env: + WORKFLOW_RUN_INFO: ${{ toJSON(github.event.workflow_run) }} + run: echo "$WORKFLOW_RUN_INFO" + - name: Download Artifacts + uses: dawidd6/action-download-artifact@v3.1.4 + with: + github_token: ${{ secrets.GITHUB_TOKEN }} + workflow: nodejs.yml + run_id: ${{ github.event.workflow_run.id }} + name: e2e + - name: Get PR number + uses: dawidd6/action-download-artifact@v3.1.4 + with: + github_token: ${{ secrets.GITHUB_TOKEN }} + workflow: nodejs.yml + run_id: ${{ github.event.workflow_run.id }} + name: pr_num + - name: Read the pr_num file + id: pr_num_reader + uses: juliangruber/read-file-action@v1.1.7 + with: + path: ./pr_num.txt + - name: List images + run: ls -al + - name: Upload images to imgur + id: upload_screenshots + uses: devicons/public-upload-to-imgur@v2.2.2 + with: + path: ./*.png + client_id: ${{ secrets.IMGUR_CLIENT_ID }} + - name: Comment on the PR + uses: jungwinter/comment@v1 + env: + IMG_MARKDOWN: ${{ join(fromJSON(steps.upload_screenshots.outputs.markdown_urls), '') }} + MESSAGE: | + Hi there, + Thank you for contributing to Hyper! + You can get the build artifacts from [here](https://nightly.link/{1}/actions/runs/{2}). + Here are screenshots of Hyper built from this pr. + {0} + with: + type: create + issue_number: ${{ steps.pr_num_reader.outputs.content }} + token: ${{ secrets.GITHUB_TOKEN }} + body: ${{ format(env.MESSAGE, env.IMG_MARKDOWN, github.repository, github.event.workflow_run.id) }} + - name: Hide older comments + uses: kanga333/comment-hider@v0.4.0 + with: + github_token: ${{ secrets.GITHUB_TOKEN }} + leave_visible: 1 + issue_number: ${{ steps.pr_num_reader.outputs.content }} diff --git a/.github/workflows/nodejs.yml b/.github/workflows/nodejs.yml new file mode 100644 index 00000000..d42e2995 --- /dev/null +++ b/.github/workflows/nodejs.yml @@ -0,0 +1,190 @@ +name: Node CI +on: + push: + branches: + - master + - canary + pull_request: +defaults: + run: + shell: bash +env: + NODE_VERSION: 18.x +jobs: + build: + runs-on: ${{matrix.os}} + strategy: + matrix: + os: + - macos-latest + - ubuntu-latest + - windows-latest + fail-fast: false + steps: + - name: Checkout + uses: actions/checkout@v4 + - name: Use Node.js ${{ env.NODE_VERSION }} + uses: actions/setup-node@v4 + with: + node-version: ${{ env.NODE_VERSION }} + - name: Fix node-gyp and Python + run: python3 -m pip install packaging setuptools + - name: Get yarn cache directory path + id: yarn-cache-dir-path + run: echo "dir=$(yarn cache dir)" >> $GITHUB_OUTPUT + - uses: actions/cache/restore@v4 + with: + path: ${{ steps.yarn-cache-dir-path.outputs.dir }} + key: ${{ runner.os }}-yarn-${{ hashFiles('yarn.lock', 'app/yarn.lock') }} + restore-keys: | + ${{ runner.os }}-yarn- + - name: Install + run: yarn install + env: + npm_config_node_gyp: ${{ github.workspace }}${{ runner.os == 'Windows' && '\node_modules\node-gyp\bin\node-gyp.js' || '/node_modules/node-gyp/bin/node-gyp.js' }} + - name: Install libarchive-tools + if: runner.os == 'Linux' + run: | + sudo apt update + sudo apt install libarchive-tools + - name: Lint and Run Unit Tests + run: yarn run test + - name: Getting Build Icon + if: github.ref == 'refs/heads/canary' || github.base_ref == 'canary' + run: | + cp build/canary.ico build/icon.ico + cp build/canary.icns build/icon.icns + - name: Build + run: | + if [ -z "$CSC_LINK" ] ; then unset CSC_LINK ; fi + if [ -z "$CSC_KEY_PASSWORD" ] ; then unset CSC_KEY_PASSWORD ; fi + if [ -z "$WIN_CSC_LINK" ] ; then unset WIN_CSC_LINK ; fi + if [ -z "$WIN_CSC_KEY_PASSWORD" ] ; then unset WIN_CSC_KEY_PASSWORD ; fi + if [ -z "$APPLE_ID" ] ; then unset APPLE_ID ; fi + if [ -z "$APPLE_APP_SPECIFIC_PASSWORD" ] ; then unset APPLE_APP_SPECIFIC_PASSWORD ; fi + yarn run dist + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + CSC_LINK: ${{ secrets.MAC_CERT_P12_BASE64 }} + CSC_KEY_PASSWORD: ${{ secrets.MAC_CERT_P12_PASSWORD }} + WIN_CSC_LINK: ${{ secrets.WIN_CERT_P12_BASE64 }} + WIN_CSC_KEY_PASSWORD: ${{ secrets.WIN_CERT_P12_PASSWORD }} + APPLE_ID: ${{ secrets.APPLE_ID }} + APPLE_APP_SPECIFIC_PASSWORD: ${{ secrets.APPLE_PASSWORD }} + - name: Archive Build Artifacts + uses: LabhanshAgrawal/upload-artifact@v3 + with: + path: | + dist/*.dmg + dist/*.snap + dist/*.AppImage + dist/*.deb + dist/*.rpm + dist/*.pacman + dist/*.exe + - name: Run E2E Tests + if: runner.os != 'Linux' + run: yarn run test:e2e + - name: Run E2E Tests on Linux + if: runner.os == 'Linux' + uses: GabrielBB/xvfb-action@v1.6 + with: + run: yarn run test:e2e + env: + SHELL: /bin/bash + - name: Archive E2E test screenshot + uses: actions/upload-artifact@v3 + with: + name: e2e + path: dist/tmp/*.png + - name: Save the pr number in an artifact + if: github.event_name == 'pull_request' + env: + PR_NUM: ${{ github.event.number }} + run: echo $PR_NUM > pr_num.txt + - name: Upload the pr num + uses: actions/upload-artifact@v3 + if: github.event_name == 'pull_request' + with: + name: pr_num + path: ./pr_num.txt + - uses: actions/cache/save@v4 + if: github.event_name == 'push' + with: + path: ${{ steps.yarn-cache-dir-path.outputs.dir }} + key: ${{ runner.os }}-yarn-${{ hashFiles('yarn.lock', 'app/yarn.lock') }} + + build-linux-arm: + runs-on: ubuntu-latest + strategy: + matrix: + include: + - name: armv7l + cpu: cortex-a8 + image: raspios_lite:latest + - name: arm64 + cpu: cortex-a53 + image: raspios_lite_arm64:latest + fail-fast: false + steps: + - name: Checkout + uses: actions/checkout@v4 + - name: Use Node.js ${{ env.NODE_VERSION }} + uses: actions/setup-node@v4 + with: + node-version: ${{ env.NODE_VERSION }} + - name: Fix node-gyp and Python + run: python3 -m pip install packaging setuptools + - name: Get yarn cache directory path + id: yarn-cache-dir-path + run: echo "dir=$(yarn cache dir)" >> $GITHUB_OUTPUT + - uses: actions/cache/restore@v4 + with: + path: ${{ steps.yarn-cache-dir-path.outputs.dir }} + key: ${{ runner.os }}-yarn-${{ hashFiles('yarn.lock', 'app/yarn.lock') }} + restore-keys: | + ${{ runner.os }}-yarn- + - name: Install + run: | + yarn install + sudo apt update + sudo apt install libarchive-tools + - name: Compile + run: yarn run build + - name: rebuild node-pty + uses: pguyot/arm-runner-action@v2.5.2 + with: + image_additional_mb: 2000 + base_image: ${{ matrix.image }} + cpu: ${{ matrix.cpu }} + shell: bash + copy_artifact_path: target/node_modules/node-pty + copy_artifact_dest: target/node_modules + commands: | + wget https://nodejs.org/dist/v18.16.0/node-v18.16.0-linux-${{ matrix.name }}.tar.xz + tar -xJf node-v18.16.0-linux-${{ matrix.name }}.tar.xz + sudo cp node-v18.16.0-linux-${{ matrix.name }}/* /usr/local/ -R + npm run rebuild-node-pty + - name: chown node-pty + run: | + sudo chown -R $USER:$USER target/node_modules/node-pty + - name: Prepare v8 snapshot + if: matrix.name == 'armv7l' + run: | + sudo dpkg --add-architecture i386 + sudo apt update + sudo apt install -y libglib2.0-0:i386 libexpat1:i386 libgcc-s1:i386 + npm_config_arch=armv7l yarn run v8-snapshot:arch + - name: Build + run: yarn run electron-builder -l deb rpm AppImage pacman --${{ matrix.name }} -c electron-builder-linux-ci.json + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + - name: Archive Build Artifacts + uses: LabhanshAgrawal/upload-artifact@v3 + with: + path: | + dist/*.snap + dist/*.AppImage + dist/*.deb + dist/*.rpm + dist/*.pacman diff --git a/.gitignore b/.gitignore index fa4e7c02..9c5932fb 100644 --- a/.gitignore +++ b/.gitignore @@ -1,13 +1,23 @@ # build output dist +app/renderer +target +bin/cli.* +cache # dependencies node_modules # logs npm-debug.log +yarn-error.log # optional dev config file and plugins directory -.hyper.js -.hyper_plugins +hyper.json +schema.json +plugins +.DS_Store +.vscode/* +!.vscode/launch.json +.idea diff --git a/.husky/.gitignore b/.husky/.gitignore new file mode 100644 index 00000000..31354ec1 --- /dev/null +++ b/.husky/.gitignore @@ -0,0 +1 @@ +_ diff --git a/.husky/pre-push b/.husky/pre-push new file mode 100755 index 00000000..f077c917 --- /dev/null +++ b/.husky/pre-push @@ -0,0 +1,4 @@ +#!/bin/sh +. "$(dirname "$0")/_/husky.sh" + +yarn test diff --git a/.npmrc b/.npmrc deleted file mode 100644 index cffe8cde..00000000 --- a/.npmrc +++ /dev/null @@ -1 +0,0 @@ -save-exact=true diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index d54e57ad..00000000 --- a/.travis.yml +++ /dev/null @@ -1,47 +0,0 @@ -sudo: required -dist: trusty - -language: node_js - -matrix: - include: - - os: osx - node_js: 6 - - os: linux - node_js: 6 - env: CC=clang CXX=clang++ npm_config_clang=1 - compiler: clang - -cache: - directories: - - node_modules - - app/node_modules - - $HOME/.electron - - $HOME/.cache - -addons: - apt: - packages: - - libgnome-keyring-dev - - icnsutils - - graphicsmagick - - xz-utils - - rpm - - bsdtar - -before_install: - - mkdir -p /tmp/git-lfs && curl -L https://github.com/github/git-lfs/releases/download/v1.2.1/git-lfs-$([ "$TRAVIS_OS_NAME" == "linux" ] && echo "linux" || echo "darwin")-amd64-1.2.1.tar.gz | tar -xz -C /tmp/git-lfs --strip-components 1 && /tmp/git-lfs/git-lfs pull - - if [[ "$TRAVIS_OS_NAME" == "linux" ]]; then export DISPLAY=:99.0; sh -e /etc/init.d/xvfb start; sleep 3; fi - -install: - - npm install - -before_script: - - npm prune - -after_success: - - npm run dist - -branches: - except: - - "/^v\\d+\\.\\d+\\.\\d+$/" diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 00000000..747bb7b0 --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,22 @@ +{ + "version": "0.2.0", + "configurations": [ + { + "type": "node", + "request": "launch", + "name": "Launch Hyper", + "runtimeExecutable": "${workspaceRoot}/node_modules/.bin/electron", + "program": "${workspaceRoot}/target/index.js", + "protocol": "inspector" + }, + { + "type": "node", + "request": "launch", + "name": "cli", + "runtimeExecutable": "node", + "program": "${workspaceRoot}/bin/cli.js", + "args": ["--help"], + "protocol": "inspector" + } + ] +} diff --git a/.yarnrc b/.yarnrc new file mode 100644 index 00000000..45291c13 --- /dev/null +++ b/.yarnrc @@ -0,0 +1 @@ +registry "https://registry.npmjs.org/" diff --git a/LICENSE.md b/LICENSE similarity index 97% rename from LICENSE.md rename to LICENSE index 5984b833..fe231dc9 100644 --- a/LICENSE.md +++ b/LICENSE @@ -1,6 +1,6 @@ # MIT License -Copyright (c) 2016 Zeit, Inc. +Copyright (c) 2018 Vercel, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/PLUGINS.md b/PLUGINS.md new file mode 100644 index 00000000..afc284a3 --- /dev/null +++ b/PLUGINS.md @@ -0,0 +1,210 @@ +# Plugin development + +## Workflow + +### Run Hyper in dev mode +Hyper can be run in dev mode by cloning this repository and following the ["Contributing" section of our README](https://github.com/vercel/hyper#contribute). + +In dev mode you'll get more ouput and access to React/Redux dev-tools in Electron. + +Prerequisites and steps are described in the ["Contributing" section of our README](https://github.com/vercel/hyper#contribute). +Be sure to use the `canary` branch. + +### Create a dev config file +Copy your config file `hyper.json` to the root of your cloned repository. Hyper, in dev mode, will use this copied config file. That means that you can continue to use your main installation of Hyper with your day-to-day configuration. +After the first run, Hyper, in dev mode, will have created a new `plugins` directory in your repository directory. + +### Setup your plugin +Go to your recently created `/plugins/local` directory and create/clone your plugin repo. An even better method on macOS/Linux is to add a symlink to your plugin directory. + +Edit your dev config file, and add your plugin name (directory name in your `local` directory) in the `localPlugins` array. +```js +module.exports = { + config: { + ... + }, + plugins: [], + localPlugins: ['hyper-awesome-plugin'], + ... +} +``` + +### Running your plugin +To load, your plugin should expose at least one API method. All possible methods are listed [here](https://github.com/vercel/hyper/blob/canary/app/plugins/extensions.ts). + +After launching Hyper in dev mode, run `yarn run app`, it should log that your plugin has been correcty loaded: `Plugin hyper-awesome-plugin (0.1.0) loaded.`. Name and version printed are the ones in your plugins `package.json` file. + +When you put a `console.log()` in your plugin code, it will be displayed in the Electron dev-tools, but only if it is located in a renderer method, like component decorators. If it is located in the Electron main process method, like the `onApp` handler, it will be displayed in your terminal where you ran `yarn run app` or in your VSCode console. + +## Recipes +Almost all available API methods can be found on https://hyper.is. +If there's any missing, let us know or submit a PR to document it! + +### Components +You can decorate almost all Hyper components with a Higher-Order Component (HOC). To understand their architecture, the easiest way is to use React dev-tools to dig in to their hierarchy. + +Multiple plugins can decorate the same Hyper component. Thus, `Component` passed as first argument to your decorator function could possibly not be an original Hyper component but a HOC of a previous plugin. If you need to retrieve a reference to a real Hyper component, you can pass down a `onDecorated` handler. +```js +exports.decorateTerms = (Terms, {React}) => { + return class extends React.Component { + constructor(props, context) { + super(props, context); + this.terms = null; + this.onDecorated = this.onDecorated.bind(this); + } + + onDecorated(terms) { + this.terms = terms; + // Don't forget to propagate it to HOC chain + if (this.props.onDecorated) this.props.onDecorated(terms); + } + + render() { + return React.createElement( + Terms, + Object.assign({}, this.props, { + onDecorated: this.onDecorated + }) + ); + // Or if you use JSX: + // + } + } +``` +:warning: Note that you have to execute `this.props.onDecorated` to not break the handler chain. Without this, you could break other plugins that decorate the same component. + +### Keymaps +If you want to add some keymaps, you need to do 2 things: + +#### Declare your key bindings +Use the `decorateKeymaps` API handler to modify existing keymaps and add yours with the following format `command: hotkeys`. +```js +// Adding Keymaps +exports.decorateKeymaps = keymaps => { + const newKeymaps = { + 'pane:maximize': 'ctrl+shift+m', + 'pane:invert': 'ctrl+shift+i' + } + return Object.assign({}, keymaps, newKeymaps); +} +``` +The command name can be whatever you want, but the following is better to respect the default naming convention: `:`. +Hotkeys are composed by [Mousetrap supported keys](https://craig.is/killing/mice#keys). + +**Bonus feature**: if your command ends with `:prefix`, it would mean that you want to use this command with an additional digit to the command. Then Hyper will create all your commands under the hood. For example, this keymap `'pane:hide:prefix': 'ctrl+shift'` will automatically generate the following: +``` +{ + 'pane:hide:1': 'ctrl+shift+1', + 'pane:hide:2': 'ctrl+shift+2', + ... + 'pane:hide:8': 'ctrl+shift+8', + 'pane:hide:last': 'ctrl+shift+9' +} +``` +Notice that `9` has been replaced by `last` because most of the time this is handy if you have more than 9 items. + + +#### Register a handler for your commands +##### Renderer/Window +Most of time, you'll want to execute some sort of handler in context of the renderer, like dispatching a Redux action. +To trigger these handlers, you'll have to register them with the `registerCommands` Terms method. +```js +this.terms.registerCommands({ + 'pane:maximize': e => { + this.props.onMaximizePane(); + // e parameter is React key event + e.preventDefault(); + } +}) +``` + +##### Main process +If there is no handler in the renderer for an existing command, an `rpc` message is emitted. +If you want to execute a handler in main process you have to subscribe to a message, for example: +```js +rpc.on('command pane:snapshot', () => { + /* Awesome snapshot feature */ +}); +``` + +### Menu +Your plugin can expose a `decorateMenu` function to modify the Hyper menu template. +Check the [Electron documentation](https://electronjs.org/docs/api/menu-item) for more details about the different menu item types/options available. + +Be careful, a click handler will be executed on the main process. If you need to trigger a handler in the render process you need to use an `rpc` message like this: +```js +exports.decorateMenu = (menu) => { + debug('decorateMenu'); + const isMac = process.platform === 'darwin'; + // menu label is different on mac + const menuLabel = isMac ? 'Shell' : 'File'; + + return menu.map(menuCategory => { + if (menuCategory.label !== menuLabel) { + return menuItem; + } + return [ + ...menuCategory, + { + type: 'separator' + }, + { + label: 'Clear all panes in all tabs', + accelerator: 'ctrl+shift+y', + click(item, focusedWindow) { + // on macOS, menu item can clicked without or minized window + if (focusedWindow) { + focusedWindow.rpc.emit('clear allPanes'); + } + } + } + ] + }); +} +/* Plugin needs to register a rpc handler on renderer side for example in a Terms HOC*/ +exports.decorateTerms = (Terms, { React }) => { + return class extends React.Component { + componentDidMount() { + window.rpc.on('clear allPanes',() => { + /* Awesome plugin feature */ + }) + } + } +} +``` + +### Cursor +If your plugin needs to know cursor position/size, it can decorate the Term component and pass a handler. This handler will be called with each cursor move while passing back all information about the cursor. +```js +exports.decorateTerm = (Term, { React, notify }) => { + // Define and return our higher order component. + return class extends React.Component { + onCursorMove (cursorFrame) { + // Don't forget to propagate it to HOC chain + if (this.props.onCursorMove) this.props.onCursorMove(cursorFrame); + + const { x, y, width, height, col, row } = cursorFrame; + /* Awesome cursor feature */ + } + } +} +``` + +### Require Electron +Hyper doesn't provide a reference to electron. However plugins can directly require electron. + +```js +const electron = require('electron') +// or +const { dialog, Menu } = require('electron') +``` + +This is needed in order to allow show/hide to have proper return of focus. + +## Hyper v2 breaking changes +Hyper v2 uses `xterm.js` instead of `hterm`. It means that PTY output renders now in a canvas element, not with a hackable DOM structure. +For example, plugins can't use TermCSS in order to modify text or link styles anymore. It is now required to use available configuration params that are passed down to `xterm.js`. + +If your plugin was deeply linked with the `hterm` API (even public methods), it certainly doesn't work anymore. + +If your plugin needs some unavailable API to tweak `xterm.js`, please open an issue. We'll be happy to expose some existing `xterm.js` API or implement new ones. diff --git a/README.md b/README.md index 0fb7c14b..8c11085e 100644 --- a/README.md +++ b/README.md @@ -1,54 +1,116 @@ -![](https://github.com/zeit/art/blob/525bd1bb39d97dd3b91c976106a6d5cc5766b678/hyper/repo-banner.png) +![](https://assets.vercel.com/image/upload/v1549723846/repositories/hyper/hyper-3-repo-banner.png) -[![Build Status](https://travis-ci.org/zeit/hyper.svg?branch=master)](https://travis-ci.org/zeit/hyper) -[![Build status](https://ci.appveyor.com/api/projects/status/txg5qb0x35h0h65p?svg=true)](https://ci.appveyor.com/project/appveyor-zeit/hyper) -[![Slack Channel](https://zeit-slackin.now.sh/badge.svg)](https://zeit.chat/) +

+ + + +

+ +[![Node CI](https://github.com/vercel/hyper/workflows/Node%20CI/badge.svg?event=push)](https://github.com/vercel/hyper/actions?query=workflow%3A%22Node+CI%22+branch%3Acanary+event%3Apush) [![Changelog #213](https://img.shields.io/badge/changelog-%23213-lightgrey.svg)](https://changelog.com/213) -[![XO code style](https://img.shields.io/badge/code_style-XO-5ed9c7.svg)](https://github.com/sindresorhus/xo) For more details, head to: https://hyper.is +## Project goals + +The goal of the project is to create a beautiful and extensible experience for command-line interface users, built on open web standards. In the beginning, our focus will be primarily around speed, stability and the development of the correct API for extension authors. + +In the future, we anticipate the community will come up with innovative additions to enhance what could be the simplest, most powerful and well-tested interface for productivity. + ## Usage [Download the latest release!](https://hyper.is/#installation) -If you're on macOS, you can also use [Homebrew Cask](https://caskroom.github.io/) to download the app by running these commands: +### Linux +#### Arch and derivatives +Hyper is available in the [AUR](https://aur.archlinux.org/packages/hyper/). Use an AUR [package manager](https://wiki.archlinux.org/index.php/AUR_helpers) e.g. [paru](https://github.com/Morganamilo/paru) + +```sh +paru -S hyper +``` + +#### NixOS +Hyper is available as [Nix package](https://github.com/NixOS/nixpkgs/blob/master/pkgs/applications/misc/hyper/default.nix), to install the app run this command: + +```sh +nix-env -i hyper +``` + +### macOS + +Use [Homebrew Cask](https://brew.sh) to download the app by running these commands: ```bash brew update -brew cask install hyper +brew install --cask hyper ``` +### Windows + +Use [chocolatey](https://chocolatey.org/) to install the app by running the following command (package information can be found [here](https://chocolatey.org/packages/hyper/)): + +```bash +choco install hyper +``` + +**Note:** The version available on [Homebrew Cask](https://brew.sh), [Chocolatey](https://chocolatey.org), [Snapcraft](https://snapcraft.io/store) or the [AUR](https://aur.archlinux.org) may not be the latest. Please consider downloading it from [here](https://hyper.is/#installation) if that's the case. + ## Contribute -1. Install the dependencies - * If you are running Linux, install `icnsutils`, `graphicsmagick`, `xz-utils` and `rpm` - * If you are running Windows, install [VC++ Build Tools Technical Preview](http://go.microsoft.com/fwlink/?LinkId=691126) using the **Default Install option**; Install Python 2.7 and add it to your `%PATH%`; Run `npm config set msvs_version 2015 --global` +Regardless of the platform you are working on, you will need to have Yarn installed. If you have never installed Yarn before, you can find out how at: https://yarnpkg.com/en/docs/install. + +1. Install necessary packages: + * Windows + - Be sure to run `yarn global add windows-build-tools` from an elevated prompt (as an administrator) to install `windows-build-tools`. + * macOS + - Once you have installed Yarn, you can skip this section! + * Linux (You can see [here](https://en.wikipedia.org/wiki/List_of_Linux_distributions) what your Linux is based on.) + - RPM-based + + `GraphicsMagick` + + `libicns-utils` + + `xz` (Installed by default on some distributions.) + - Debian-based + + `graphicsmagick` + + `icnsutils` + + `xz-utils` 2. [Fork](https://help.github.com/articles/fork-a-repo/) this repository to your own GitHub account and then [clone](https://help.github.com/articles/cloning-a-repository/) it to your local device -3. Install the dependencies: `npm install` -4. Build the code and watch for changes: `npm run dev` -5. In another terminal tab/window/pane, run the app: `npm run app` +3. Install the dependencies: `yarn` +4. Build the code and watch for changes: `yarn run dev` +5. To run `hyper` + * `yarn run app` from another terminal tab/window/pane + * If you are using **Visual Studio Code**, select `Launch Hyper` in debugger configuration to launch a new Hyper instance with debugger attached. + * If you interrupt `yarn run dev`, you'll need to relaunch it each time you want to test something. Webpack will watch changes and will rebuild renderer code when needed (and only what have changed). You'll just have to relaunch electron by using yarn run app or VSCode launch task. To make sure that your code works in the finished application, you can generate the binaries like this: ```bash -$ npm run pack +yarn run dist ``` -After that, you'll see the binary in the `./dist` folder! +After that, you will see the binary in the `./dist` folder! -### pty.js issues +#### Known issues that can happen during development -If after building during development you get an alert dialog related to `pty.js` issues, -make sure its build process is working correctly by running `npm rebuild` manually inside -the `app` directory. +##### Error building `node-pty` -If you're on macOS, this typically is related to Xcode issues (like not having agreed +If after building during development you get an alert dialog related to `node-pty` issues, +make sure its build process is working correctly by running `yarn run rebuild-node-pty`. + +If you are on macOS, this typically is related to Xcode issues (like not having agreed to the Terms of Service by running `sudo xcodebuild` after a fresh Xcode installation). +##### Error with `C++` on macOS when running `yarn` + +If you are getting compiler errors when running `yarn` add the environment variable `export CXX=clang++` + +##### Error with `codesign` on macOS when running `yarn run dist` + +If you have issues in the `codesign` step when running `yarn run dist` on macOS, you can temporarily disable code signing locally by setting +`export CSC_IDENTITY_AUTO_DISCOVERY=false` for the current terminal session. + ## Related Repositories -- [Art](https://github.com/zeit/art/tree/master/hyper) -- [Website](https://github.com/zeit/hyper-website) -- [Sample Extension](https://github.com/zeit/hyperpower) -- [Sample Theme](https://github.com/zeit/hyperyellow) +- [Website](https://github.com/vercel/hyper-site) +- [Sample Extension](https://github.com/vercel/hyperpower) +- [Sample Theme](https://github.com/vercel/hyperyellow) +- [Awesome Hyper](https://github.com/bnb/awesome-hyper) diff --git a/app/.npmrc b/app/.npmrc deleted file mode 100644 index cffe8cde..00000000 --- a/app/.npmrc +++ /dev/null @@ -1 +0,0 @@ -save-exact=true diff --git a/app/.yarnrc b/app/.yarnrc new file mode 100644 index 00000000..45291c13 --- /dev/null +++ b/app/.yarnrc @@ -0,0 +1 @@ +registry "https://registry.npmjs.org/" diff --git a/app/accelerators.js b/app/accelerators.js deleted file mode 100644 index ddd76ae1..00000000 --- a/app/accelerators.js +++ /dev/null @@ -1,136 +0,0 @@ -const platform = process.platform; - -const isMac = platform === 'darwin'; - -const prefix = isMac ? 'Cmd' : 'Ctrl'; - -const applicationMenu = { // app/menu.js - preferences: ',', - quit: isMac ? 'Q' : '', - - // Shell/File menu - newWindow: 'N', - newTab: 'T', - splitVertically: isMac ? 'D' : 'Shift+E', - splitHorizontally: isMac ? 'Shift+D' : 'Shift+O', - closeSession: 'W', - closeWindow: 'Shift+W', - - // Edit menu - undo: 'Z', - redo: 'Shift+Z', - cut: 'X', - copy: isMac ? 'C' : 'Shift+C', - paste: 'V', - selectAll: 'A', - clear: 'K', - emojis: isMac ? 'Ctrl+Cmd+Space' : '', - - // View menu - reload: 'R', - fullReload: 'Shift+R', - toggleDevTools: isMac ? 'Alt+I' : 'Shift+I', - resetZoom: '0', - zoomIn: 'plus', - zoomOut: '-', - - // Plugins menu - updatePlugins: 'Shift+U', - - // Window menu - minimize: 'M', - showPreviousTab: 'Alt+Left', - showNextTab: 'Alt+Right', - selectNextPane: 'Ctrl+Alt+Tab', - selectPreviousPane: 'Ctrl+Shift+Alt+Tab', - enterFullScreen: isMac ? 'Ctrl+Cmd+F' : 'F11' -}; - -const mousetrap = { // lib/containers/hyper.js - moveTo1: '1', - moveTo2: '2', - moveTo3: '3', - moveTo4: '4', - moveTo5: '5', - moveTo6: '6', - moveTo7: '7', - moveTo8: '8', - moveToLast: '9', - - // here `1`, `2` etc are used to "emulate" something like `moveLeft: ['...', '...', etc]` - moveLeft1: 'Shift+Left', - moveRight1: 'Shift+Right', - moveLeft2: 'Shift+{', - moveRight2: 'Shift+}', - moveLeft3: 'Alt+Left', - moveRight3: 'Alt+Right', - moveLeft4: 'Ctrl+Shift+Tab', - moveRight4: 'Ctrl+Tab', - - // here we add `+` at the beginning to prevent the prefix from being added - moveWordLeft: '+Alt+Left', - moveWordRight: '+Alt+Right', - deleteWordLeft: '+Alt+Backspace', - deleteWordRight: '+Alt+Delete', - deleteLine: 'Backspace', - moveToStart: 'Left', - moveToEnd: 'Right', - selectAll: 'A' -}; - -const allAccelerators = Object.assign({}, applicationMenu, mousetrap); -const cache = []; -// ^ here we store the shortcuts so we don't need to -// look into the `allAccelerators` everytime - -for (const key in allAccelerators) { - if ({}.hasOwnProperty.call(allAccelerators, key)) { - let value = allAccelerators[key]; - if (value) { - if (value.startsWith('+')) { - // we don't need to add the prefix to accelerators starting with `+` - value = value.slice(1); - } else if (!value.startsWith('Ctrl')) { // nor to the ones starting with `Ctrl` - value = `${prefix}+${value}`; - } - cache.push(value.toLowerCase()); - allAccelerators[key] = value; - } - } -} - -// decides if a keybard event is a Hyper Accelerator -function isAccelerator(e) { - let keys = []; - if (!e.ctrlKey && !e.metaKey && !e.altKey) { - // all accelerators needs Ctrl or Cmd or Alt - return false; - } - - if (e.ctrlKey) { - keys.push('ctrl'); - } - if (e.metaKey && isMac) { - keys.push('cmd'); - } - if (e.shiftKey) { - keys.push('shift'); - } - if (e.altKey) { - keys.push('alt'); - } - - if (e.key === ' ') { - keys.push('space'); - } else { - // we need `toLowerCase` for when the shortcut has `shift` - // we need to replace `arrow` when the shortcut uses the arrow keys - keys.push(e.key.toLowerCase().replace('arrow', '')); - } - - keys = keys.join('+'); - return cache.includes(keys); -} - -module.exports.isAccelerator = isAccelerator; -module.exports.accelerators = allAccelerators; diff --git a/app/auto-updater-linux.ts b/app/auto-updater-linux.ts new file mode 100644 index 00000000..aa95c1d7 --- /dev/null +++ b/app/auto-updater-linux.ts @@ -0,0 +1,52 @@ +import {EventEmitter} from 'events'; + +import fetch from 'electron-fetch'; + +class AutoUpdater extends EventEmitter implements Electron.AutoUpdater { + updateURL!: string; + quitAndInstall() { + this.emitError('QuitAndInstall unimplemented'); + } + getFeedURL() { + return this.updateURL; + } + + setFeedURL(options: Electron.FeedURLOptions) { + this.updateURL = options.url; + } + + checkForUpdates() { + if (!this.updateURL) { + return this.emitError('Update URL is not set'); + } + this.emit('checking-for-update'); + + fetch(this.updateURL) + .then((res) => { + if (res.status === 204) { + this.emit('update-not-available'); + return; + } + return res.json().then(({name, notes, pub_date}: {name: string; notes: string; pub_date: string}) => { + // Only name is mandatory, needed to construct release URL. + if (!name) { + throw new Error('Malformed server response: release name is missing.'); + } + const date = pub_date ? new Date(pub_date) : new Date(); + this.emit('update-available', {}, notes, name, date); + }); + }) + .catch(this.emitError.bind(this)); + } + + emitError(error: string | Error) { + if (typeof error === 'string') { + error = new Error(error); + } + this.emit('error', error); + } +} + +const autoUpdaterLinux = new AutoUpdater(); + +export default autoUpdaterLinux; diff --git a/app/auto-updater.js b/app/auto-updater.js deleted file mode 100644 index 215a5bfe..00000000 --- a/app/auto-updater.js +++ /dev/null @@ -1,53 +0,0 @@ -const {autoUpdater} = require('electron'); -const ms = require('ms'); - -const notify = require('./notify'); // eslint-disable-line no-unused-vars -const {version} = require('./package'); - -// accepted values: `osx`, `win32` -// https://nuts.gitbook.com/update-windows.html -const platform = process.platform === 'darwin' ? - 'osx' : - process.platform; -const FEED_URL = `https://hyper-updates.now.sh/update/${platform}`; -let isInit = false; - -function init() { - autoUpdater.on('error', (err, msg) => { - console.error('Error fetching updates', msg + ' (' + err.stack + ')'); - }); - - autoUpdater.setFeedURL(`${FEED_URL}/${version}`); - - setTimeout(() => { - autoUpdater.checkForUpdates(); - }, ms('10s')); - - setInterval(() => { - autoUpdater.checkForUpdates(); - }, ms('30m')); - - isInit = true; -} - -module.exports = function (win) { - if (!isInit) { - init(); - } - - const {rpc} = win; - - const onupdate = (ev, releaseNotes, releaseName) => { - rpc.emit('update available', {releaseNotes, releaseName}); - }; - - autoUpdater.on('update-downloaded', onupdate); - - rpc.once('quit and install', () => { - autoUpdater.quitAndInstall(); - }); - - win.on('close', () => { - autoUpdater.removeListener('update-downloaded', onupdate); - }); -}; diff --git a/app/commands.ts b/app/commands.ts new file mode 100644 index 00000000..469a5a3d --- /dev/null +++ b/app/commands.ts @@ -0,0 +1,170 @@ +import {app, Menu} from 'electron'; +import type {BrowserWindow} from 'electron'; + +import {openConfig, getConfig} from './config'; +import {updatePlugins} from './plugins'; +import {installCLI} from './utils/cli-install'; +import * as systemContextMenu from './utils/system-context-menu'; + +const commands: Record void> = { + 'window:new': () => { + // If window is created on the same tick, it will consume event too + setTimeout(app.createWindow, 0); + }, + 'tab:new': (focusedWindow) => { + if (focusedWindow) { + focusedWindow.rpc.emit('termgroup add req', {}); + } else { + setTimeout(app.createWindow, 0); + } + }, + 'pane:splitRight': (focusedWindow) => { + focusedWindow?.rpc.emit('split request vertical', {}); + }, + 'pane:splitDown': (focusedWindow) => { + focusedWindow?.rpc.emit('split request horizontal', {}); + }, + 'pane:close': (focusedWindow) => { + focusedWindow?.rpc.emit('termgroup close req'); + }, + 'window:preferences': () => { + void openConfig(); + }, + 'editor:clearBuffer': (focusedWindow) => { + focusedWindow?.rpc.emit('session clear req'); + }, + 'editor:selectAll': (focusedWindow) => { + focusedWindow?.rpc.emit('term selectAll'); + }, + 'plugins:update': () => { + updatePlugins(); + }, + 'window:reload': (focusedWindow) => { + focusedWindow?.rpc.emit('reload'); + }, + 'window:reloadFull': (focusedWindow) => { + focusedWindow?.reload(); + }, + 'window:devtools': (focusedWindow) => { + if (!focusedWindow) { + return; + } + const webContents = focusedWindow.webContents; + if (webContents.isDevToolsOpened()) { + webContents.closeDevTools(); + } else { + webContents.openDevTools({mode: 'detach'}); + } + }, + 'zoom:reset': (focusedWindow) => { + focusedWindow?.rpc.emit('reset fontSize req'); + }, + 'zoom:in': (focusedWindow) => { + focusedWindow?.rpc.emit('increase fontSize req'); + }, + 'zoom:out': (focusedWindow) => { + focusedWindow?.rpc.emit('decrease fontSize req'); + }, + 'tab:prev': (focusedWindow) => { + focusedWindow?.rpc.emit('move left req'); + }, + 'tab:next': (focusedWindow) => { + focusedWindow?.rpc.emit('move right req'); + }, + 'pane:prev': (focusedWindow) => { + focusedWindow?.rpc.emit('prev pane req'); + }, + 'pane:next': (focusedWindow) => { + focusedWindow?.rpc.emit('next pane req'); + }, + 'editor:movePreviousWord': (focusedWindow) => { + focusedWindow?.rpc.emit('session move word left req'); + }, + 'editor:moveNextWord': (focusedWindow) => { + focusedWindow?.rpc.emit('session move word right req'); + }, + 'editor:moveBeginningLine': (focusedWindow) => { + focusedWindow?.rpc.emit('session move line beginning req'); + }, + 'editor:moveEndLine': (focusedWindow) => { + focusedWindow?.rpc.emit('session move line end req'); + }, + 'editor:deletePreviousWord': (focusedWindow) => { + focusedWindow?.rpc.emit('session del word left req'); + }, + 'editor:deleteNextWord': (focusedWindow) => { + focusedWindow?.rpc.emit('session del word right req'); + }, + 'editor:deleteBeginningLine': (focusedWindow) => { + focusedWindow?.rpc.emit('session del line beginning req'); + }, + 'editor:deleteEndLine': (focusedWindow) => { + focusedWindow?.rpc.emit('session del line end req'); + }, + 'editor:break': (focusedWindow) => { + focusedWindow?.rpc.emit('session break req'); + }, + 'editor:stop': (focusedWindow) => { + focusedWindow?.rpc.emit('session stop req'); + }, + 'editor:quit': (focusedWindow) => { + focusedWindow?.rpc.emit('session quit req'); + }, + 'editor:tmux': (focusedWindow) => { + focusedWindow?.rpc.emit('session tmux req'); + }, + 'editor:search': (focusedWindow) => { + focusedWindow?.rpc.emit('session search'); + }, + 'editor:search-close': (focusedWindow) => { + focusedWindow?.rpc.emit('session search close'); + }, + 'cli:install': () => { + void installCLI(true); + }, + 'window:hamburgerMenu': () => { + if (process.platform !== 'darwin' && ['', true].includes(getConfig().showHamburgerMenu)) { + Menu.getApplicationMenu()!.popup({x: 25, y: 22}); + } + }, + 'systemContextMenu:add': () => { + systemContextMenu.add(); + }, + 'systemContextMenu:remove': () => { + systemContextMenu.remove(); + }, + 'window:toggleKeepOnTop': (focusedWindow) => { + focusedWindow?.setAlwaysOnTop(!focusedWindow.isAlwaysOnTop()); + } +}; + +//Special numeric command +([1, 2, 3, 4, 5, 6, 7, 8, 'last'] as const).forEach((cmdIndex) => { + const index = cmdIndex === 'last' ? cmdIndex : cmdIndex - 1; + commands[`tab:jump:${cmdIndex}`] = (focusedWindow) => { + focusedWindow?.rpc.emit('move jump req', index); + }; +}); + +//Profile specific commands +getConfig().profiles.forEach((profile) => { + commands[`window:new:${profile.name}`] = () => { + setTimeout(() => app.createWindow(undefined, undefined, profile.name), 0); + }; + commands[`tab:new:${profile.name}`] = (focusedWindow) => { + focusedWindow?.rpc.emit('termgroup add req', {profile: profile.name}); + }; + commands[`pane:splitRight:${profile.name}`] = (focusedWindow) => { + focusedWindow?.rpc.emit('split request vertical', {profile: profile.name}); + }; + commands[`pane:splitDown:${profile.name}`] = (focusedWindow) => { + focusedWindow?.rpc.emit('split request horizontal', {profile: profile.name}); + }; +}); + +export const execCommand = (command: string, focusedWindow?: BrowserWindow) => { + const fn = commands[command]; + if (fn) { + fn(focusedWindow); + } +}; diff --git a/app/config-default.js b/app/config-default.js deleted file mode 100644 index e920e945..00000000 --- a/app/config-default.js +++ /dev/null @@ -1,100 +0,0 @@ -module.exports = { - config: { - // default font size in pixels for all tabs - fontSize: 12, - - // font family with optional fallbacks - fontFamily: 'Menlo, "DejaVu Sans Mono", Consolas, "Lucida Console", monospace', - - // terminal cursor background color and opacity (hex, rgb, hsl, hsv, hwb or cmyk) - cursorColor: 'rgba(248,28,229,0.8)', - - // `BEAM` for |, `UNDERLINE` for _, `BLOCK` for █ - cursorShape: 'BLOCK', - - // color of the text - foregroundColor: '#fff', - - // terminal background color - backgroundColor: '#000', - - // border color (window, tabs) - borderColor: '#333', - - // custom css to embed in the main window - css: '', - - // custom css to embed in the terminal window - termCSS: '', - - // set to `true` if you're using a Linux set up - // that doesn't shows native menus - // default: `false` on Linux, `true` on Windows (ignored on macOS) - showHamburgerMenu: '', - - // set to `false` if you want to hide the minimize, maximize and close buttons - // additionally, set to `'left'` if you want them on the left, like in Ubuntu - // default: `true` on windows and Linux (ignored on macOS) - showWindowControls: '', - - // custom padding (css format, i.e.: `top right bottom left`) - padding: '12px 14px', - - // the full list. if you're going to provide the full color palette, - // including the 6 x 6 color cubes and the grayscale map, just provide - // an array here instead of a color map object - colors: { - black: '#000000', - red: '#ff0000', - green: '#33ff00', - yellow: '#ffff00', - blue: '#0066ff', - magenta: '#cc00ff', - cyan: '#00ffff', - white: '#d0d0d0', - lightBlack: '#808080', - lightRed: '#ff0000', - lightGreen: '#33ff00', - lightYellow: '#ffff00', - lightBlue: '#0066ff', - lightMagenta: '#cc00ff', - lightCyan: '#00ffff', - lightWhite: '#ffffff' - }, - - // the shell to run when spawning a new session (i.e. /usr/local/bin/fish) - // if left empty, your system's login shell will be used by default - shell: '', - - // for setting shell arguments (i.e. for using interactive shellArgs: ['-i']) - // by default ['--login'] will be used - shellArgs: ['--login'], - - // for environment variables - env: {}, - - // set to false for no bell - bell: 'SOUND', - - // if true, selected text will automatically be copied to the clipboard - copyOnSelect: false - - // URL to custom bell - // bellSoundURL: 'http://example.com/bell.mp3', - - // for advanced config flags please refer to https://hyper.is/#cfg - }, - - // a list of plugins to fetch and install from npm - // format: [@org/]project[#version] - // examples: - // `hyperpower` - // `@company/project` - // `project#1.0.1` - plugins: [], - - // in development, you can create a directory under - // `~/.hyper_plugins/local/` and include it here - // to load it and avoid it being `npm install`ed - localPlugins: [] -}; diff --git a/app/config.js b/app/config.js deleted file mode 100644 index d42d50f5..00000000 --- a/app/config.js +++ /dev/null @@ -1,147 +0,0 @@ -const {homedir} = require('os'); -const {statSync, renameSync, readFileSync, writeFileSync} = require('fs'); -const {resolve} = require('path'); -const vm = require('vm'); - -const {dialog} = require('electron'); -const isDev = require('electron-is-dev'); -const gaze = require('gaze'); -const Config = require('electron-config'); -const notify = require('./notify'); - -// local storage -const winCfg = new Config({ - defaults: { - windowPosition: [50, 50], - windowSize: [540, 380] - } -}); - -let configDir = homedir(); -if (isDev) { - // if a local config file exists, use it - try { - const devDir = resolve(__dirname, '..'); - const devConfig = resolve(devDir, '.hyper.js'); - statSync(devConfig); - configDir = devDir; - console.log('using config file:', devConfig); - } catch (err) { - // ignore - } -} - -const path = resolve(configDir, '.hyper.js'); -const pathLegacy = resolve(configDir, '.hyperterm.js'); - -const watchers = []; - -let cfg = {}; - -function watch() { - gaze(path, function (err) { - if (err) { - throw err; - } - this.on('changed', () => { - try { - if (exec(readFileSync(path, 'utf8'))) { - notify('Hyper configuration reloaded!'); - watchers.forEach(fn => fn()); - } - } catch (err) { - dialog.showMessageBox({ - message: `An error occurred loading your configuration (${path}): ${err.message}`, - buttons: ['Ok'] - }); - } - }); - this.on('error', () => { - // Ignore file watching errors - }); - }); -} - -let _str; // last script -function exec(str) { - if (str === _str) { - return false; - } - _str = str; - const script = new vm.Script(str); - const module = {}; - script.runInNewContext({module}); - if (!module.exports) { - throw new Error('Error reading configuration: `module.exports` not set'); - } - const _cfg = module.exports; - if (!_cfg.config) { - throw new Error('Error reading configuration: `config` key is missing'); - } - _cfg.plugins = _cfg.plugins || []; - _cfg.localPlugins = _cfg.localPlugins || []; - cfg = _cfg; - return true; -} - -exports.subscribe = function (fn) { - watchers.push(fn); - return () => { - watchers.splice(watchers.indexOf(fn), 1); - }; -}; - -exports.init = function () { - // for backwards compatibility with hyperterm - // (prior to the rename), we try to rename - // on behalf of the user - try { - statSync(pathLegacy); - renameSync(pathLegacy, path); - } catch (err) { - // ignore - } - - try { - exec(readFileSync(path, 'utf8')); - } catch (err) { - console.log('read error', path, err.message); - const defaultConfig = readFileSync(resolve(__dirname, 'config-default.js')); - try { - console.log('attempting to write default config to', path); - exec(defaultConfig); - writeFileSync(path, defaultConfig); - } catch (err) { - throw new Error(`Failed to write config to ${path}`); - } - } - watch(); -}; - -exports.getConfigDir = function () { - // expose config directory to load plugin from the right place - return configDir; -}; - -exports.getConfig = function () { - return cfg.config; -}; - -exports.getPlugins = function () { - return { - plugins: cfg.plugins, - localPlugins: cfg.localPlugins - }; -}; - -exports.window = { - get() { - const position = winCfg.get('windowPosition'); - const size = winCfg.get('windowSize'); - return {position, size}; - }, - recordState(win) { - winCfg.set('windowPosition', win.getPosition()); - winCfg.set('windowSize', win.getSize()); - } -}; diff --git a/app/config.ts b/app/config.ts new file mode 100644 index 00000000..b4613d57 --- /dev/null +++ b/app/config.ts @@ -0,0 +1,156 @@ +import {app} from 'electron'; + +import chokidar from 'chokidar'; + +import type {parsedConfig, configOptions} from '../typings/config'; + +import {_import, getDefaultConfig} from './config/import'; +import _openConfig from './config/open'; +import {cfgPath, cfgDir} from './config/paths'; +import notify from './notify'; +import {getColorMap} from './utils/colors'; + +const watchers: Function[] = []; +let cfg: parsedConfig = {} as any; +let _watcher: chokidar.FSWatcher; + +export const getDeprecatedCSS = (config: configOptions) => { + const deprecated: string[] = []; + const deprecatedCSS = ['x-screen', 'x-row', 'cursor-node', '::selection']; + deprecatedCSS.forEach((css) => { + if (config.css?.includes(css) || config.termCSS?.includes(css)) { + deprecated.push(css); + } + }); + return deprecated; +}; + +const checkDeprecatedConfig = () => { + if (!cfg.config) { + return; + } + const deprecated = getDeprecatedCSS(cfg.config); + if (deprecated.length === 0) { + return; + } + const deprecatedStr = deprecated.join(', '); + notify('Configuration warning', `Your configuration uses some deprecated CSS classes (${deprecatedStr})`); +}; + +const _watch = () => { + if (_watcher) { + return; + } + + const onChange = () => { + // Need to wait 100ms to ensure that write is complete + setTimeout(() => { + cfg = _import(); + notify('Configuration updated', 'Hyper configuration reloaded!'); + watchers.forEach((fn) => { + fn(); + }); + checkDeprecatedConfig(); + }, 100); + }; + + _watcher = chokidar.watch(cfgPath); + _watcher.on('change', onChange); + _watcher.on('error', (error) => { + console.error('error watching config', error); + }); + + app.on('before-quit', () => { + if (Object.keys(_watcher.getWatched()).length > 0) { + _watcher.close().catch((err) => { + console.warn(err); + }); + } + }); +}; + +export const subscribe = (fn: Function) => { + watchers.push(fn); + return () => { + watchers.splice(watchers.indexOf(fn), 1); + }; +}; + +export const getConfigDir = () => { + // expose config directory to load plugin from the right place + return cfgDir; +}; + +export const getDefaultProfile = () => { + return cfg.config.defaultProfile || cfg.config.profiles[0]?.name || 'default'; +}; + +// get config for the default profile, keeping it for backward compatibility +export const getConfig = () => { + return getProfileConfig(getDefaultProfile()); +}; + +export const getProfiles = () => { + return cfg.config.profiles; +}; + +export const getProfileConfig = (profileName: string): configOptions => { + const {profiles, defaultProfile, ...baseConfig} = cfg.config; + const profileConfig = profiles.find((p) => p.name === profileName)?.config || {}; + for (const key in profileConfig) { + if (typeof baseConfig[key] === 'object' && !Array.isArray(baseConfig[key])) { + baseConfig[key] = {...baseConfig[key], ...profileConfig[key]}; + } else { + baseConfig[key] = profileConfig[key]; + } + } + return {...baseConfig, defaultProfile, profiles}; +}; + +export const openConfig = () => { + return _openConfig(); +}; + +export const getPlugins = (): {plugins: string[]; localPlugins: string[]} => { + return { + plugins: cfg.plugins, + localPlugins: cfg.localPlugins + }; +}; + +export const getKeymaps = () => { + return cfg.keymaps; +}; + +export const setup = () => { + cfg = _import(); + _watch(); + checkDeprecatedConfig(); +}; + +export {get as getWin, recordState as winRecord, defaults as windowDefaults} from './config/windows'; + +export const fixConfigDefaults = (decoratedConfig: configOptions) => { + const defaultConfig = getDefaultConfig().config!; + decoratedConfig.colors = getColorMap(decoratedConfig.colors) || {}; + // We must have default colors for xterm css. + decoratedConfig.colors = {...defaultConfig.colors, ...decoratedConfig.colors}; + return decoratedConfig; +}; + +export const htermConfigTranslate = (config: configOptions) => { + const cssReplacements: Record = { + 'x-screen x-row([ {.[])': '.xterm-rows > div$1', + '.cursor-node([ {.[])': '.terminal-cursor$1', + '::selection([ {.[])': '.terminal .xterm-selection div$1', + 'x-screen a([ {.[])': '.terminal a$1', + 'x-row a([ {.[])': '.terminal a$1' + }; + Object.keys(cssReplacements).forEach((pattern) => { + const searchvalue = new RegExp(pattern, 'g'); + const newvalue = cssReplacements[pattern]; + config.css = config.css?.replace(searchvalue, newvalue); + config.termCSS = config.termCSS?.replace(searchvalue, newvalue); + }); + return config; +}; diff --git a/app/config/config-default.json b/app/config/config-default.json new file mode 100644 index 00000000..2a6a66ff --- /dev/null +++ b/app/config/config-default.json @@ -0,0 +1,77 @@ +{ + "$schema": "./schema.json", + "config": { + "updateChannel": "stable", + "fontSize": 12, + "fontFamily": "Menlo, \"DejaVu Sans Mono\", Consolas, \"Lucida Console\", monospace", + "fontWeight": "normal", + "fontWeightBold": "bold", + "lineHeight": 1, + "letterSpacing": 0, + "scrollback": 1000, + "cursorColor": "rgba(248,28,229,0.8)", + "cursorAccentColor": "#000", + "cursorShape": "BLOCK", + "cursorBlink": false, + "foregroundColor": "#fff", + "backgroundColor": "#000", + "selectionColor": "rgba(248,28,229,0.3)", + "borderColor": "#333", + "css": "", + "termCSS": "", + "workingDirectory": "", + "showHamburgerMenu": "", + "showWindowControls": "", + "padding": "12px 14px", + "colors": { + "black": "#000000", + "red": "#C51E14", + "green": "#1DC121", + "yellow": "#C7C329", + "blue": "#0A2FC4", + "magenta": "#C839C5", + "cyan": "#20C5C6", + "white": "#C7C7C7", + "lightBlack": "#686868", + "lightRed": "#FD6F6B", + "lightGreen": "#67F86F", + "lightYellow": "#FFFA72", + "lightBlue": "#6A76FB", + "lightMagenta": "#FD7CFC", + "lightCyan": "#68FDFE", + "lightWhite": "#FFFFFF", + "limeGreen": "#32CD32", + "lightCoral": "#F08080" + }, + "shell": "", + "shellArgs": [ + "--login" + ], + "env": {}, + "bell": "SOUND", + "bellSound": null, + "bellSoundURL": null, + "copyOnSelect": false, + "defaultSSHApp": true, + "quickEdit": false, + "macOptionSelectionMode": "vertical", + "webGLRenderer": false, + "webLinksActivationKey": "", + "disableLigatures": true, + "disableAutoUpdates": false, + "autoUpdatePlugins": true, + "preserveCWD": true, + "screenReaderMode": false, + "imageSupport": true, + "defaultProfile": "default", + "profiles": [ + { + "name": "default", + "config": {} + } + ] + }, + "plugins": [], + "localPlugins": [], + "keymaps": {} +} diff --git a/app/config/import.ts b/app/config/import.ts new file mode 100644 index 00000000..b9965375 --- /dev/null +++ b/app/config/import.ts @@ -0,0 +1,65 @@ +import {readFileSync, mkdirpSync} from 'fs-extra'; + +import type {rawConfig} from '../../typings/config'; +import notify from '../notify'; + +import {_init} from './init'; +import {migrateHyper3Config} from './migrate'; +import {defaultCfg, cfgPath, plugs, defaultPlatformKeyPath} from './paths'; + +let defaultConfig: rawConfig; + +const _importConf = () => { + // init plugin directories if not present + mkdirpSync(plugs.base); + mkdirpSync(plugs.local); + + try { + migrateHyper3Config(); + } catch (err) { + console.error(err); + } + + let defaultCfgRaw = '{}'; + try { + defaultCfgRaw = readFileSync(defaultCfg, 'utf8'); + } catch (err) { + console.log(err); + } + const _defaultCfg = JSON.parse(defaultCfgRaw) as rawConfig; + + // Importing platform specific keymap + let content = '{}'; + try { + content = readFileSync(defaultPlatformKeyPath(), 'utf8'); + } catch (err) { + console.error(err); + } + const mapping = JSON.parse(content) as Record; + _defaultCfg.keymaps = mapping; + + // Import user config + let userCfg: rawConfig; + try { + userCfg = JSON.parse(readFileSync(cfgPath, 'utf8')); + } catch (err) { + notify("Couldn't parse config file. Using default config instead."); + userCfg = JSON.parse(defaultCfgRaw); + } + + return {userCfg, defaultCfg: _defaultCfg}; +}; + +export const _import = () => { + const imported = _importConf(); + defaultConfig = imported.defaultCfg; + const result = _init(imported.userCfg, imported.defaultCfg); + return result; +}; + +export const getDefaultConfig = () => { + if (!defaultConfig) { + defaultConfig = _importConf().defaultCfg; + } + return defaultConfig; +}; diff --git a/app/config/init.ts b/app/config/init.ts new file mode 100644 index 00000000..a41b864c --- /dev/null +++ b/app/config/init.ts @@ -0,0 +1,63 @@ +import vm from 'vm'; + +import merge from 'lodash/merge'; + +import type {parsedConfig, rawConfig, configOptions} from '../../typings/config'; +import notify from '../notify'; +import mapKeys from '../utils/map-keys'; + +const _extract = (script?: vm.Script): Record => { + const module: Record = {}; + script?.runInNewContext({module}, {displayErrors: true}); + if (!module.exports) { + throw new Error('Error reading configuration: `module.exports` not set'); + } + // eslint-disable-next-line @typescript-eslint/no-unsafe-return + return module.exports; +}; + +const _syntaxValidation = (cfg: string) => { + try { + return new vm.Script(cfg, {filename: '.hyper.js'}); + } catch (_err) { + const err = _err as {name: string}; + notify(`Error loading config: ${err.name}`, JSON.stringify(err), {error: err}); + } +}; + +const _extractDefault = (cfg: string) => { + return _extract(_syntaxValidation(cfg)); +}; + +// init config +const _init = (userCfg: rawConfig, defaultCfg: rawConfig): parsedConfig => { + return { + config: (() => { + if (userCfg?.config) { + const conf = userCfg.config; + conf.defaultProfile = conf.defaultProfile || 'default'; + conf.profiles = conf.profiles || []; + conf.profiles = conf.profiles.length > 0 ? conf.profiles : [{name: 'default', config: {}}]; + conf.profiles = conf.profiles.map((p, i) => ({ + ...p, + name: p.name || `profile-${i + 1}`, + config: p.config || {} + })); + if (!conf.profiles.map((p) => p.name).includes(conf.defaultProfile)) { + conf.defaultProfile = conf.profiles[0].name; + } + return merge({}, defaultCfg.config, conf); + } else { + notify('Error reading configuration: `config` key is missing'); + return defaultCfg.config || ({} as configOptions); + } + })(), + // Merging platform specific keymaps with user defined keymaps + keymaps: mapKeys({...defaultCfg.keymaps, ...userCfg?.keymaps}), + // Ignore undefined values in plugin and localPlugins array Issue #1862 + plugins: userCfg?.plugins?.filter(Boolean) || [], + localPlugins: userCfg?.localPlugins?.filter(Boolean) || [] + }; +}; + +export {_init, _extractDefault}; diff --git a/app/config/migrate.ts b/app/config/migrate.ts new file mode 100644 index 00000000..522da1e9 --- /dev/null +++ b/app/config/migrate.ts @@ -0,0 +1,190 @@ +import {dirname, resolve} from 'path'; + +import {builders, namedTypes} from 'ast-types'; +import type {ExpressionKind} from 'ast-types/lib/gen/kinds'; +import {copy, copySync, existsSync, readFileSync, writeFileSync} from 'fs-extra'; +import merge from 'lodash/merge'; +import {parse, prettyPrint} from 'recast'; +import * as babelParser from 'recast/parsers/babel'; + +import notify from '../notify'; + +import {_extractDefault} from './init'; +import {cfgDir, cfgPath, defaultCfg, legacyCfgPath, plugs, schemaFile, schemaPath} from './paths'; + +// function to remove all json serializable entries from an array expression +function removeElements(node: namedTypes.ArrayExpression): namedTypes.ArrayExpression { + const newElements = node.elements.filter((element) => { + if (namedTypes.ObjectExpression.check(element)) { + const newElement = removeProperties(element); + if (newElement.properties.length === 0) { + return false; + } + } else if (namedTypes.ArrayExpression.check(element)) { + const newElement = removeElements(element); + if (newElement.elements.length === 0) { + return false; + } + } else if (namedTypes.Literal.check(element)) { + return false; + } + return true; + }); + return {...node, elements: newElements}; +} + +// function to remove all json serializable properties from an object expression +function removeProperties(node: namedTypes.ObjectExpression): namedTypes.ObjectExpression { + const newProperties = node.properties.filter((property) => { + if ( + namedTypes.ObjectProperty.check(property) && + (namedTypes.Literal.check(property.key) || namedTypes.Identifier.check(property.key)) && + !property.computed + ) { + if (namedTypes.ObjectExpression.check(property.value)) { + const newValue = removeProperties(property.value); + if (newValue.properties.length === 0) { + return false; + } + } else if (namedTypes.ArrayExpression.check(property.value)) { + const newValue = removeElements(property.value); + if (newValue.elements.length === 0) { + return false; + } + } else if (namedTypes.Literal.check(property.value)) { + return false; + } + } + return true; + }); + return {...node, properties: newProperties}; +} + +export function configToPlugin(code: string): string { + const ast: namedTypes.File = parse(code, { + parser: babelParser + }); + const statements = ast.program.body; + let moduleExportsNode: namedTypes.AssignmentExpression | null = null; + let configNode: ExpressionKind | null = null; + + for (const statement of statements) { + if (namedTypes.ExpressionStatement.check(statement)) { + const expression = statement.expression; + if ( + namedTypes.AssignmentExpression.check(expression) && + expression.operator === '=' && + namedTypes.MemberExpression.check(expression.left) && + namedTypes.Identifier.check(expression.left.object) && + expression.left.object.name === 'module' && + namedTypes.Identifier.check(expression.left.property) && + expression.left.property.name === 'exports' + ) { + moduleExportsNode = expression; + if (namedTypes.ObjectExpression.check(expression.right)) { + const properties = expression.right.properties; + for (const property of properties) { + if ( + namedTypes.ObjectProperty.check(property) && + namedTypes.Identifier.check(property.key) && + property.key.name === 'config' + ) { + configNode = property.value as ExpressionKind; + if (namedTypes.ObjectExpression.check(property.value)) { + configNode = removeProperties(property.value); + } + } + } + } else { + configNode = builders.memberExpression(moduleExportsNode.right, builders.identifier('config')); + } + } + } + } + + if (!moduleExportsNode) { + console.log('No module.exports found in config'); + return ''; + } + if (!configNode) { + console.log('No config field found in module.exports'); + return ''; + } + if (namedTypes.ObjectExpression.check(configNode) && configNode.properties.length === 0) { + return ''; + } + + moduleExportsNode.right = builders.objectExpression([ + builders.property( + 'init', + builders.identifier('decorateConfig'), + builders.arrowFunctionExpression( + [builders.identifier('_config')], + builders.callExpression( + builders.memberExpression(builders.identifier('Object'), builders.identifier('assign')), + [builders.objectExpression([]), builders.identifier('_config'), configNode] + ) + ) + ) + ]); + + return prettyPrint(ast, {tabWidth: 2}).code; +} + +export const _write = (path: string, data: string) => { + // This method will take text formatted as Unix line endings and transform it + // to text formatted with DOS line endings. We do this because the default + // text editor on Windows (notepad) doesn't Deal with LF files. Still. In 2017. + const crlfify = (str: string) => { + return str.replace(/\r?\n/g, '\r\n'); + }; + const format = process.platform === 'win32' ? crlfify(data.toString()) : data; + writeFileSync(path, format, 'utf8'); +}; + +// Migrate Hyper3 config to Hyper4 but only if the user hasn't manually +// touched the new config and if the old config is not a symlink +export const migrateHyper3Config = () => { + copy(schemaPath, resolve(cfgDir, schemaFile), (err) => { + if (err) { + console.error(err); + } + }); + + if (existsSync(cfgPath)) { + return; + } + + if (!existsSync(legacyCfgPath)) { + copySync(defaultCfg, cfgPath); + return; + } + + // Migrate + copySync(resolve(dirname(legacyCfgPath), '.hyper_plugins', 'local'), plugs.local); + + const defaultCfgData = JSON.parse(readFileSync(defaultCfg, 'utf8')); + let newCfgData; + try { + const legacyCfgRaw = readFileSync(legacyCfgPath, 'utf8'); + const legacyCfgData = _extractDefault(legacyCfgRaw); + newCfgData = merge({}, defaultCfgData, legacyCfgData); + + const pluginCode = configToPlugin(legacyCfgRaw); + if (pluginCode) { + const pluginPath = resolve(plugs.local, 'migrated-hyper3-config.js'); + newCfgData.localPlugins = ['migrated-hyper3-config', ...(newCfgData.localPlugins || [])]; + _write(pluginPath, pluginCode); + } + } catch (e) { + console.error(e); + notify( + 'Hyper 4', + `Failed to migrate your config from Hyper 3.\nDefault config will be created instead at ${cfgPath}` + ); + newCfgData = defaultCfgData; + } + _write(cfgPath, JSON.stringify(newCfgData, null, 2)); + + notify('Hyper 4', `Settings location and format has changed to ${cfgPath}`); +}; diff --git a/app/config/open.ts b/app/config/open.ts new file mode 100644 index 00000000..264c2292 --- /dev/null +++ b/app/config/open.ts @@ -0,0 +1,80 @@ +import {exec} from 'child_process'; + +import {shell} from 'electron'; + +import * as Registry from 'native-reg'; + +import {cfgPath} from './paths'; + +const getUserChoiceKey = () => { + try { + // Load FileExts keys for .js files + const fileExtsKeys = Registry.openKey( + Registry.HKCU, + 'Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\FileExts\\.js', + Registry.Access.READ + ); + const keys = fileExtsKeys ? Registry.enumKeyNames(fileExtsKeys) : []; + Registry.closeKey(fileExtsKeys); + + // Find UserChoice key + const userChoice = keys.find((k) => k.endsWith('UserChoice')); + return userChoice + ? `Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\FileExts\\.js\\${userChoice}` + : userChoice; + } catch (error) { + console.error(error); + return; + } +}; + +const hasDefaultSet = () => { + const userChoice = getUserChoiceKey(); + if (!userChoice) return false; + + try { + // Load key values + const userChoiceKey = Registry.openKey(Registry.HKCU, userChoice, Registry.Access.READ)!; + const values: string[] = Registry.enumValueNames(userChoiceKey).map( + (x) => (Registry.queryValue(userChoiceKey, x) as string) || '' + ); + Registry.closeKey(userChoiceKey); + + // Look for default program + const hasDefaultProgramConfigured = values.every( + (value) => value && typeof value === 'string' && !value.includes('WScript.exe') && !value.includes('JSFile') + ); + + return hasDefaultProgramConfigured; + } catch (error) { + console.error(error); + return false; + } +}; + +// This mimics shell.openItem, true if it worked, false if not. +const openNotepad = (file: string) => + new Promise((resolve) => { + exec(`start notepad.exe ${file}`, (error) => { + resolve(!error); + }); + }); + +const openConfig = () => { + // Windows opens .js files with WScript.exe by default + // If the user hasn't set up an editor for .js files, we fallback to notepad. + if (process.platform === 'win32') { + try { + if (hasDefaultSet()) { + return shell.openPath(cfgPath).then((error) => error === ''); + } + console.warn('No default app set for .js files, using notepad.exe fallback'); + } catch (err) { + console.error('Open config with default app error:', err); + } + return openNotepad(cfgPath); + } + return shell.openPath(cfgPath).then((error) => error === ''); +}; + +export default openConfig; diff --git a/app/config/paths.ts b/app/config/paths.ts new file mode 100644 index 00000000..2c2ce283 --- /dev/null +++ b/app/config/paths.ts @@ -0,0 +1,96 @@ +// This module exports paths, names, and other metadata that is referenced +import {statSync} from 'fs'; +import {homedir} from 'os'; +import {resolve, join} from 'path'; + +import {app} from 'electron'; + +import isDev from 'electron-is-dev'; + +const cfgFile = 'hyper.json'; +const defaultCfgFile = 'config-default.json'; +const schemaFile = 'schema.json'; +const homeDirectory = homedir(); + +// If the user defines XDG_CONFIG_HOME they definitely want their config there, +// otherwise use the home directory in linux/mac and userdata in windows +let cfgDir = process.env.XDG_CONFIG_HOME + ? join(process.env.XDG_CONFIG_HOME, 'Hyper') + : process.platform === 'win32' + ? app.getPath('userData') + : join(homeDirectory, '.config', 'Hyper'); + +const legacyCfgPath = join( + process.env.XDG_CONFIG_HOME !== undefined + ? join(process.env.XDG_CONFIG_HOME, 'hyper') + : process.platform == 'win32' + ? app.getPath('userData') + : homedir(), + '.hyper.js' +); + +let cfgPath = join(cfgDir, cfgFile); +const schemaPath = resolve(__dirname, schemaFile); + +const devDir = resolve(__dirname, '../..'); +const devCfg = join(devDir, cfgFile); +const defaultCfg = resolve(__dirname, defaultCfgFile); + +if (isDev) { + // if a local config file exists, use it + try { + statSync(devCfg); + cfgPath = devCfg; + cfgDir = devDir; + console.log('using config file:', cfgPath); + } catch (err) { + // ignore + } +} + +const plugins = resolve(cfgDir, 'plugins'); +const plugs = { + base: plugins, + local: resolve(plugins, 'local'), + cache: resolve(plugins, 'cache') +}; +const yarn = resolve(__dirname, '../../bin/yarn-standalone.js'); +const cliScriptPath = resolve(__dirname, '../../bin/hyper'); +const cliLinkPath = '/usr/local/bin/hyper'; + +const icon = resolve(__dirname, '../static/icon96x96.png'); + +const keymapPath = resolve(__dirname, '../keymaps'); +const darwinKeys = join(keymapPath, 'darwin.json'); +const win32Keys = join(keymapPath, 'win32.json'); +const linuxKeys = join(keymapPath, 'linux.json'); + +const defaultPlatformKeyPath = () => { + switch (process.platform) { + case 'darwin': + return darwinKeys; + case 'win32': + return win32Keys; + case 'linux': + return linuxKeys; + default: + return darwinKeys; + } +}; + +export { + cfgDir, + cfgPath, + legacyCfgPath, + cfgFile, + defaultCfg, + icon, + defaultPlatformKeyPath, + plugs, + yarn, + cliScriptPath, + cliLinkPath, + homeDirectory, + schemaFile, + schemaPath +}; diff --git a/app/config/schema.json b/app/config/schema.json new file mode 100644 index 00000000..6bcf8500 --- /dev/null +++ b/app/config/schema.json @@ -0,0 +1,756 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "definitions": { + "FontWeight": { + "anyOf": [ + { + "enum": [ + "100", + "200", + "300", + "400", + "500", + "600", + "700", + "800", + "900", + "bold", + "normal" + ], + "type": "string" + }, + { + "type": "number" + } + ], + "description": "A string or number representing text font weight." + }, + "Partial": { + "properties": { + "backgroundColor": { + "description": "terminal background color\n\nopacity is only supported on macOS", + "type": "string" + }, + "bell": { + "description": "Supported Options:\n1. 'SOUND' -> Enables the bell as a sound\n2. false: turns off the bell", + "enum": [ + "SOUND", + false + ] + }, + "bellSound": { + "description": "base64 encoded string of the sound file to use for the bell\nif null, the default bell will be used", + "type": [ + "string", + "null" + ] + }, + "bellSoundURL": { + "description": "An absolute file path to a sound file on the machine.", + "type": [ + "string", + "null" + ] + }, + "borderColor": { + "description": "border color (window, tabs)", + "type": "string" + }, + "colors": { + "description": "the full list. if you're going to provide the full color palette,\nincluding the 6 x 6 color cubes and the grayscale map, just provide\nan array here instead of a color map object", + "properties": { + "black": { + "type": "string" + }, + "blue": { + "type": "string" + }, + "cyan": { + "type": "string" + }, + "green": { + "type": "string" + }, + "lightBlack": { + "type": "string" + }, + "lightBlue": { + "type": "string" + }, + "lightCyan": { + "type": "string" + }, + "lightGreen": { + "type": "string" + }, + "lightMagenta": { + "type": "string" + }, + "lightRed": { + "type": "string" + }, + "lightWhite": { + "type": "string" + }, + "lightYellow": { + "type": "string" + }, + "magenta": { + "type": "string" + }, + "red": { + "type": "string" + }, + "white": { + "type": "string" + }, + "yellow": { + "type": "string" + } + }, + "required": [ + "black", + "blue", + "cyan", + "green", + "lightBlack", + "lightBlue", + "lightCyan", + "lightGreen", + "lightMagenta", + "lightRed", + "lightWhite", + "lightYellow", + "magenta", + "red", + "white", + "yellow" + ], + "type": "object" + }, + "copyOnSelect": { + "description": "if `true` selected text will automatically be copied to the clipboard", + "type": "boolean" + }, + "css": { + "description": "custom CSS to embed in the main window", + "type": "string" + }, + "cursorAccentColor": { + "description": "terminal text color under BLOCK cursor", + "type": "string" + }, + "cursorBlink": { + "description": "set to `true` for blinking cursor", + "type": "boolean" + }, + "cursorColor": { + "description": "terminal cursor background color and opacity (hex, rgb, hsl, hsv, hwb or cmyk)", + "type": "string" + }, + "cursorShape": { + "description": "`'BEAM'` for |, `'UNDERLINE'` for _, `'BLOCK'` for █", + "enum": [ + "BEAM", + "BLOCK", + "UNDERLINE" + ], + "type": "string" + }, + "disableLigatures": { + "description": "if `false` Hyper will use ligatures provided by some fonts", + "type": "boolean" + }, + "env": { + "additionalProperties": { + "type": "string" + }, + "description": "for environment variables", + "type": "object" + }, + "fontFamily": { + "description": "font family with optional fallbacks", + "type": "string" + }, + "fontSize": { + "description": "default font size in pixels for all tabs", + "type": "number" + }, + "fontWeight": { + "$ref": "#/definitions/FontWeight", + "description": "default font weight eg:'normal', '400', 'bold'" + }, + "fontWeightBold": { + "$ref": "#/definitions/FontWeight", + "description": "font weight for bold characters eg:'normal', '600', 'bold'" + }, + "foregroundColor": { + "description": "color of the text", + "type": "string" + }, + "imageSupport": { + "description": "Whether to enable Sixel and iTerm2 inline image protocol support or not.", + "type": "boolean" + }, + "letterSpacing": { + "description": "letter spacing as a relative unit", + "type": "number" + }, + "lineHeight": { + "description": "line height as a relative unit", + "type": "number" + }, + "macOptionSelectionMode": { + "description": "choose either `'vertical'`, if you want the column mode when Option key is hold during selection (Default)\nor `'force'`, if you want to force selection regardless of whether the terminal is in mouse events mode\n(inside tmux or vim with mouse mode enabled for example).", + "type": "string" + }, + "modifierKeys": { + "properties": { + "altIsMeta": { + "type": "boolean" + }, + "cmdIsMeta": { + "type": "boolean" + } + }, + "required": [ + "altIsMeta", + "cmdIsMeta" + ], + "type": "object" + }, + "padding": { + "description": "custom padding (CSS format, i.e.: `top right bottom left` or `top horizontal bottom` or `vertical horizontal` or `all`)", + "type": "string" + }, + "preserveCWD": { + "description": "set to true to preserve working directory when creating splits or tabs", + "type": "boolean" + }, + "quickEdit": { + "description": "if `true` on right click selected text will be copied or pasted if no\nselection is present (`true` by default on Windows and disables the context menu feature)", + "type": "boolean" + }, + "screenReaderMode": { + "description": "set to true to enable screen reading apps (like NVDA) to read the contents of the terminal", + "type": "boolean" + }, + "scrollback": { + "type": "number" + }, + "selectionColor": { + "description": "terminal selection color", + "type": "string" + }, + "shell": { + "description": "the shell to run when spawning a new session (e.g. /usr/local/bin/fish)\nif left empty, your system's login shell will be used by default\n\nWindows\n- Make sure to use a full path if the binary name doesn't work\n- Remove `--login` in shellArgs\n\nWindows Subsystem for Linux (WSL) - previously Bash on Windows\n- Example: `C:\\\\Windows\\\\System32\\\\wsl.exe`\n\nGit-bash on Windows\n- Example: `C:\\\\Program Files\\\\Git\\\\bin\\\\bash.exe`\n\nPowerShell on Windows\n- Example: `C:\\\\WINDOWS\\\\System32\\\\WindowsPowerShell\\\\v1.0\\\\powershell.exe`\n\nCygwin\n- Example: `C:\\\\cygwin64\\\\bin\\\\bash.exe`\n\nGit Bash\n- Example: `C:\\\\Program Files\\\\Git\\\\git-cmd.exe`\nThen Add `--command=usr/bin/bash.exe` to shellArgs", + "type": "string" + }, + "shellArgs": { + "description": "for setting shell arguments (e.g. for using interactive shellArgs: `['-i']`)\nby default `['--login']` will be used", + "items": { + "type": "string" + }, + "type": "array" + }, + "showHamburgerMenu": { + "description": "if you're using a Linux setup which show native menus, set to false\n\ndefault: `true` on Linux, `true` on Windows, ignored on macOS", + "enum": [ + "", + false, + true + ] + }, + "showWindowControls": { + "description": "set to `false` if you want to hide the minimize, maximize and close buttons\n\nadditionally, set to `'left'` if you want them on the left, like in Ubuntu\n\ndefault: `true` on Windows and Linux, ignored on macOS", + "enum": [ + "", + false, + "left", + true + ] + }, + "termCSS": { + "description": "custom CSS to embed in the terminal window", + "type": "string" + }, + "uiFontFamily": { + "type": "string" + }, + "webGLRenderer": { + "description": "Whether to use the WebGL renderer. Set it to false to use canvas-based\nrendering (slower, but supports transparent backgrounds)", + "type": "boolean" + }, + "webLinksActivationKey": { + "description": "keypress required for weblink activation: [ctrl | alt | meta | shift]", + "enum": [ + "", + "alt", + "ctrl", + "meta", + "shift" + ], + "type": "string" + }, + "windowSize": { + "description": "Initial window size in pixels", + "items": [ + { + "type": "number" + }, + { + "type": "number" + } + ], + "maxItems": 2, + "minItems": 2, + "type": "array" + }, + "workingDirectory": { + "description": "set custom startup directory (must be an absolute path)", + "type": "string" + } + }, + "type": "object" + }, + "configOptions": { + "allOf": [ + { + "properties": { + "autoUpdatePlugins": { + "description": "if `true` (default), Hyper will update plugins every 5 hours\nyou can also set it to a custom time e.g. `1d` or `2h`", + "type": [ + "string", + "boolean" + ] + }, + "defaultSSHApp": { + "description": "if `true` hyper will be set as the default protocol client for SSH", + "type": "boolean" + }, + "disableAutoUpdates": { + "description": "if `true` hyper will not check for updates", + "type": "boolean" + }, + "updateChannel": { + "description": "choose either `'stable'` for receiving highly polished, or `'canary'` for less polished but more frequent updates", + "enum": [ + "canary", + "stable" + ], + "type": "string" + }, + "useConpty": { + "type": "boolean" + } + }, + "required": [ + "autoUpdatePlugins", + "defaultSSHApp", + "disableAutoUpdates", + "updateChannel" + ], + "type": "object" + }, + { + "properties": { + "backgroundColor": { + "description": "terminal background color\n\nopacity is only supported on macOS", + "type": "string" + }, + "bell": { + "description": "Supported Options:\n1. 'SOUND' -> Enables the bell as a sound\n2. false: turns off the bell", + "enum": [ + "SOUND", + false + ] + }, + "bellSound": { + "description": "base64 encoded string of the sound file to use for the bell\nif null, the default bell will be used", + "type": [ + "string", + "null" + ] + }, + "bellSoundURL": { + "description": "An absolute file path to a sound file on the machine.", + "type": [ + "string", + "null" + ] + }, + "borderColor": { + "description": "border color (window, tabs)", + "type": "string" + }, + "colors": { + "description": "the full list. if you're going to provide the full color palette,\nincluding the 6 x 6 color cubes and the grayscale map, just provide\nan array here instead of a color map object", + "properties": { + "black": { + "type": "string" + }, + "blue": { + "type": "string" + }, + "cyan": { + "type": "string" + }, + "green": { + "type": "string" + }, + "lightBlack": { + "type": "string" + }, + "lightBlue": { + "type": "string" + }, + "lightCyan": { + "type": "string" + }, + "lightGreen": { + "type": "string" + }, + "lightMagenta": { + "type": "string" + }, + "lightRed": { + "type": "string" + }, + "lightWhite": { + "type": "string" + }, + "lightYellow": { + "type": "string" + }, + "magenta": { + "type": "string" + }, + "red": { + "type": "string" + }, + "white": { + "type": "string" + }, + "yellow": { + "type": "string" + } + }, + "required": [ + "black", + "blue", + "cyan", + "green", + "lightBlack", + "lightBlue", + "lightCyan", + "lightGreen", + "lightMagenta", + "lightRed", + "lightWhite", + "lightYellow", + "magenta", + "red", + "white", + "yellow" + ], + "type": "object" + }, + "copyOnSelect": { + "description": "if `true` selected text will automatically be copied to the clipboard", + "type": "boolean" + }, + "css": { + "description": "custom CSS to embed in the main window", + "type": "string" + }, + "cursorAccentColor": { + "description": "terminal text color under BLOCK cursor", + "type": "string" + }, + "cursorBlink": { + "description": "set to `true` for blinking cursor", + "type": "boolean" + }, + "cursorColor": { + "description": "terminal cursor background color and opacity (hex, rgb, hsl, hsv, hwb or cmyk)", + "type": "string" + }, + "cursorShape": { + "description": "`'BEAM'` for |, `'UNDERLINE'` for _, `'BLOCK'` for █", + "enum": [ + "BEAM", + "BLOCK", + "UNDERLINE" + ], + "type": "string" + }, + "disableLigatures": { + "description": "if `false` Hyper will use ligatures provided by some fonts", + "type": "boolean" + }, + "env": { + "additionalProperties": { + "type": "string" + }, + "description": "for environment variables", + "type": "object" + }, + "fontFamily": { + "description": "font family with optional fallbacks", + "type": "string" + }, + "fontSize": { + "description": "default font size in pixels for all tabs", + "type": "number" + }, + "fontWeight": { + "$ref": "#/definitions/FontWeight", + "description": "default font weight eg:'normal', '400', 'bold'" + }, + "fontWeightBold": { + "$ref": "#/definitions/FontWeight", + "description": "font weight for bold characters eg:'normal', '600', 'bold'" + }, + "foregroundColor": { + "description": "color of the text", + "type": "string" + }, + "imageSupport": { + "description": "Whether to enable Sixel and iTerm2 inline image protocol support or not.", + "type": "boolean" + }, + "letterSpacing": { + "description": "letter spacing as a relative unit", + "type": "number" + }, + "lineHeight": { + "description": "line height as a relative unit", + "type": "number" + }, + "macOptionSelectionMode": { + "description": "choose either `'vertical'`, if you want the column mode when Option key is hold during selection (Default)\nor `'force'`, if you want to force selection regardless of whether the terminal is in mouse events mode\n(inside tmux or vim with mouse mode enabled for example).", + "type": "string" + }, + "modifierKeys": { + "properties": { + "altIsMeta": { + "type": "boolean" + }, + "cmdIsMeta": { + "type": "boolean" + } + }, + "required": [ + "altIsMeta", + "cmdIsMeta" + ], + "type": "object" + }, + "padding": { + "description": "custom padding (CSS format, i.e.: `top right bottom left` or `top horizontal bottom` or `vertical horizontal` or `all`)", + "type": "string" + }, + "preserveCWD": { + "description": "set to true to preserve working directory when creating splits or tabs", + "type": "boolean" + }, + "quickEdit": { + "description": "if `true` on right click selected text will be copied or pasted if no\nselection is present (`true` by default on Windows and disables the context menu feature)", + "type": "boolean" + }, + "screenReaderMode": { + "description": "set to true to enable screen reading apps (like NVDA) to read the contents of the terminal", + "type": "boolean" + }, + "scrollback": { + "type": "number" + }, + "selectionColor": { + "description": "terminal selection color", + "type": "string" + }, + "shell": { + "description": "the shell to run when spawning a new session (e.g. /usr/local/bin/fish)\nif left empty, your system's login shell will be used by default\n\nWindows\n- Make sure to use a full path if the binary name doesn't work\n- Remove `--login` in shellArgs\n\nWindows Subsystem for Linux (WSL) - previously Bash on Windows\n- Example: `C:\\\\Windows\\\\System32\\\\wsl.exe`\n\nGit-bash on Windows\n- Example: `C:\\\\Program Files\\\\Git\\\\bin\\\\bash.exe`\n\nPowerShell on Windows\n- Example: `C:\\\\WINDOWS\\\\System32\\\\WindowsPowerShell\\\\v1.0\\\\powershell.exe`\n\nCygwin\n- Example: `C:\\\\cygwin64\\\\bin\\\\bash.exe`\n\nGit Bash\n- Example: `C:\\\\Program Files\\\\Git\\\\git-cmd.exe`\nThen Add `--command=usr/bin/bash.exe` to shellArgs", + "type": "string" + }, + "shellArgs": { + "description": "for setting shell arguments (e.g. for using interactive shellArgs: `['-i']`)\nby default `['--login']` will be used", + "items": { + "type": "string" + }, + "type": "array" + }, + "showHamburgerMenu": { + "description": "if you're using a Linux setup which show native menus, set to false\n\ndefault: `true` on Linux, `true` on Windows, ignored on macOS", + "enum": [ + "", + false, + true + ] + }, + "showWindowControls": { + "description": "set to `false` if you want to hide the minimize, maximize and close buttons\n\nadditionally, set to `'left'` if you want them on the left, like in Ubuntu\n\ndefault: `true` on Windows and Linux, ignored on macOS", + "enum": [ + "", + false, + "left", + true + ] + }, + "termCSS": { + "description": "custom CSS to embed in the terminal window", + "type": "string" + }, + "uiFontFamily": { + "type": "string" + }, + "webGLRenderer": { + "description": "Whether to use the WebGL renderer. Set it to false to use canvas-based\nrendering (slower, but supports transparent backgrounds)", + "type": "boolean" + }, + "webLinksActivationKey": { + "description": "keypress required for weblink activation: [ctrl | alt | meta | shift]", + "enum": [ + "", + "alt", + "ctrl", + "meta", + "shift" + ], + "type": "string" + }, + "windowSize": { + "description": "Initial window size in pixels", + "items": [ + { + "type": "number" + }, + { + "type": "number" + } + ], + "maxItems": 2, + "minItems": 2, + "type": "array" + }, + "workingDirectory": { + "description": "set custom startup directory (must be an absolute path)", + "type": "string" + } + }, + "required": [ + "backgroundColor", + "bell", + "bellSound", + "bellSoundURL", + "borderColor", + "colors", + "copyOnSelect", + "css", + "cursorAccentColor", + "cursorBlink", + "cursorColor", + "cursorShape", + "disableLigatures", + "env", + "fontFamily", + "fontSize", + "fontWeight", + "fontWeightBold", + "foregroundColor", + "imageSupport", + "letterSpacing", + "lineHeight", + "macOptionSelectionMode", + "padding", + "preserveCWD", + "quickEdit", + "screenReaderMode", + "scrollback", + "selectionColor", + "shell", + "shellArgs", + "showHamburgerMenu", + "showWindowControls", + "termCSS", + "webGLRenderer", + "webLinksActivationKey", + "workingDirectory" + ], + "type": "object" + }, + { + "properties": { + "defaultProfile": { + "description": "The default profile name to use when launching a new session", + "type": "string" + }, + "profiles": { + "description": "A list of profiles to use", + "items": { + "properties": { + "config": { + "$ref": "#/definitions/Partial", + "description": "Specify all the options you want to override for each profile.\nOptions set here override the defaults set in the root." + }, + "name": { + "type": "string" + } + }, + "required": [ + "config", + "name" + ], + "type": "object" + }, + "type": "array" + } + }, + "required": [ + "defaultProfile", + "profiles" + ], + "type": "object" + } + ] + } + }, + "properties": { + "config": { + "$ref": "#/definitions/configOptions" + }, + "keymaps": { + "additionalProperties": { + "anyOf": [ + { + "items": { + "type": "string" + }, + "type": "array" + }, + { + "type": "string" + } + ] + }, + "description": "Example\n'window:devtools': 'cmd+alt+o',", + "type": "object" + }, + "localPlugins": { + "description": "in development, you can create a directory under\n`plugins/local/` and include it here\nto load it and avoid it being `npm install`ed", + "items": { + "type": "string" + }, + "type": "array" + }, + "plugins": { + "description": "a list of plugins to fetch and install from npm\nformat: [@org/]project[#version]\nexamples:\n `hyperpower`\n `@company/project`\n `project#1.0.1`", + "items": { + "type": "string" + }, + "type": "array" + } + }, + "type": "object" +} + diff --git a/app/config/windows.ts b/app/config/windows.ts new file mode 100644 index 00000000..4cd6d500 --- /dev/null +++ b/app/config/windows.ts @@ -0,0 +1,21 @@ +import type {BrowserWindow} from 'electron'; + +import Config from 'electron-store'; + +export const defaults = { + windowPosition: [50, 50] as [number, number], + windowSize: [540, 380] as [number, number] +}; + +// local storage +const cfg = new Config({defaults}); + +export function get() { + const position = cfg.get('windowPosition', defaults.windowPosition); + const size = cfg.get('windowSize', defaults.windowSize); + return {position, size}; +} +export function recordState(win: BrowserWindow) { + cfg.set('windowPosition', win.getPosition()); + cfg.set('windowSize', win.getSize()); +} diff --git a/app/index.html b/app/index.html index 98a7ab38..3d16602e 100644 --- a/app/index.html +++ b/app/index.html @@ -5,10 +5,12 @@ + + + ); +}); + +Header.displayName = 'Header'; + +export default Header; diff --git a/lib/components/new-tab.tsx b/lib/components/new-tab.tsx new file mode 100644 index 00000000..3fe99543 --- /dev/null +++ b/lib/components/new-tab.tsx @@ -0,0 +1,149 @@ +import React, {useRef, useState} from 'react'; + +import {VscChevronDown} from '@react-icons/all-files/vsc/VscChevronDown'; +import useClickAway from 'react-use/lib/useClickAway'; + +import type {configOptions} from '../../typings/config'; + +interface Props { + defaultProfile: string; + profiles: configOptions['profiles']; + openNewTab: (name: string) => void; + backgroundColor: string; + borderColor: string; + tabsVisible: boolean; +} +const isMac = /Mac/.test(navigator.userAgent); + +const DropdownButton = ({defaultProfile, profiles, openNewTab, backgroundColor, borderColor, tabsVisible}: Props) => { + const [dropdownOpen, setDropdownOpen] = useState(false); + const ref = useRef(null); + + const toggleDropdown = () => { + setDropdownOpen(!dropdownOpen); + }; + + useClickAway(ref, () => { + setDropdownOpen(false); + }); + + return ( +
e.stopPropagation()} + onBlur={() => setDropdownOpen(false)} + > + + + {dropdownOpen && ( +
    + {profiles.map((profile) => ( +
  • { + openNewTab(profile.name); + setDropdownOpen(false); + }} + className={`profile_dropdown_item ${ + profile.name === defaultProfile && profiles.length > 1 ? 'profile_dropdown_item_default' : '' + }`} + > + {profile.name} +
  • + ))} +
+ )} + + +
+ ); +}; + +export default DropdownButton; diff --git a/lib/components/notification.js b/lib/components/notification.js deleted file mode 100644 index 855d558a..00000000 --- a/lib/components/notification.js +++ /dev/null @@ -1,125 +0,0 @@ -import React from 'react'; -import Component from '../component'; - -export default class Notification extends Component { - - constructor() { - super(); - this.state = { - dismissing: false - }; - this.handleDismiss = this.handleDismiss.bind(this); - this.onElement = this.onElement.bind(this); - } - - componentDidMount() { - if (this.props.dismissAfter) { - this.setDismissTimer(); - } - } - - componentWillReceiveProps(next) { - // if we have a timer going and the notification text - // changed we reset the timer - if (next.text !== this.props.text) { - if (this.props.dismissAfter) { - this.resetDismissTimer(); - } - if (this.state.dismissing) { - this.setState({dismissing: false}); - } - } - } - - handleDismiss() { - this.setState({dismissing: true}); - } - - onElement(el) { - if (el) { - el.addEventListener('webkitTransitionEnd', () => { - if (this.state.dismissing) { - this.props.onDismiss(); - } - }); - const {backgroundColor} = this.props; - if (backgroundColor) { - el.style.setProperty( - 'background-color', - backgroundColor, - 'important' - ); - } - } - } - - setDismissTimer() { - this.dismissTimer = setTimeout(() => { - this.handleDismiss(); - }, this.props.dismissAfter); - } - - resetDismissTimer() { - clearTimeout(this.dismissTimer); - this.setDismissTimer(); - } - - componentWillUnmount() { - clearTimeout(this.dismissTimer); - } - - template(css) { - const {backgroundColor} = this.props; - const opacity = this.state.dismissing ? 0 : 1; - return (
- { this.props.customChildrenBefore } - { this.props.children || this.props.text } - { - this.props.userDismissable ? - [x] : - null - } - { this.props.customChildren } -
); - } - - styles() { - return { - indicator: { - display: 'inline-block', - cursor: 'default', - WebkitUserSelect: 'none', - background: 'rgba(255, 255, 255, .2)', - borderRadius: '2px', - padding: '8px 14px 9px', - marginLeft: '10px', - transition: '150ms opacity ease', - color: '#fff', - fontSize: '11px', - fontFamily: `-apple-system, BlinkMacSystemFont, - "Segoe UI", "Roboto", "Oxygen", - "Ubuntu", "Cantarell", "Fira Sans", - "Droid Sans", "Helvetica Neue", sans-serif` - }, - - dismissLink: { - position: 'relative', - left: '4px', - cursor: 'pointer', - color: '#528D11', - ':hover': { - color: '#2A5100' - } - } - }; - } - -} diff --git a/lib/components/notification.tsx b/lib/components/notification.tsx new file mode 100644 index 00000000..68b7a2df --- /dev/null +++ b/lib/components/notification.tsx @@ -0,0 +1,110 @@ +import React, {forwardRef, useEffect, useRef, useState} from 'react'; + +import type {NotificationProps} from '../../typings/hyper'; + +const Notification = forwardRef>((props, ref) => { + const dismissTimer = useRef(undefined); + const [dismissing, setDismissing] = useState(false); + + useEffect(() => { + setDismissTimer(); + }, []); + + useEffect(() => { + // if we have a timer going and the notification text + // changed we reset the timer + resetDismissTimer(); + setDismissing(false); + }, [props.text]); + + const handleDismiss = () => { + setDismissing(true); + }; + + const onElement = (el: HTMLDivElement | null) => { + if (el) { + el.addEventListener('webkitTransitionEnd', () => { + if (dismissing) { + props.onDismiss(); + } + }); + const {backgroundColor} = props; + if (backgroundColor) { + el.style.setProperty('background-color', backgroundColor, 'important'); + } + + if (ref) { + if (typeof ref === 'function') ref(el); + else ref.current = el; + } + } + }; + + const setDismissTimer = () => { + if (typeof props.dismissAfter === 'number') { + dismissTimer.current = setTimeout(() => { + handleDismiss(); + }, props.dismissAfter); + } + }; + + const resetDismissTimer = () => { + clearTimeout(dismissTimer.current); + setDismissTimer(); + }; + + useEffect(() => { + return () => { + clearTimeout(dismissTimer.current); + }; + }, []); + + const {backgroundColor, color} = props; + const opacity = dismissing ? 0 : 1; + return ( +
+ {props.customChildrenBefore} + {props.children || props.text} + {props.userDismissable ? ( + + [x] + + ) : null} + {props.customChildren} + + +
+ ); +}); + +Notification.displayName = 'Notification'; + +export default Notification; diff --git a/lib/components/notifications.js b/lib/components/notifications.js deleted file mode 100644 index 75a0b12a..00000000 --- a/lib/components/notifications.js +++ /dev/null @@ -1,115 +0,0 @@ -import React from 'react'; - -import Component from '../component'; -import {decorate} from '../utils/plugins'; - -import Notification_ from './notification'; - -const Notification = decorate(Notification_); - -export default class Notifications extends Component { - - template(css) { - return (
- { this.props.customChildrenBefore } - { - this.props.fontShowing && - - } - - { - this.props.resizeShowing && - - } - - { - this.props.messageShowing && - { - this.props.messageURL ? [ - this.props.messageText, - ' (', - { - window.require('electron').shell.openExternal(ev.target.href); - ev.preventDefault(); - }} - href={this.props.messageURL} - >more, - ')' - ] : null - } - - } - - { - this.props.updateShowing && - - Version {this.props.updateVersion} ready. - {this.props.updateNote && ` ${this.props.updateNote.trim().replace(/\.$/, '')}`} - {' '} - ( { - window.require('electron').shell.openExternal(ev.target.href); - ev.preventDefault(); - }} - href={`https://github.com/zeit/hyper/releases/tag/${this.props.updateVersion}`} - >notes). - {' '} - - Restart - . - { ' ' } - - } - { this.props.customChildren } -
); - } - - styles() { - return { - view: { - position: 'fixed', - bottom: '20px', - right: '20px' - } - }; - } - -} diff --git a/lib/components/notifications.tsx b/lib/components/notifications.tsx new file mode 100644 index 00000000..79e6ede3 --- /dev/null +++ b/lib/components/notifications.tsx @@ -0,0 +1,132 @@ +import React, {forwardRef} from 'react'; + +import type {NotificationsProps} from '../../typings/hyper'; +import {decorate} from '../utils/plugins'; + +import Notification_ from './notification'; + +const Notification = decorate(Notification_, 'Notification'); + +const Notifications = forwardRef((props, ref) => { + return ( +
+ {props.customChildrenBefore} + {props.fontShowing && ( + + )} + + {props.resizeShowing && ( + + )} + + {props.messageShowing && ( + + {props.messageURL ? ( + <> + {props.messageText} ( + { + void window.require('electron').shell.openExternal(ev.currentTarget.href); + ev.preventDefault(); + }} + href={props.messageURL} + > + more + + ) + + ) : null} + + )} + + {props.updateShowing && ( + + Version {props.updateVersion} ready. + {props.updateNote && ` ${props.updateNote.trim().replace(/\.$/, '')}`} ( + { + void window.require('electron').shell.openExternal(ev.currentTarget.href); + ev.preventDefault(); + }} + href={`https://github.com/vercel/hyper/releases/tag/${props.updateVersion}`} + > + notes + + ).{' '} + {props.updateCanInstall ? ( + + Restart + + ) : ( + { + void window.require('electron').shell.openExternal(ev.currentTarget.href); + ev.preventDefault(); + }} + href={props.updateReleaseUrl!} + > + Download + + )} + .{' '} + + )} + {props.customChildren} + + +
+ ); +}); + +Notifications.displayName = 'Notifications'; + +export default Notifications; diff --git a/lib/components/searchBox.tsx b/lib/components/searchBox.tsx new file mode 100644 index 00000000..55a72f16 --- /dev/null +++ b/lib/components/searchBox.tsx @@ -0,0 +1,237 @@ +import React, {useCallback, useRef, useEffect, forwardRef} from 'react'; + +import {VscArrowDown} from '@react-icons/all-files/vsc/VscArrowDown'; +import {VscArrowUp} from '@react-icons/all-files/vsc/VscArrowUp'; +import {VscCaseSensitive} from '@react-icons/all-files/vsc/VscCaseSensitive'; +import {VscClose} from '@react-icons/all-files/vsc/VscClose'; +import {VscRegex} from '@react-icons/all-files/vsc/VscRegex'; +import {VscWholeWord} from '@react-icons/all-files/vsc/VscWholeWord'; +import clsx from 'clsx'; + +import type {SearchBoxProps} from '../../typings/hyper'; + +type SearchButtonColors = { + foregroundColor: string; + selectionColor: string; + backgroundColor: string; +}; + +type SearchButtonProps = React.PropsWithChildren< + { + onClick: () => void; + active: boolean; + title: string; + } & SearchButtonColors +>; + +const SearchButton = ({ + onClick, + active, + title, + foregroundColor, + backgroundColor, + selectionColor, + children +}: SearchButtonProps) => { + const handleKeyUp = useCallback( + (event: React.KeyboardEvent) => { + if (event.key === 'Enter' || event.key === ' ') { + onClick(); + } + }, + [onClick] + ); + + return ( +
+ {children} + +
+ ); +}; + +const SearchBox = forwardRef((props, ref) => { + const { + caseSensitive, + wholeWord, + regex, + results, + toggleCaseSensitive, + toggleWholeWord, + toggleRegex, + next, + prev, + close, + backgroundColor, + foregroundColor, + borderColor, + selectionColor, + font + } = props; + + const searchTermRef = useRef(''); + const inputRef = useRef(null); + + const handleChange = useCallback( + (event: React.KeyboardEvent) => { + searchTermRef.current = event.currentTarget.value; + if (event.shiftKey && event.key === 'Enter') { + prev(searchTermRef.current); + } else if (event.key === 'Enter') { + next(searchTermRef.current); + } + }, + [prev, next] + ); + + useEffect(() => { + inputRef.current?.focus(); + }, [inputRef.current]); + + const searchButtonColors: SearchButtonColors = { + backgroundColor: borderColor, + selectionColor, + foregroundColor + }; + + return ( +
+
+ + + + + + + + + + + + + +
+ + + {results === undefined + ? '' + : results.resultCount === 0 + ? 'No results' + : `${results.resultIndex + 1} of ${results.resultCount}`} + + +
+ prev(searchTermRef.current)} + active={false} + title="Previous Match" + {...searchButtonColors} + > + + + + next(searchTermRef.current)} + active={false} + title="Next Match" + {...searchButtonColors} + > + + + + + + +
+ + +
+ ); +}); + +SearchBox.displayName = 'SearchBox'; + +export default SearchBox; diff --git a/lib/components/split-pane.js b/lib/components/split-pane.js deleted file mode 100644 index d23d9aea..00000000 --- a/lib/components/split-pane.js +++ /dev/null @@ -1,191 +0,0 @@ -/* eslint-disable quote-props */ -import React from 'react'; -import Component from '../component'; - -export default class SplitPane extends Component { - - constructor(props) { - super(props); - this.handleDragStart = this.handleDragStart.bind(this); - this.onDrag = this.onDrag.bind(this); - this.onDragEnd = this.onDragEnd.bind(this); - this.state = {dragging: false}; - } - - componentDidUpdate(prevProps) { - if (this.state.dragging && prevProps.sizes !== this.props.sizes) { - // recompute positions for ongoing dragging - this.dragPanePosition = this.dragTarget.getBoundingClientRect()[this.d2]; - } - } - - handleDragStart(ev) { - ev.preventDefault(); - this.setState({dragging: true}); - window.addEventListener('mousemove', this.onDrag); - window.addEventListener('mouseup', this.onDragEnd); - - // dimensions to consider - if (this.props.direction === 'horizontal') { - this.d1 = 'height'; - this.d2 = 'top'; - this.d3 = 'clientY'; - } else { - this.d1 = 'width'; - this.d2 = 'left'; - this.d3 = 'clientX'; - } - - this.dragTarget = ev.target; - this.dragPanePosition = this.dragTarget.getBoundingClientRect()[this.d2]; - this.panes = Array.from(ev.target.parentNode.childNodes); - this.panesSize = ev.target.parentNode.getBoundingClientRect()[this.d1]; - this.paneIndex = this.panes.indexOf(ev.target); - this.paneIndex -= Math.ceil(this.paneIndex / 2); - } - - onDrag(ev) { - let {sizes} = this.props; - let sizes_; - if (sizes) { - sizes_ = [].concat(sizes); - } else { - const total = this.props.children.length; - sizes = sizes_ = new Array(total).fill(1 / total); - } - const i = this.paneIndex; - const pos = ev[this.d3]; - const d = Math.abs(this.dragPanePosition - pos) / this.panesSize; - if (pos > this.dragPanePosition) { - sizes_[i] += d; - sizes_[i + 1] -= d; - } else { - sizes_[i] -= d; - sizes_[i + 1] += d; - } - this.props.onResize(sizes_); - } - - onDragEnd() { - if (this.state.dragging) { - window.removeEventListener('mousemove', this.onDrag); - window.removeEventListener('mouseup', this.onDragEnd); - this.setState({dragging: false}); - } - } - - template(css) { - const children = this.props.children; - const {direction, borderColor} = this.props; - let {sizes} = this.props; - if (!sizes) { - // workaround for the fact that if we don't specify - // sizes, sometimes flex fails to calculate the - // right height for the horizontal panes - sizes = new Array(children.length).fill(1 / children.length); - } - return (
- { - React.Children.map(children, (child, i) => { - const style = { - flexBasis: (sizes[i] * 100) + '%', - flexGrow: 0 - }; - return [ -
- { child } -
, - i < children.length - 1 ? -
: - null - ]; - }) - } -
-
); - } - - styles() { - return { - panes: { - display: 'flex', - flex: 1, - outline: 'none', - position: 'relative', - width: '100%', - height: '100%' - }, - - 'panes_vertical': { - flexDirection: 'row' - }, - - 'panes_horizontal': { - flexDirection: 'column' - }, - - pane: { - flex: 1, - outline: 'none', - position: 'relative' - }, - - divider: { - boxSizing: 'border-box', - zIndex: '1', - backgroundClip: 'padding-box', - flexShrink: 0 - }, - - 'divider_vertical': { - borderLeft: '5px solid rgba(255, 255, 255, 0)', - borderRight: '5px solid rgba(255, 255, 255, 0)', - width: '11px', - margin: '0 -5px', - cursor: 'col-resize' - }, - - 'divider_horizontal': { - height: '11px', - margin: '-5px 0', - borderTop: '5px solid rgba(255, 255, 255, 0)', - borderBottom: '5px solid rgba(255, 255, 255, 0)', - cursor: 'row-resize', - width: '100%' - }, - - // this shim is used to make sure mousemove events - // trigger in all the draggable area of the screen - // - // this is not the case due to hterm's