Uxp developer tools adobe что это
The “Adobe UXP: Things you Need to Know!” YouTube playlist.
Editor’s Note: “We’re happy to welcome Davide Barranca, a Photoshop retoucher and developer based in Italy, back to the Adobe Tech blog. Davide is the author of the Professional Photoshop Scripting book and the Adobe Photoshop HTML Panels Development course. He writes about Photoshop and Adobe extensibility on his blog.”
— Erin Finnegan, Community Engineer, Creative Cloud.
During the MAX 2020 conference Adobe officially unveiled UXP plugins (Unified eXtensibility Platform) availability for third-party developers in Photoshop 2021. It was great news, and the first stage of a transition process that in the long run aims to replace the old extensibility technology (CEP — Common Extensibility Platform) with the new UXP (Unified eXtensibility Platform).
Before anyone gets nervous: CEP isn’t going anywhere in the short-term. It’s been recently updated to v10, and will coexist alongside with UXP “for a long time” (quote from Adobe). On one hand, the extended CEP/UXP overlap period allows Adobe to better integrate the new tech with their Creative Cloud applications; on the other hand, it gives developers time to get accustomed to UXP and eventually port their products.
When the shiny new thing was CEP, around early 2014, I documented my own learning process with a series of blog posts titled HTML Panels Tips, mostly as a reminder to my older self — I tend to forget stuff at an annoyingly fast pace. Over time the collection grew considerably and—I’m told—it’s been of great help to other developers as well. Eventually my blog posts became the starting point of the larger Photoshop HTML Panels Development course.
With UXP I find myself in a similar situation now: I have to learn it from scratch, and I want to share my findings as I go. Truth to be told, I’m lucky enough to have been part of the limited group of developers involved with Adobe during the prerelease stages of the UXP launch, so I’ve had plenty of time to ask questions, note answers, and get lost down a number of rabbit holes.
I started recording a series of videos on UXP that are part of a freely available YouTube playlist titled Adobe UXP: Things you Need to Know! that I’m happy to present you here.
The videos are time-coded with named sections, around twenty minutes long each, for a total of ~3 hours of free UXP training so far. The agenda for each episode is to pick a couple of subjects and discuss them, mostly with the help of sample code that I write from scratch so that you can follow along — because learning by doing is the best. The level varies from beginner to intermediate depending on the topic, but I get into advanced subjects as well (when needed and especially if it’s fun).
They are available directly from YouTube (English spoken with curated English subtitles), and on my blog, where I’ve been asked to publish the transcripts as well to help those who need to translate them (or for anyone who wants to do a text-based search).
There are eight of videos at the moment, but the list is growing and the project is alive. Think about them as your “eight steps to your first Photoshop UXP plugin”.
This is the longest video of the series: I cover all the highlights of the MAX 2020 announcement. Start here if you’re not sure why UXP is going to be a big deal. (Editor’s Note: It’s also a great place to start if you have prior development experience with Creative Cloud.)
In the second video, I guide you through the new Adobe.io portal for developers and point out the relevant sections in the Doc pages — we are all going to spend a lot of time there!
In this video, we’re going to use the UXP Developer Tool to load, reload, watch, debug, package and scaffold new UXP plugins from templates.
This time I cover the difference between Panels vs. Command-based UXP plugins, and how the manifest.json—the main entry-point—is structured.
In this episode I discuss the very important topic of Synchronous vs. Asynchronous code in the Photoshop Scripting DOM, and how UXP differs compared to ExtendScript in that regard.
Here, I approach BatchPlay, the super-powerful Photoshop-only Scripting technique that can overcome the DOM’s limits. BatchPlay is so important (and kinda unfriendly) that it is the subject of a three part mini-series.
In this second part of the mini-series, I explore BatchPlay with the help of the Alchemist plugin as a UXP Script Listener.
In the third and final part of the BatchPlay mini-series, I use the Alchemist plugin as a UXP Script Inspector.
I produced the first eight videos in a burst of enthusiasm right after the MAX announcement, in the spur of the moment, and and at a very fast pace. I plan to keep going, so if you have specific requests please let me know on Twitter or in my YouTube channel. The playlist is freely available, yet your support with a donation is most welcome — because it’s been 2020 for everyone on planet Earth, my friends.
Как известно, веб-разработка делится на 2 части: frontend (фронтенд) и backend (бэкенд).
Вольно выражаясь, фронтенд это то, что работает в браузере, т.е. верстка (html + css) и браузерные скрипты (javascript).
Бэкенд — это скрипты, работающие на сервере.
В этой статье разберем инструменты разработчика (DevTools), которые встроены во все современные браузеры. Эти инструменты — незаменимая вещь для фронтенд-разработчика.
Разбирать будем на примере инструментов разработчики, которые встроены в браузер Google Chrome.
Открыть инструменты разработчика можно 3-мя способами:
- Нажать клавишу F12
- Нажать сочетание клавиш ctrl+shift+i
Через меню браузера: в правом верхнем углу три точки -> Дополнительные инструменты -> Инструменты разработчика См. картинку:
Через меню браузера: в правом верхнем углу три точки -> Дополнительные инструменты -> Инструменты разработчика См. картинку:
Внимание: Инструменты разработчика предоставляют огромное множество возможностей, и в этой статье мы разберем лишь некоторые из них.
Сначала про расположение: открыв блок инструментов в правом верхнем углу мы снова видим три точки, нажав на них можно расположить инструменты разработчика справа, слева, внизу и в отдельном окне. См. скриншот:
Сначала про расположение: открыв блок инструментов в правом верхнем углу мы снова видим три точки, нажав на них можно расположить инструменты разработчика справа, слева, внизу и в отдельном окне. См. скриншот:
Инструменты разработчика для верстальщика
Инструменты распределены по панелям. Их достаточно много, но как часто бывают, чаще используют лишь некоторые из них.
Панель «Elements»
Эта панель отображает элементы и их свойства, и мы можем редактировать эти элементы и свойства прямо тут же в браузере.
Панель «Elements» разделена на две области: дерево элементов страницы и свойства выбранного элемента.
Панель «Elements» разделена на две области: дерево элементов страницы и свойства выбранного элемента.
Выбрать элемент, для просмотра его свойств, можно разными способами:
При помощи визуального поиска: щелкаем мышью по стрелочке, которая находится в левом верхнем углу блока инструментов разработчика и мышью выбираем нужный элемент:
При помощи визуального поиска: щелкаем мышью по стрелочке, которая находится в левом верхнем углу блока инструментов разработчика и мышью выбираем нужный элемент:
При активных инструментах разработчика нажать ctrl+f и в появившейся строке поиска ввести: тег, класс, атрибут, текст элемента…
При активных инструментах разработчика нажать ctrl+f и в появившейся строке поиска ввести: тег, класс, атрибут, текст элемента…
На панели «Elements» можно увидеть все css-правила, применяемые к элементу.
В реальной разработке к одному элементу может применяться множество правил, находящихся в разных местах css-файла, и, даже в разных css-файлах.
И в этом случае вкладка «Elements» просто незаменима. На скриншоте ниже показан элемент, на который действует множество правил, находящихся в разных местах и разных файлах, сразу видно, в каком файле и на какой строке находится то или иное правило:
Это очень удобно при изучении чужого кода.
Например, мы изучаем популярнейший css-фреймворк bootstrap. Среди его классов, относящихся к сетке (т.е. к позиционированию элементов) имеется класс .row. Любой, кто верстает с использованием этого фреймворка использует этот класс, практически, на каждой странице. Для чего же он нужен?
Открывает инструменты разработчика, находим элемент с этим классом, выделяем его и смотрим:
Глядя на эти правила, мы понимаем, что:
- Этот класс является flex-контейнером для вложенных элементов display: flex;
- Элементы, находящиеся внутри этого контейнера, будут выстраиваться в несколько строк flex-wrap: wrap;
- Ну и видим, справа и слева минусовые отступы.
Но и это далеко не всё. Мы можем просмотреть правила, которые применяются при срабатывании псевдоклассов. Таких как :hover, :active и т.д. См. скриншот:
Но и это далеко не всё. Мы можем просмотреть правила, которые применяются при срабатывании псевдоклассов. Таких как :hover, :active и т.д. См. скриншот:
Можно увидеть, как будет выглядеть элемент, если к нему применить какой-то из существующих классов или отключить уже примененный класс:
Переключившись на вкладку «computed» можно посмотреть окончательную версию всех стилей, примененных к элементу:
Проверка разметки на адаптивность
Поскольку современная верстка адаптивна, т.е. делается под множество устройств с различными размерами экрана, перед разработчиком встает задача, проверить, как будет выглядеть его верстка при различной ширине экрана.
Для этого мы можем использовать «Переключение в режим устройства» (Toggle device mode). Повторное нажатие на эту иконку, вернет обычный режим:
И после этого, можно выбирать какое-то устройство из списка или выбрать произвольную ширину:
Вы можете выбрать устройство и повернуть его:
В режиме устройства, можно перезагрузить страницу с эмуляцией медленного интернета, вы увидите, насколько долго грузится ваша страница, быть может стоит оптимизировать изображения? См. скриншот ниже:
Инструменты разработчика для javascript-программиста
Программирование состоит не только из написания кода. Редко случается, что мало-мальски сложный код начинает сразу работать так, как было задумано. В большинстве случаев “что-то идет не так”. Чтобы заставить программу (скрипт) выполняться так, как задумал разработчик, ее «отлаживают».
Отладка — этап разработки, на котором обнаруживают и устраняют ошибки. Часто она занимает больше времени, чем собственно написание кода.
Для фронтенд javascript-программиста средой выполнения скриптов, которые он пишет, является браузер. Дальше посмотрим какие возможности для отладки предоставляют нам «инструменты разработчика» в Google Chrome.
Панель «Console»
В принципе, при написании js-скриптов консоль, обычно, открыта всегда, поскольку любые необработанные ошибки, сразу видны. Видны файл и строка, где произошла ошибка:
UXP (Unified Extensibility Platform) платформа уже внедряется в течении 2 лет, на этой платформе сделаны многие элементы интерфейса Adobe программ — стартовые страницы, диалог создания нового документа? галерея нейронных фильтров в PS2021 и т.п. Предполагается развитие платформы на базе Adobe XD, как приложения для разработки интерфейсов плагинов, программная часть разрабатывается как и раньше в любых удобных редакторах кода. На момент написания статьи в доступе около 300 плагинов на базе платформы UXP.
В концепции UXP теперь все расширения и панели называются плагинами и ни как по другому.
Схема взаимодействия UXP и Adobe приложений:
На схеме мы видим, UXP представляет собой общий высоко технологический стек, обеспечивающий современную высокоскоростную среду выполнения JavaScript движка, этот стек включает в себя общий набор API для доступа к сети, файловой системе, Dom модели HTML, системе визуализации, модели ML для обработки данных и вывода данных, а также API для доступа к службам Creative Cloud от имени пользователя, таким как библиотеки и облачные документы. Он также включает в себя слой пользовательского интерфейса, напоминающий React Native, для размещения собственных элементов управления совместимые c HTML и CSS. UXP имеет связи с конкретными API хостов, для взаимодействия с приложением и самим документом.
Унифицированная Среда Выполнения JavaScript
При создании панелей с помощью CEP мы не могли напрямую взаимодействовать с Photoshop — вместо этого мы использовали evalScript для передачи управления коду, работающему в среде ExtendScript, которая содержит API для связи с хост-приложением.
Для такого взаимодействия требоваться поддерживать два Java движка и две среды выполнения кода. Передача кода и данных по этому способу происходит медленно и невероятно трудно отлаживается. Единая среда выполнения позволяет UXP UI и бизнес-логике совместно использовать один и тот же высокоскоростной нативный Java движок, а это означает, что больше нет необходимости использовать evalScript!
Современная Среда Выполнения JavaScript
При использовании ExtendScript код выполнялся в среде JavaScript, основанной на стандарте ECMAScript 3 1999 года. Старый стандарт ограничивал возможности ExtendScript. Современные движки JavaScript значительно продвинулись в производительности и экономичном использовании оперативной памяти. UXP платформа, использует качестве виртуальной машины JavaScript версии V8.
Общие API
API Хосты
Каждый хост-продукт имеет свою схему для взаимодействия с приложением и открытым документом, и UXP позволяет хост-продукту предоставлять эти API непосредственно разработчику. То, как выглядят эти хост-API, будет зависеть от конкретного приложения.
Пользовательский интерфейс
UXP использует HTML и CSS в дополнение к собственным виджетам для создания быстрого и адаптивного пользовательского интерфейса, который используется хост-приложением как собственный интерфейс. То есть мы продолжим использовать HTML и CSS для создания интерфейса, а UXP будет транслировать этот интерфейс как родную среду хост-приложения.
Теперь в UXP будут доступны элементы управления интерфейса от Spectrum UI, это позволит пользоваться общими элементами управления, шаблонами дизайна и поддержкой без необходимости тратить часы на воссоздание внешнего вида каждого приложения в пользовательском интерфейсе вашего плагина.
И так из плюсов новой платформы плагины будут работать быстрее, а создавать их будет проще, интерфейсы станут намного интереснее. Однозначно установка плагинов упростилась, после их загрузки они сразу доступны без перезапуска программы.
Теперь о минусах, панели уже вынесены в меню, как устаревшие расширения, не исключено, что на какой-то версии они будут исключены, также как когда то были исключены панели на Flash. Абсолютно изменится структура кода скрипта, все придется переписывать, и это не только вопрос синтаксиса, а в большей степени это изменение DOM модели в среде UXP, а это меняет все, будем надеяться к лучшему.
Платформа еще сырая, некоторые ссылки внутри разделов документации ведут на пустые срамницы, они еще в разработке, но основа уже есть.
Качаем программу для создания и управления плагинами Adobe UXP Developer Tool, устанавливаем и запускаем.
Для работы потребуется Photoshop верией не ниже 22.00.00, запускаем его.
В программе Adobe UXP Developer Tool нажимаем кнопку Create Plugin:
Заполняем поля, для первого примера из шаблонов выбираем ps-starter — простой плагин основанный на JavaScript без дополнительных библиотек.
Далее нажимаем кнопку Select Folder — выбираем папку, где будет располагаться наш плагин.
В программе UXP Developer Tool появится запись об установленном плагине, заходим в меню и выбираем load:
После этого в Photoshop откроется панель тестового плагина:
в этом плагине при нажатии на кнопу на панель выводится список слоев в документе. Можно изучать содержимое папки с плагином:
основные файлы manifest.json — описание плагина, основная информация, размеры панели плагина, аналогично манифесту из CEP, но синтаксис уже другой. Index.html — как обычно это интерфейс плагина на html. Index.js — JavaScript код плагина:
Как можно заметить, что из единого JavaScript плагин может обращаться как к элементам HTML, так, и к API Photoshop и это очень здорово!
Рассмотрим создание плагина с библиотекой React. Создание плагина отличается выбором шаблона — вместо ps-starter выбираем ps-react-starter. При попытке загрузить в программе UXP Developer Tool — получаем ошибку:
In this episode we’ll learn how to build Modal Dialogs for UXP plugins. Feel free to watch the video or read the article, they cover the same ground.
ExtendScript history
ExtendScript was the language that we’ve been using to script Adobe applications literally forever. It was based on the ECMAScript spec version 3 (a.k.a. ES3), that was cutting edge in the decade 1999-2009. Trivia moment: ECMA stands for European Computer Manufacturers Association, and it’s the organization that standardized the JavaScript language under the name ECMAScript. There’s a terrific interview with Brendan Eich (who famously created JavaScript in a hurry in just 10 days) in Lex Fridman’s channel, check that out – trust me, the man is quite something.
So in a way JavaScript and ExtendScript share a “common ancestor”, ES3, but their evolution diverged. Adobe extended (hence the name) the ES3 spec with extra features e.g. the E4X library for XML literals support; while JavaScript went on with ES5 (JSON support, Array methods…), ES6 (new syntax…), etc.
Fast forward to the Adobe MAX 2020 conference and the adoption of a new, unified UI/Scripting engine in UXP. All the ExtendScript extras that we were familiar with are now gone: disappeared, no more. This is the price we’ve got to pay to have a modern JavaScript engine – fair enough. Some fellow developers might not have realized this because there was a lot to sink in, but probably the most conspicuous feature that’s gone missing is the entire ScriptUI class, that has always been the principal tool to build script-driven Windows both in the CEP era and also way before when the Cloud was not around and all we had was a Creative Suite.
Let’s be clear about terminology before going any further, so that no matter what your background is we’re all on the same page:
- Dialog: an independent window that pops up and can be:
- Modal: it steals the focus, you can’t interact with any other UI element but the dialog itself.
- Modeless: the dialog stays around and you’re allowed to deal with the rest of the Photoshop interface.
The concept of Modal vs. Modeless UIs is present all over in the Photoshop interface, e.g. Adjustments: on the left a Modal dialog, on the right a Modeless panel.
We used to build modals with ScriptUI Windows of type 'dialog' , and in theory modeless with ScriptUI Windows of type 'palette' , but those weren’t really supported in Photoshop – they acted weird and we’ve been officially advised against their use. Before CEP came about, ScriptUI was enough to build rich UIs:
But as soon as Flash first, then CEP panels landed in Photoshop, ScriptUI was relegated to simpler dialogs or for backward compatibility only. You may not know it, but also those super-handy alert() , prompt() and confirm() dialogs were part of ScriptUI.
They’re all gone too, with the exception of alert() that’s been re-implemented in the Photoshop API as showAlert() .
Even though it doesn’t differentiate between title vs. text yet (they’re both bold, only the title should be) – a minor cosmetic glitch.
Anyway, whatever code we used to write in the recent past to create dialogs, that’s gone now – thanks for all the fish. UXP provides alternatives for both modeless windows (as UXP panels, that I’ve extensively covered) and modal dialogs, which I’m going to show you in a moment.
⚠️ Disclaimer
That said, there are features that might be already available for you to use, but not really (either partially or fully) documented yet. Incidentally this happens to be the case of some Dialogs, so I was dubious whether to include them here or not. I’ve decided that I will mention them anyway because IMHO it’s crucial for you to plan ahead and be informed about the actual realm of possibilities, so to speak. Although I would suggest not to use those features yet, for the risk that the API will change is even greater – be warned.
As a general rule, you won’t hear a word from me about anything that belongs to the prerelease, or that works in beta versions only – besides breaking all sort of NDAs, it would be pointless. Instead, if the feature is implemented in Photoshop-release I might mention/show it, essentially to inform you but deferring for the actual use to some time in the future when the official documentation covers it fully.
I’ve prepared two different UXP plugins to show you a few of the possible ways to use Dialogs – one using vanilla JS and the other based on React.js. I haven’t covered React here yet, but it felt wrong to leave that out. You can find both of the examples in my GitHub repository.
Vanilla JS UXP dialogs
This vanilla JS example comes directly from the ps-starter template that is available from the UXP Developer Tool (see here if you still need pointers).
The base structure is very bare, just some Spectrum UXP components:
Let’s cover what is officially documented first, which is the result of the first “dialog” button. In order to create a modal dialog, you need to have an actual element in the first:
The element itself is nothing special, I’ve used Spectrum elements that we’ve seen in the past episode like , and . Please note that, as I’ve also mentioned in the Spectrum episode, a class of "row" or "column" triggers the display equals to flex in the so it’s possible to use FlexBox-specific styles such as justify-content etc.
The two elements onclick handlers both use the close() method of the dialog, that in turn is retrieved with document.querySelector() passing the id , which is in fact "dialog" (I hope this is not confusing).
Please note that even if the markup code is there, the dialog doesn’t pop up by default. In order to open it let’s have a look at the openDialog() function that is triggered by the plugin’s “dialog” button.
So, the dialog is retrieved with the same querySelector() but to open it we run the UXP-specific uxpShowModal() method. That accepts an options object with a title property (the dialog’s title bar); a resize prop, that controls whether the dialog is resizeable (either "horizontal" , "vertical" , "both" or "none" – might still be a bit buggy, it was in the past); and size , an object with width and height properties (quite self explanatory).
To sum up: you add to the one or more elements (that you can get by id ) filled with whatever elements you need. You open the modal dialog with uxpShowModal() passing an options object, and you can close the dialog with the close() method optionally passing a return value (in the example I’ve got close('NOPE') and close('OK') ). Also note that opening a dialog is an asynchronous process (hence openDialog is an async callback, and it await s for the uxpShowModal() ) that allows the result res to be stored/logged afterwards. If the user cancels, a "reasonCanceled" string is returned.
Spectrum dialog
Warning: this is, as I said earlier, still undocumented so please wait for the official documentation and/or use with caution.
Instead of a element, there’s the possibility to use a that allows some pre-defined styling as slots. You still place it in the markup:
But the result is strikingly different:
Instead you set the "open" attribute of the element. Similarly, as you can see in the dialog “Ok” button’s click handler, to close the dialog you just remove "open" via removeAttribute() .
Now you know that this is possible and it’ll be soon documented – you can play with it in Photoshop 22.2. Speaking of versions, if you’re wondering how the Photoshop/UXP line fills:
React.js UXP dialog
As I said I’ve not introduced React.js in this series yet – it’s planned – but I want to include an example anyway. This comes straight from the ps-react-starter template, cleaned of almost everything; I might assume that you know how to orient yourself in a React project, but If you don’t and want to follow/play with it, please download the React example from this repository, then:
Do not npm install because it won’t deploy all the needed components. Then point the UXP Developer Tool to the manifest.json that sits in the project’s dist folder – the distribution files come pre-compiled. If you want to modify the code, then you need to:
This will watch the src folder and bundle with Webpack on each save to dist : if you’re not familiar with React, usually you code separate components that a bundler (such as WebPack) merges alongside with the required dependencies in one or a few JavaScript files in dist . Additionally, you need to watch the dist folder in the UXP Developer Tool so that it knows when to reload the plugin.
The whole example is very simplified, it’s a dummy Preferences dialog that doesn’t really saves any preference, but is able to hand it to the UXP panel (I will suggest later on ways to improve it).
Let’s concentrate on the only two files that matter here, both in the src folder: /panels/Dialogs.jsx , the outer container in the UXP plugin panel; and /components/Preferences.jsx , the content of the dialog that pops up.
The Dialogs.jsx file is not very fancy but there are two or three things I’d like to point out.
The openPreferences() function is in charge of opening the dialog: interestingly, it uses ReactDOM.render() to render the component, but first it needs to create a element (via createElement() ) stored in the preferencesDialog variable, and then append it to the . Only then you’re allowed to uxpShowModal() . Also note that when the modal is closed there’s no need to keep the around anymore and you can remove() it.
Nothing relevant to mention in the HTML part, just a very simple Spectrum Component structure with a bit of extra styles to keep things properly spaced.
The Preferences.jsx is as follows:
It’s a stateless function component where I’ve used the state hook to keep track of the two bits of information (the fictitious smartObject and vectorContent ) that I want to pass along to the panel on close – see the onClick() handler for the “Ok” button, whereas the “Cancel” returns the same "reasonCanceled" .
As I’ve mentioned in the previous video about Spectrum components, you always must use the ternary operator for checkboxes (and set null when needed) otherwise they won’t work properly. Please note that I’m using inline handler functions for the onInput event just for convenience. Also note that, and this is peculiar to React.js, the style must be an object – hence the double curly braces: one set to indicate inline JavaScript, one set for the object notation, with camelCase properties. And finally className in lieu of class : but remember, only in standard elements, not Spectrum components that accept the usual class .
This is just an example; in the real world you may want to, say, always store the values (e.g. in the localStorage ) and pass them to the component to populate the modal when it’s shown – but the goal here is to focus on dialog creation.
Recap
Dialogs as we knew them (as ScriptUI Windows, or various simple pop-ups like prompt() and confirm() ) are banned in UXP-land. UXP plugins deal with modeless panels natively, and can display modal dialogs as elements via uxpShowModal() . (that are slightly different) are coming in the near future so keep an eye at the official documentation. All in all UXP can manage dialogs quite nicely so the transition to the new system shouldn’t be too big of a deal!
Thanks for following along! If you find this content useful, please consider supporting me: you can either purchase my latest UXP Course with ReactJS, or donate what you can like the following fine people did—it’ll be much appreciated! 🙏🏻
Thanks to: John Stevenson ⭐️, Adam Plouff, Dana Frenklach, Dmitry Egorov, Roberto Sabatini, Carlo Diamanti, Wending Dai, Pedro Marques, Anthony Kuyper, Gabriel Correia, Ben Wright, CtrlSoftware, Maiane Araujo, Mihály Dávid Paseczki.
Читайте также: