Giter VIP home page Giter VIP logo

btt's Introduction

btt

Package logo

Package version Vunerabilities

Vunerabilitiesn

Manage your BetterTouchTool in JavaScript, easily.

Get started

See the guide and api for btt.js.

About

This package is a handy wrapper over BetterTouchTool built in webserver API. (by @Andreas Hegenberg)

This package will allow you to automate you MacOS-running machine using JavaScript. You'll be able to:

  • Create event listeners that'll run within an operating system, outside the browser!
  • Toggle your do-not-disturb state
  • Show a system notification
  • Toggle Night Shift
  • Sleep your computer after timeout
  • Create your own touchbar widgets
  • Feel a notification via haptic engine
  • Control the brightness of the screen and keyboard
  • Control the volume levels
  • Use the content of your clipboard to be opened in a specific url or application
  • Create your own UIs "within system" using web view
  • Trigger a system-wide keyboard shortcut
  • Send a shortcut to a specific application
  • Show / Hide / Open / Quit a specific applcation
  • Move your mouse to a specific position and click
  • Hide your cursor
  • Lock / Unlock your MacOS machine
  • Integrate your flow / touchbar with various APIs ...

and anything else that BetterTouchTool or the JavaScript specification will allow you to do!

Typed, browser/server side library

This package provides its own type definitions and can be run both on browser (using module bundlers) and in a nodejs environment.

Requirements

This package depends on the application BetterTouchTool in at least version v2.0.0, you need to have it installed and running before going further.

Then, please enable and configure the webserver in the BetterTouchTool preferences. You're now ready to go!

Installation

npm install btt

Example usage

First, create a btt instance passing the required data for BTT webserver.

// import Btt class from the package
import { Btt } from 'btt';

// create an instance representing btt webserver
// can be remote or local
const btt = new Btt({
  domain: '127.0.0.1',
  port: 8000,
  protocol: 'http',
  version: '2.525',
});

Now you can invoke the actions - there are plenty of ways to do it, and all are promise-based.

// sequentially run three actions - spotlight, type text and night shift
// as all actions are promise-based, you can use async/await notation without hassle
btt
  .triggerShortcut('cmd+space').invoke()
  .then(() => btt.sendText({ text: 'Hello world!'}).invoke())
  .then(() => btt.toggleNightShift().invoke());

Response structure for every action

// every single action returns a CallResult object containing information about the Call

interface CallResult {
  time: number;     // contains time in MS that this action took to perform (including fetch time)
  status: number;   // contains an HTTP status / string
  value: any;       // depending on the method used, may return an array, object or fetch result
  note?: string;    // an additional note for the user
}

Chaining methods

// you can also use a custom chain method to simplify even more and avoid using async/await
btt
  .invokeChain()                      // 1)
  .triggerShortcut('cmd+space')       // 2)
  .sendText({text: 'Hello world!'})   // 3)
  .wait(1000)                         // 4)
  .toggleNightShift()                 // 5)
  .call()                             // 6)
  .then(v => console.info(v))         // 7)

// Explanation:
// 1) Starts method chaining
// 2) Action that a user wants to perform
// 3) Action that a user wants to perform
// 4) Additional method available in chain only - wait before triggering next action
// 5) Action that a user wants to perform
// 6) Invokes all previously-defined actions, ensuring the execution order
// 7) Returns a promise that resolves once all of the actions are fulfilled. 
//    Contains information about the status of the chain (time, value, status)

Event listeners

You can even register a system-wide event listener within BTT that'll trigger particular actions

// creates a trigger in BetterTouchTool. Keep in mind that this is persistent until you manually delete it!
btt.addTriggerAction('oneFingerForceClick', (ev) => {

  // create a list of actions that you want to perform on single finger force click
  const actionsToInvoke = [
    btt.showHUD({
      title: 'Wow!',
      details: 'I triggered! ๐Ÿ˜',
    }),
  ];
  
  // and push them to `actions` property in the event object.
  ev.actions.push(...actionsToInvoke);
});

// you can also delete an event listener - trigger: 
btt.removeTriggerAction('oneFingerForceClick', callbackFuntion);

The above method will trigger the callback upon running your script, not when a particular event really occurs. If you need to call a function upon event recognition, you need to use btt-node-server and use the addEventListener and removeEventListener methods on the btt instance. The callback you provide will run in the nodejs environment, within vm.

const btt = new Btt({
  domain: '127.0.0.1',
  port: 8000,
  protocol: 'http',
  version: '2.525',
  // pass eventServer to use this part of the lib
  eventServer: {
    domain: 'localhost',
    port: 8888,
  },
});

