touch-bar.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. import { EventEmitter } from 'events';
  2. let nextItemID = 1;
  3. const hiddenProperties = Symbol('hidden touch bar props');
  4. const extendConstructHook = (target: any, hook: Function) => {
  5. const existingHook = target._hook;
  6. target._hook = function () {
  7. if (existingHook) existingHook.call(this);
  8. hook.call(this);
  9. };
  10. };
  11. const ImmutableProperty = <T extends TouchBarItem<any>>(def: (config: T extends TouchBarItem<infer C> ? C : never, setInternalProp: <K extends keyof T>(k: K, v: T[K]) => void) => any) => (target: T, propertyKey: keyof T) => {
  12. extendConstructHook(target as any, function (this: T) {
  13. (this as any)[hiddenProperties][propertyKey] = def((this as any)._config, (k, v) => {
  14. (this as any)[hiddenProperties][k] = v;
  15. });
  16. });
  17. Object.defineProperty(target, propertyKey, {
  18. get: function () {
  19. return (this as any)[hiddenProperties][propertyKey];
  20. },
  21. set: function () {
  22. throw new Error(`Cannot override property ${name}`);
  23. },
  24. enumerable: true,
  25. configurable: false
  26. });
  27. };
  28. const LiveProperty = <T extends TouchBarItem<any>>(def: (config: T extends TouchBarItem<infer C> ? C : never) => any, onMutate?: (self: T, newValue: any) => void) => (target: T, propertyKey: keyof T) => {
  29. extendConstructHook(target as any, function (this: T) {
  30. (this as any)[hiddenProperties][propertyKey] = def((this as any)._config);
  31. if (onMutate) onMutate((this as any), (this as any)[hiddenProperties][propertyKey]);
  32. });
  33. Object.defineProperty(target, propertyKey, {
  34. get: function () {
  35. return this[hiddenProperties][propertyKey];
  36. },
  37. set: function (value) {
  38. if (onMutate) onMutate((this as any), value);
  39. this[hiddenProperties][propertyKey] = value;
  40. this.emit('change', this);
  41. },
  42. enumerable: true
  43. });
  44. };
  45. abstract class TouchBarItem<ConfigType> extends EventEmitter {
  46. @ImmutableProperty(() => `${nextItemID++}`) id!: string;
  47. abstract type: string;
  48. abstract onInteraction: Function | null;
  49. child?: TouchBar;
  50. private _parents: { id: string; type: string }[] = [];
  51. private _config!: ConfigType;
  52. constructor (config: ConfigType) {
  53. super();
  54. this._config = this._config || config || {} as any;
  55. (this as any)[hiddenProperties] = {};
  56. const hook = (this as any)._hook;
  57. if (hook) hook.call(this);
  58. delete (this as any)._hook;
  59. }
  60. public _addParent (item: TouchBarItem<any>) {
  61. const existing = this._parents.some(test => test.id === item.id);
  62. if (!existing) {
  63. this._parents.push({
  64. id: item.id,
  65. type: item.type
  66. });
  67. }
  68. }
  69. public _removeParent (item: TouchBarItem<any>) {
  70. this._parents = this._parents.filter(test => test.id !== item.id);
  71. }
  72. }
  73. class TouchBarButton extends TouchBarItem<Electron.TouchBarButtonConstructorOptions> implements Electron.TouchBarButton {
  74. @ImmutableProperty(() => 'button')
  75. type!: string;
  76. @LiveProperty<TouchBarButton>(config => config.label)
  77. label!: string;
  78. @LiveProperty<TouchBarButton>(config => config.accessibilityLabel)
  79. accessibilityLabel!: string;
  80. @LiveProperty<TouchBarButton>(config => config.backgroundColor)
  81. backgroundColor!: string;
  82. @LiveProperty<TouchBarButton>(config => config.icon)
  83. icon!: Electron.NativeImage;
  84. @LiveProperty<TouchBarButton>(config => config.iconPosition)
  85. iconPosition!: Electron.TouchBarButton['iconPosition'];
  86. @LiveProperty<TouchBarButton>(config => typeof config.enabled !== 'boolean' ? true : config.enabled)
  87. enabled!: boolean;
  88. @ImmutableProperty<TouchBarButton>(({ click: onClick }) => typeof onClick === 'function' ? () => onClick() : null)
  89. onInteraction!: Function | null;
  90. }
  91. class TouchBarColorPicker extends TouchBarItem<Electron.TouchBarColorPickerConstructorOptions> implements Electron.TouchBarColorPicker {
  92. @ImmutableProperty(() => 'colorpicker')
  93. type!: string;
  94. @LiveProperty<TouchBarColorPicker>(config => config.availableColors)
  95. availableColors!: string[];
  96. @LiveProperty<TouchBarColorPicker>(config => config.selectedColor)
  97. selectedColor!: string;
  98. @ImmutableProperty<TouchBarColorPicker>(({ change: onChange }, setInternalProp) => typeof onChange === 'function' ? (details: { color: string }) => {
  99. setInternalProp('selectedColor', details.color);
  100. onChange(details.color);
  101. } : null)
  102. onInteraction!: Function | null;
  103. }
  104. class TouchBarGroup extends TouchBarItem<Electron.TouchBarGroupConstructorOptions> implements Electron.TouchBarGroup {
  105. @ImmutableProperty(() => 'group')
  106. type!: string;
  107. @LiveProperty<TouchBarGroup>(config => config.items instanceof TouchBar ? config.items : new TouchBar(config.items), (self, newChild: TouchBar) => {
  108. if (self.child) {
  109. for (const item of self.child.orderedItems) {
  110. item._removeParent(self);
  111. }
  112. }
  113. for (const item of newChild.orderedItems) {
  114. item._addParent(self);
  115. }
  116. })
  117. child!: TouchBar;
  118. onInteraction = null;
  119. }
  120. class TouchBarLabel extends TouchBarItem<Electron.TouchBarLabelConstructorOptions> implements Electron.TouchBarLabel {
  121. @ImmutableProperty(() => 'label')
  122. type!: string;
  123. @LiveProperty<TouchBarLabel>(config => config.label)
  124. label!: string;
  125. @LiveProperty<TouchBarLabel>(config => config.accessibilityLabel)
  126. accessibilityLabel!: string;
  127. @LiveProperty<TouchBarLabel>(config => config.textColor)
  128. textColor!: string;
  129. onInteraction = null;
  130. }
  131. class TouchBarPopover extends TouchBarItem<Electron.TouchBarPopoverConstructorOptions> implements Electron.TouchBarPopover {
  132. @ImmutableProperty(() => 'popover')
  133. type!: string;
  134. @LiveProperty<TouchBarPopover>(config => config.label)
  135. label!: string;
  136. @LiveProperty<TouchBarPopover>(config => config.icon)
  137. icon!: Electron.NativeImage;
  138. @LiveProperty<TouchBarPopover>(config => config.showCloseButton)
  139. showCloseButton!: boolean;
  140. @LiveProperty<TouchBarPopover>(config => config.items instanceof TouchBar ? config.items : new TouchBar(config.items), (self, newChild: TouchBar) => {
  141. if (self.child) {
  142. for (const item of self.child.orderedItems) {
  143. item._removeParent(self);
  144. }
  145. }
  146. for (const item of newChild.orderedItems) {
  147. item._addParent(self);
  148. }
  149. })
  150. child!: TouchBar;
  151. onInteraction = null;
  152. }
  153. class TouchBarSlider extends TouchBarItem<Electron.TouchBarSliderConstructorOptions> implements Electron.TouchBarSlider {
  154. @ImmutableProperty(() => 'slider')
  155. type!: string;
  156. @LiveProperty<TouchBarSlider>(config => config.label)
  157. label!: string;
  158. @LiveProperty<TouchBarSlider>(config => config.minValue)
  159. minValue!: number;
  160. @LiveProperty<TouchBarSlider>(config => config.maxValue)
  161. maxValue!: number;
  162. @LiveProperty<TouchBarSlider>(config => config.value)
  163. value!: number;
  164. @ImmutableProperty<TouchBarSlider>(({ change: onChange }, setInternalProp) => typeof onChange === 'function' ? (details: { value: number }) => {
  165. setInternalProp('value', details.value);
  166. onChange(details.value);
  167. } : null)
  168. onInteraction!: Function | null;
  169. }
  170. class TouchBarSpacer extends TouchBarItem<Electron.TouchBarSpacerConstructorOptions> implements Electron.TouchBarSpacer {
  171. @ImmutableProperty(() => 'spacer')
  172. type!: string;
  173. @ImmutableProperty<TouchBarSpacer>(config => config.size)
  174. size!: Electron.TouchBarSpacer['size'];
  175. onInteraction = null;
  176. }
  177. class TouchBarSegmentedControl extends TouchBarItem<Electron.TouchBarSegmentedControlConstructorOptions> implements Electron.TouchBarSegmentedControl {
  178. @ImmutableProperty(() => 'segmented_control')
  179. type!: string;
  180. @LiveProperty<TouchBarSegmentedControl>(config => config.segmentStyle)
  181. segmentStyle!: Electron.TouchBarSegmentedControl['segmentStyle'];
  182. @LiveProperty<TouchBarSegmentedControl>(config => config.segments || [])
  183. segments!: Electron.SegmentedControlSegment[];
  184. @LiveProperty<TouchBarSegmentedControl>(config => config.selectedIndex)
  185. selectedIndex!: number;
  186. @LiveProperty<TouchBarSegmentedControl>(config => config.mode)
  187. mode!: Electron.TouchBarSegmentedControl['mode'];
  188. @ImmutableProperty<TouchBarSegmentedControl>(({ change: onChange }, setInternalProp) => typeof onChange === 'function' ? (details: { selectedIndex: number, isSelected: boolean }) => {
  189. setInternalProp('selectedIndex', details.selectedIndex);
  190. onChange(details.selectedIndex, details.isSelected);
  191. } : null)
  192. onInteraction!: Function | null;
  193. }
  194. class TouchBarScrubber extends TouchBarItem<Electron.TouchBarScrubberConstructorOptions> implements Electron.TouchBarScrubber {
  195. @ImmutableProperty(() => 'scrubber')
  196. type!: string;
  197. @LiveProperty<TouchBarScrubber>(config => config.items)
  198. items!: Electron.ScrubberItem[];
  199. @LiveProperty<TouchBarScrubber>(config => config.selectedStyle || null)
  200. selectedStyle!: Electron.TouchBarScrubber['selectedStyle'];
  201. @LiveProperty<TouchBarScrubber>(config => config.overlayStyle || null)
  202. overlayStyle!: Electron.TouchBarScrubber['overlayStyle'];
  203. @LiveProperty<TouchBarScrubber>(config => config.showArrowButtons || false)
  204. showArrowButtons!: boolean;
  205. @LiveProperty<TouchBarScrubber>(config => config.mode || 'free')
  206. mode!: Electron.TouchBarScrubber['mode'];
  207. @LiveProperty<TouchBarScrubber>(config => typeof config.continuous === 'undefined' ? true : config.continuous)
  208. continuous!: boolean;
  209. @ImmutableProperty<TouchBarScrubber>(({ select: onSelect, highlight: onHighlight }) => typeof onSelect === 'function' || typeof onHighlight === 'function' ? (details: { type: 'select'; selectedIndex: number } | { type: 'highlight'; highlightedIndex: number }) => {
  210. if (details.type === 'select') {
  211. if (onSelect) onSelect(details.selectedIndex);
  212. } else {
  213. if (onHighlight) onHighlight(details.highlightedIndex);
  214. }
  215. } : null)
  216. onInteraction!: Function | null;
  217. }
  218. class TouchBarOtherItemsProxy extends TouchBarItem<null> implements Electron.TouchBarOtherItemsProxy {
  219. @ImmutableProperty(() => 'other_items_proxy') type!: string;
  220. onInteraction = null;
  221. }
  222. const escapeItemSymbol = Symbol('escape item');
  223. class TouchBar extends EventEmitter implements Electron.TouchBar {
  224. // Bind a touch bar to a window
  225. static _setOnWindow (touchBar: TouchBar | Electron.TouchBarConstructorOptions['items'], window: Electron.BrowserWindow) {
  226. if (window._touchBar != null) {
  227. window._touchBar._removeFromWindow(window);
  228. }
  229. if (!touchBar) {
  230. window._setTouchBarItems([]);
  231. return;
  232. }
  233. if (Array.isArray(touchBar)) {
  234. touchBar = new TouchBar({ items: touchBar });
  235. }
  236. touchBar._addToWindow(window);
  237. }
  238. private windowListeners = new Map<number, Function>();
  239. private items = new Map<string, TouchBarItem<any>>();
  240. orderedItems: TouchBarItem<any>[] = [];
  241. constructor (options: Electron.TouchBarConstructorOptions) {
  242. super();
  243. if (options == null) {
  244. throw new Error('Must specify options object as first argument');
  245. }
  246. let { items, escapeItem } = options;
  247. if (!Array.isArray(items)) {
  248. items = [];
  249. }
  250. this.escapeItem = (escapeItem as any) || null;
  251. const registerItem = (item: TouchBarItem<any>) => {
  252. this.items.set(item.id, item);
  253. item.on('change', this.changeListener);
  254. if (item.child instanceof TouchBar) {
  255. item.child.orderedItems.forEach(registerItem);
  256. }
  257. };
  258. let hasOtherItemsProxy = false;
  259. const idSet = new Set();
  260. items.forEach((item) => {
  261. if (!(item instanceof TouchBarItem)) {
  262. throw new Error('Each item must be an instance of TouchBarItem');
  263. }
  264. if (item.type === 'other_items_proxy') {
  265. if (!hasOtherItemsProxy) {
  266. hasOtherItemsProxy = true;
  267. } else {
  268. throw new Error('Must only have one OtherItemsProxy per TouchBar');
  269. }
  270. }
  271. if (!idSet.has(item.id)) {
  272. idSet.add(item.id);
  273. } else {
  274. throw new Error('Cannot add a single instance of TouchBarItem multiple times in a TouchBar');
  275. }
  276. });
  277. // register in separate loop after all items are validated
  278. for (const item of (items as TouchBarItem<any>[])) {
  279. this.orderedItems.push(item);
  280. registerItem(item);
  281. }
  282. }
  283. private changeListener = (item: TouchBarItem<any>) => {
  284. this.emit('change', item.id, item.type);
  285. };
  286. private [escapeItemSymbol]: TouchBarItem<unknown> | null = null;
  287. set escapeItem (item: TouchBarItem<unknown> | null) {
  288. if (item != null && !(item instanceof TouchBarItem)) {
  289. throw new Error('Escape item must be an instance of TouchBarItem');
  290. }
  291. const escapeItem = this.escapeItem;
  292. if (escapeItem) {
  293. escapeItem.removeListener('change', this.changeListener);
  294. }
  295. this[escapeItemSymbol] = item;
  296. if (this.escapeItem != null) {
  297. this.escapeItem.on('change', this.changeListener);
  298. }
  299. this.emit('escape-item-change', item);
  300. }
  301. get escapeItem (): TouchBarItem<unknown> | null {
  302. return this[escapeItemSymbol];
  303. }
  304. _addToWindow (window: Electron.BrowserWindow) {
  305. const { id } = window;
  306. // Already added to window
  307. if (this.windowListeners.has(id)) return;
  308. window._touchBar = this;
  309. const changeListener = (itemID: string) => {
  310. window._refreshTouchBarItem(itemID);
  311. };
  312. this.on('change', changeListener);
  313. const escapeItemListener = (item: Electron.TouchBarItemType | null) => {
  314. window._setEscapeTouchBarItem(item != null ? item : {});
  315. };
  316. this.on('escape-item-change', escapeItemListener);
  317. const interactionListener = (_: any, itemID: string, details: any) => {
  318. let item = this.items.get(itemID);
  319. if (item == null && this.escapeItem != null && this.escapeItem.id === itemID) {
  320. item = this.escapeItem;
  321. }
  322. if (item != null && item.onInteraction != null) {
  323. item.onInteraction(details);
  324. }
  325. };
  326. window.on('-touch-bar-interaction', interactionListener);
  327. const removeListeners = () => {
  328. this.removeListener('change', changeListener);
  329. this.removeListener('escape-item-change', escapeItemListener);
  330. window.removeListener('-touch-bar-interaction', interactionListener);
  331. window.removeListener('closed', removeListeners);
  332. window._touchBar = null;
  333. this.windowListeners.delete(id);
  334. const unregisterItems = (items: TouchBarItem<any>[]) => {
  335. for (const item of items) {
  336. item.removeListener('change', this.changeListener);
  337. if (item.child instanceof TouchBar) {
  338. unregisterItems(item.child.orderedItems);
  339. }
  340. }
  341. };
  342. unregisterItems(this.orderedItems);
  343. if (this.escapeItem) {
  344. this.escapeItem.removeListener('change', this.changeListener);
  345. }
  346. };
  347. window.once('closed', removeListeners);
  348. this.windowListeners.set(id, removeListeners);
  349. window._setTouchBarItems(this.orderedItems);
  350. escapeItemListener(this.escapeItem);
  351. }
  352. _removeFromWindow (window: Electron.BrowserWindow) {
  353. const removeListeners = this.windowListeners.get(window.id);
  354. if (removeListeners != null) removeListeners();
  355. }
  356. static TouchBarButton = TouchBarButton;
  357. static TouchBarColorPicker = TouchBarColorPicker;
  358. static TouchBarGroup = TouchBarGroup;
  359. static TouchBarLabel = TouchBarLabel;
  360. static TouchBarPopover = TouchBarPopover;
  361. static TouchBarSlider = TouchBarSlider;
  362. static TouchBarSpacer = TouchBarSpacer;
  363. static TouchBarSegmentedControl = TouchBarSegmentedControl;
  364. static TouchBarScrubber = TouchBarScrubber;
  365. static TouchBarOtherItemsProxy = TouchBarOtherItemsProxy;
  366. }
  367. export default TouchBar;