// adds real event listener, that'll run once event occurs
btt.addEventListener('cmd+ctrl+alt+u', async (ev) => {
  // write the code as you'd normally do -> trigger the action for some interval
  const intervalID = setInterval(() => {
    btt.showHUD({ title: 'It works!'}).invoke();
  }, 1000);

  // you can use fetch API here or anything that your node version will support

  // stops the interval after 10 seconds
  await new Promise((res, rej) => {
    setTimeout(() => {
      clearTimeout(intervalID);
      res();
    }, 10000);
  });
  
  // the value you return from the callback will be the response of the btt-node-server 
  return { messsage: 'Hello world!' };
});

To get all available events, you have to look in the enums (list of all valid events will be available soon). Most of the time you can just guess because all event names are the lowercased equivalent of the triggers from within BetterTouchTool.

Additional action information

For use within the browser, you can get the url that lies behind all actions and assign it to some <a href="${link}">Link</a>. To get link you simply need to read the .url property of any action:

console.log(
  btt.triggerShortcut('cmd+space').url
);

If you want to have a peak at the generated action JSON, or want to share it with others who use BetterTouchTool you can read the .json property of any action.

console.log(
  btt.showHUD({ title: 'Hello!' }).json
);

More examples

For more advanced examples visit the example section

Notice

Keep in mind that this module only provides handy utility functions that send requests to BTT built in webserver. So depending on your BTT version, some actions may be glitchy. Do not hestitate to report those issues here or in the official BTT community forum.

Also, keep in mind that accessing any kind of low level APIs from JS may be dangerous, make sure to stay secure

Related projects:

  • btt - BetterTouchTool management in JS
  • btt-node-server - Simple express server, required for advanced event listener handling
  • btt-node Premature version of this package (btt) - deprecated

License

MIT

btt's People

Contributors

brntsllvn avatar dependabot[bot] avatar mitkotschimev avatar worie avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

btt's Issues

make addEventListener callback act like a real function

Currently, addEventListener method of this package just creates actions and attaches them to BTT.
But it could respect any other JavaScript function, for example setInterval, timeout, fetches etc.

  • Requires creation of btt-server subproject
  • Add an Action to BTT that invokes specific endpoint / sends specific message
  • Save the function definition somehow on the btt-server side.
  • Invoke the code upon recieving an event from real BetterTouchTool

Create an abstraction to control JSONs better

There's a mess in Utilities or Events.ts files - because jsons need some manipulations to work properly in BetterTouchTool. I'd like to create a separate service for managing this part of the package

Fix recursive build (webpack, ts)

Currently if you run npm run build, the build process goes into infinite loop for some reason - i guess it is due to fact that typedoc builds its files, perhaps that may be it but it's a wild guess.

Create a btt web view boiler plate

this package can be run both on frontend and backend - to ease up working with web view, I'll create a boilerplate for createing apps that are supposed to be used within btt web view.

Typings not exported properly

There's a bug with type definitions exporting. If you install the package from NPM, the typings won't work. If you clone the repo manually and run npm link in it, then npm link btt in your app, it'll work. But surely, this is just a temporary solution and everything should be working fine when using npm build as well.

Support for widgetInstance.addEventListener

Just realized that there's no simple way to update the action that is meant to happen upon clicking touchbar widget from the lib - I'll try to add support for both addTriggerAction (for use without btt-node-server) and addEventListener.

"Sorry, you have to provide the node/bash binary path manually in the params" when using addEventListener

Hey there Worie - this is an awesome library, and you're doing a great job! I'm trying to set up btt-node-server alongside this library, and I'm running into some issues.

First of all, I can instantiate btt (which I've installed within a local Create React App) in the browser and execute triggers in BTT. It's awesome.

However, when I attempt to use btt.addEventListener to access btt-node-server, an error prints in my console:

Sorry, you have to provide the node/bash binary path manually in the params

The shortcut I input as the first argument (cmd-alt-opt-u etc) appears in BTT but doesn't have any actions associated with it. It's just the keyboard command.

I've been digging into the AppConfig and I found the nodeBinaryPath option, but when I set that, the app crashes when I try to call btt.addEventListener.

Here's the config:
Browser:

    const btt = new Btt({
      domain: '127.0.0.1',
      port: 58267,
      protocol: 'http',
      version: '2.687',
      sharedKey: 'yourSharedKey',
      nodeBinaryPath: '/usr/local/bin/node',
      // pass eventServer to use this part of the lib
      eventServer: {
        domain: '127.0.0.1',
        port: 8888,
      },
    });

btt-node-server:

BTT_DOMAIN=127.0.0.1
BTT_PORT=58267
BTT_PROTOCOL=http
BTT_SHARED_KEY=yourSharedKey
BTT_VERSION=2.687
PORT=8888

Any ideas? I can just use the btt library to execute triggers that I've already defined, but I'm just curious why it's not working.

Add docs

Find a way of easy deployment of the generated docs somewhere without polluting the repo and update the link in the README.md

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.