AI-native design editor. Open-source Figma alternative.
feat: fill layers with Unsplash and Pexels photos from the image fill (#1545)
Danila Poyarkov4ae1128025cd
diff --git a/changes/1545/added.md b/changes/1545/added.mdnew file mode 100644index 000000000..8b1d1b947--- /dev/null+++ b/changes/1545/added.md@@ -0,0 +1,2 @@+- An image fill's **Stock photo** searches Unsplash or Pexels and fills the layer with the photo picked, crediting its photographer and showing the service's own picks before a search; a service without a key leads to its free key in Settings, where **Test connection** checks it.+- A PNG, JPEG, or WebP file dropped on an image fill fills the layer with it.diff --git a/changes/1545/fixed.md b/changes/1545/fixed.mdnew file mode 100644index 000000000..2edbdcaa5--- /dev/null+++ b/changes/1545/fixed.md@@ -0,0 +1 @@+- On the desktop, links in chat replies and collaboration rooms open in the browser, and links such as **Get API key** no longer show a "shell.open not allowed" error.diff --git a/desktop/AGENTS.md b/desktop/AGENTS.mdindex 2338ca703..8ecd75341 100644--- a/desktop/AGENTS.md+++ b/desktop/AGENTS.md@@ -15,6 +15,6 @@ Check `desktop/Cargo.toml`, `desktop/capabilities/**`, and `desktop/tauri.conf.j- Run `bun run generate:icons --target desktop` before direct Cargo checks; native icons are generated, not committed.- `build_fig_file` performs full `.fig` export on desktop at the level it is given, on a blocking thread, since high levels take seconds; saves that patch an opened archive compress in the web worker (`packages/fig/AGENTS.md`).- The embedded WebDriver plugin compiles only with the `native-test` Cargo feature and must never be enabled in development or production binaries. Native tests use `bun run test:native` (`tests/AGENTS.md`).-- The editor opens external links through the `open_external_url` command, which allows only `http`, `https`, and `mailto`; native-test builds record them for `take_native_test_opened_urls` instead of launching a browser (`system::opener` unit tests, `tests/e2e/native/cloud-links.spec.ts`).+- The editor opens external links through the `open_external_url` command, which allows only `http`, `https`, and `mailto`; native-test builds record them for `take_native_test_opened_urls` instead of launching a browser. The main window is built in `setup` so `window.open` goes the same way (`open_new_window_externally`); the shell plugin's own link handler is kept out by `src/app/shell/external-links.ts` (`system::opener` unit tests, `tests/e2e/native/cloud-links.spec.ts`).- `openpencil://` links are parsed in `desktop/src/launch/links.rs` and queued in `desktop/src/launch/mod.rs`: `open` queues files through `take_pending_open`, `join` queues validated room IDs through `take_pending_rooms`, `cloud` queues Cloud invitations and shared links (UUID, hex secret, `http(s)` server) through `take_pending_cloud_links`; second launches forward their link arguments through the single-instance handler (`launch::links` unit tests).- SF Symbols are drawn by SwiftUI through the Swift package `desktop/swift/sf-symbols`, linked by `build.rs` on macOS; they are never bundled, served, or read from Apple's font files. `sf_symbols_render` stays a synchronous command so Tauri runs it on the main thread SwiftUI needs, and both commands answer null below macOS 14, which lacks the path operations that cut badge knockouts (`packages/core/tests/icons/sf-symbols/provider.test.ts`).diff --git a/desktop/src/lib.rs b/desktop/src/lib.rsindex c1632bb4a..08796551d 100644--- a/desktop/src/lib.rs+++ b/desktop/src/lib.rs@@ -114,6 +114,21 @@ pub fn run() {handle_menu_event(app, event.id().0.as_str());}).setup(|app| {+ // The main window is built here rather than from the config alone, so that pages it+ // opens with `window.open` reach the system browser.+ let main = app+ .config()+ .app+ .windows+ .first()+ .cloned()+ .ok_or("the main window is not configured")?;+ tauri::WebviewWindowBuilder::from_config(app.handle(), &main)?+ .on_new_window(system::opener::open_new_window_externally(+ app.handle().clone(),+ ))+ .build()?;+launch::queue_open_paths(app.handle(), args::startup_open_paths());use tauri_plugin_deep_link::DeepLinkExt;diff --git a/desktop/src/system/opener.rs b/desktop/src/system/opener.rsindex 679398789..17102603a 100644--- a/desktop/src/system/opener.rs+++ b/desktop/src/system/opener.rs@@ -48,6 +48,29 @@ pub fn open_external_url(Ok(())}+/// Sends a page the editor opens in a new window, through `window.open`, to the system browser+/// as `open_external_url` does. The webview opens no window of its own; without this handler it+/// would drop the request and the link would do nothing.+pub fn open_new_window_externally<R: tauri::Runtime>(+ app: tauri::AppHandle<R>,+) -> impl Fn(tauri::Url, tauri::webview::NewWindowFeatures) -> tauri::webview::NewWindowResponse<R>+ + Send+ + 'static {+ move |url, _| {+ #[cfg(not(feature = "native-test"))]+ let opened = open_external_url(app.clone(), url.to_string());+ #[cfg(feature = "native-test")]+ let opened = {+ use tauri::Manager;+ open_external_url(app.state::<OpenedExternalUrls>(), url.to_string())+ };+ if let Err(error) = opened {+ eprintln!("[opener] {url}: {error}");+ }+ tauri::webview::NewWindowResponse::Deny+ }+}+#[cfg(feature = "native-test")]#[tauri::command]pub fn take_native_test_opened_urls(state: tauri::State<OpenedExternalUrls>) -> Vec<String> {diff --git a/desktop/tauri.conf.json b/desktop/tauri.conf.jsonindex d4406bac7..92dfe4c9f 100644--- a/desktop/tauri.conf.json+++ b/desktop/tauri.conf.json@@ -15,7 +15,8 @@"title": "OpenPencil","width": 1280,"height": 800,- "dragDropEnabled": false+ "dragDropEnabled": false,+ "create": false}],"security": {diff --git a/desktop/tauri.native-test.conf.json b/desktop/tauri.native-test.conf.jsonindex d18fe643e..06254fbf7 100644--- a/desktop/tauri.native-test.conf.json+++ b/desktop/tauri.native-test.conf.json@@ -12,7 +12,8 @@"title": "OpenPencil Native Test","width": 1280,"height": 800,- "dragDropEnabled": false+ "dragDropEnabled": false,+ "create": false}]},diff --git a/packages/core/src/tools/index.ts b/packages/core/src/tools/index.tsindex 586188e21..fd8362f85 100644--- a/packages/core/src/tools/index.ts+++ b/packages/core/src/tools/index.ts@@ -48,9 +48,14 @@ export { setPexelsAPIKey, setUnsplashAccessKey } from './stock-photo'export { importMermaid, importSVG } from './create'export { arrangeNodes } from './structure'export {+ checkStockPhotoKey,+ getStockPhotoProvider,getStockPhotoProviders,registerStockPhotoProvider,setActiveStockPhotoProvider,+ type StockPhotoKeyCheck,+ type StockPhotoOrientation,type StockPhotoProvider,- type StockPhotoResult+ type StockPhotoResult,+ type StockPhotoSearchOptions} from './stock-photo/providers'diff --git a/packages/core/src/tools/stock-photo.ts b/packages/core/src/tools/stock-photo.tsindex 2f1db5e59..c05c96a98 100644--- a/packages/core/src/tools/stock-photo.ts+++ b/packages/core/src/tools/stock-photo.ts@@ -7,15 +7,7 @@ import { parsePhotoRequests } from './stock-photo/requests'export { applyPhoto, type PhotoRequest, type PhotoResult } from './stock-photo/apply'export { parsePhotoRequests } from './stock-photo/requests'-export {- getStockPhotoProviders,- registerStockPhotoProvider,- setActiveStockPhotoProvider,- setPexelsAPIKey,- setUnsplashAccessKey,- type StockPhotoProvider,- type StockPhotoResult-} from './stock-photo/providers'+export { setPexelsAPIKey, setUnsplashAccessKey } from './stock-photo/providers'export const stockPhoto = defineTool({name: 'stock_photo',@@ -38,7 +30,7 @@ export const stockPhoto = defineTool({const provider = getActiveProvider()if (!provider) {return {- error: `No stock photo provider configured. Ask the user to add an API key in AI chat settings. Available providers: Pexels, Unsplash.`+ error: `No stock photo service has a key. Ask the user to add a Pexels or Unsplash key: Insert photo in the toolbar asks for one.`}}diff --git a/packages/core/src/tools/stock-photo/apply.ts b/packages/core/src/tools/stock-photo/apply.tsindex b094d8e25..45a39ed04 100644--- a/packages/core/src/tools/stock-photo/apply.ts+++ b/packages/core/src/tools/stock-photo/apply.ts@@ -88,6 +88,8 @@ export async function applyPhoto(const imageHash = storeImage(figma.graph, imageBytes)node.fills = [{ type: 'IMAGE', imageHash, scaleMode: 'FILL' }]+ // A missed report does not undo the photo the document already shows.+ await provider.reportUse?.(photo).catch(() => undefined)return {id: node.id,diff --git a/packages/core/src/tools/stock-photo/providers.ts b/packages/core/src/tools/stock-photo/providers.tsindex 742ce62e2..4d5d4efb7 100644--- a/packages/core/src/tools/stock-photo/providers.ts+++ b/packages/core/src/tools/stock-photo/providers.ts@@ -1,23 +1,44 @@import { ofetch } from 'ofetch'+import * as v from 'valibot'export interface StockPhotoResult {+ /** The image at the size asked for, to place in the document. */url: string+ /** A small image for a grid of results. */+ thumbnailURL: stringwidth: numberheight: numberphotographer: string+ /** The photographer's page, which the services ask credits to link to. */+ photographerURL: string+ /** The photo's own page on the service. */+ pageURL: stringsourceId: string}+export type StockPhotoOrientation = 'landscape' | 'portrait' | 'square'++export interface StockPhotoSearchOptions {+ perPage: number+ /** Results page, from 1. */+ page?: number+ /** Any shape when unset. */+ orientation?: StockPhotoOrientation+ targetDim: number+}+export interface StockPhotoProvider {name: string- search(- query: string,- options: {- perPage: number- orientation: 'landscape' | 'portrait' | 'square'- targetDim: number- }- ): Promise<StockPhotoResult[]>+ /** The service's name as people know it: "Pexels". */+ label?: string+ search(query: string, options: StockPhotoSearchOptions): Promise<StockPhotoResult[]>+ /** The photos the service shows before a search: Unsplash's editorial feed, Pexels' curated. */+ browse?(options: StockPhotoSearchOptions): Promise<StockPhotoResult[]>+ /**+ * Tells the service a photo was used, which Unsplash's API terms require of every placed+ * photo; services that do not ask for it leave this out.+ */+ reportUse?(photo: StockPhotoResult): Promise<void>}const providers = new Map<string, StockPhotoProvider>()@@ -36,26 +57,39 @@ export function getStockPhotoProviders(): string[] {return [...providers.keys()]}+/** The chosen service, or the first one with a key once the chosen one's key is removed. */export function getActiveProvider(): StockPhotoProvider | null {- if (!activeProviderId) return null- return providers.get(activeProviderId) ?? null+ const active = activeProviderId ? providers.get(activeProviderId) : undefined+ return active ?? providers.values().next().value ?? null}-interface PexelsPhoto {- id: number- width: number- height: number- photographer: string- src: {- original: string- large2x: string- large: string- medium: string- small: string- landscape: string- }+type CredentialSource = string | null | (() => Promise<string | null>)++async function resolveCredential(source: CredentialSource): Promise<string | null> {+ return typeof source === 'function' ? source() : source}+const pexelsSearchSchema = v.object({+ photos: v.array(+ v.object({+ id: v.number(),+ width: v.number(),+ height: v.number(),+ url: v.string(),+ photographer: v.string(),+ photographer_url: v.string(),+ src: v.object({+ original: v.string(),+ large2x: v.string(),+ large: v.string(),+ medium: v.string(),+ small: v.string()+ })+ })+ )+})+type PexelsPhoto = v.InferOutput<typeof pexelsSearchSchema>['photos'][number]+function pickPexelsSize(src: PexelsPhoto['src'], targetDim: number): string {if (targetDim <= 200) return src.smallif (targetDim <= 400) return src.medium@@ -64,12 +98,6 @@ function pickPexelsSize(src: PexelsPhoto['src'], targetDim: number): string {return src.original}-type CredentialSource = string | null | (() => Promise<string | null>)--async function resolveCredential(source: CredentialSource): Promise<string | null> {- return typeof source === 'function' ? source() : source-}-let pexelsAPIKey: CredentialSource = nullexport function setPexelsAPIKey(key: CredentialSource): void {@@ -77,51 +105,75 @@ export function setPexelsAPIKey(key: CredentialSource): void {if (key) {registerStockPhotoProvider(pexelsProvider)setActiveStockPhotoProvider('pexels')+ } else {+ providers.delete(pexelsProvider.name)}}+async function pexelsPhotos(+ path: string,+ query: Record<string, string | number | undefined>,+ targetDim: number+): Promise<StockPhotoResult[]> {+ const key = await resolveCredential(pexelsAPIKey)+ if (!key) throw new Error('Pexels API key not configured')+ const response = await ofetch.raw(`https://api.pexels.com/v1/${path}`, {+ headers: { Authorization: key },+ ignoreResponseError: true,+ query,+ retry: 0+ })+ if (!response.ok) throw new Error(`Pexels ${response.status}`)+ const data = v.parse(pexelsSearchSchema, response._data)+ return data.photos.map((photo) => ({+ url: pickPexelsSize(photo.src, targetDim),+ thumbnailURL: photo.src.medium,+ width: photo.width,+ height: photo.height,+ photographer: photo.photographer,+ photographerURL: photo.photographer_url,+ pageURL: photo.url,+ sourceId: String(photo.id)+ }))+}+const pexelsProvider: StockPhotoProvider = {name: 'pexels',- async search(query, { perPage, orientation, targetDim }) {- const key = await resolveCredential(pexelsAPIKey)- if (!key) throw new Error('Pexels API key not configured')- const response = await ofetch.raw<{ photos: PexelsPhoto[] }>(- 'https://api.pexels.com/v1/search',- {- headers: { Authorization: key },- ignoreResponseError: true,- query: { query, per_page: perPage, orientation },- retry: 0- }- )- if (!response.ok) throw new Error(`Pexels ${response.status}`)- const data = response._data as { photos: PexelsPhoto[] }- return data.photos.map((photo) => ({- url: pickPexelsSize(photo.src, targetDim),- width: photo.width,- height: photo.height,- photographer: photo.photographer,- sourceId: String(photo.id)- }))+ label: 'Pexels',+ search(query, { perPage, page = 1, orientation, targetDim }) {+ return pexelsPhotos('search', { query, per_page: perPage, page, orientation }, targetDim)+ },+ browse({ perPage, page = 1, targetDim }) {+ return pexelsPhotos('curated', { per_page: perPage, page }, targetDim)}}-let unsplashAccessKey: CredentialSource = null+const unsplashPhotoSchema = v.object({+ id: v.string(),+ width: v.number(),+ height: v.number(),+ urls: v.object({+ raw: v.string(),+ full: v.string(),+ regular: v.string(),+ small: v.string(),+ thumb: v.string()+ }),+ user: v.object({ name: v.string(), links: v.object({ html: v.string() }) }),+ links: v.object({ html: v.string(), download_location: v.string() })+})+type UnsplashPhoto = v.InferOutput<typeof unsplashPhotoSchema>+const unsplashSearchSchema = v.object({ results: v.array(unsplashPhotoSchema) })+const unsplashListSchema = v.array(unsplashPhotoSchema)-export function setUnsplashAccessKey(key: CredentialSource): void {- unsplashAccessKey = key- if (key) {- registerStockPhotoProvider(unsplashProvider)- }-}+/** How long a use report may take; the photo is already placed, so a slow one is dropped. */+const REPORT_USE_TIMEOUT_MS = 10_000-interface UnsplashPhoto {- id: string- width: number- height: number- urls: { raw: string; full: string; regular: string; small: string; thumb: string }- user: { name: string }- links: { download_location: string }+/** Unsplash asks for links back to it to name the app they come from. */+const UNSPLASH_REFERRAL = 'utm_source=openpencil&utm_medium=referral'++function unsplashLink(url: string): string {+ return `${url}${url.includes('?') ? '&' : '?'}${UNSPLASH_REFERRAL}`}function pickUnsplashSize(urls: UnsplashPhoto['urls'], targetDim: number): string {@@ -131,32 +183,122 @@ function pickUnsplashSize(urls: UnsplashPhoto['urls'], targetDim: number): strinreturn urls.full}+let unsplashAccessKey: CredentialSource = null+/** Where to report each placed photo, by photo; Unsplash gives it with the search result. */+const unsplashDownloads = new Map<string, string>()++export function setUnsplashAccessKey(key: CredentialSource): void {+ unsplashAccessKey = key+ if (key) registerStockPhotoProvider(unsplashProvider)+ else providers.delete(unsplashProvider.name)+}++async function unsplashHeaders(): Promise<Record<string, string>> {+ const key = await resolveCredential(unsplashAccessKey)+ if (!key) throw new Error('Unsplash access key not configured')+ return { Authorization: `Client-ID ${key}`, 'Accept-Version': 'v1' }+}++async function unsplashGet(path: string, query: Record<string, string | number | undefined>) {+ const response = await ofetch.raw(`https://api.unsplash.com/${path}`, {+ headers: await unsplashHeaders(),+ ignoreResponseError: true,+ query,+ retry: 0+ })+ if (!response.ok) throw new Error(`Unsplash ${response.status}`)+ return response._data+}++function unsplashResult(photo: UnsplashPhoto, targetDim: number): StockPhotoResult {+ unsplashDownloads.set(photo.id, photo.links.download_location)+ return {+ url: pickUnsplashSize(photo.urls, targetDim),+ thumbnailURL: photo.urls.small,+ width: photo.width,+ height: photo.height,+ photographer: photo.user.name,+ photographerURL: unsplashLink(photo.user.links.html),+ pageURL: unsplashLink(photo.links.html),+ sourceId: photo.id+ }+}+const unsplashProvider: StockPhotoProvider = {name: 'unsplash',- async search(query, { perPage, orientation }) {- const key = await resolveCredential(unsplashAccessKey)- if (!key) throw new Error('Unsplash access key not configured')- const orient = orientation === 'square' ? 'squarish' : orientation- const response = await ofetch.raw<{ results: UnsplashPhoto[] }>(- 'https://api.unsplash.com/search/photos',- {- headers: {- Authorization: `Client-ID ${key}`,- 'Accept-Version': 'v1'- },- ignoreResponseError: true,- query: { query, per_page: perPage, orientation: orient },- retry: 0- }+ label: 'Unsplash',+ async search(query, { perPage, page = 1, orientation, targetDim }) {+ const data = v.parse(+ unsplashSearchSchema,+ await unsplashGet('search/photos', {+ query,+ per_page: perPage,+ page,+ orientation: orientation === 'square' ? 'squarish' : orientation+ })+ )+ return data.results.map((photo) => unsplashResult(photo, targetDim))+ },+ async browse({ perPage, page = 1, targetDim }) {+ const data = v.parse(+ unsplashListSchema,+ await unsplashGet('photos', { per_page: perPage, page }))- if (!response.ok) throw new Error(`Unsplash ${response.status}`)- const data = response._data as { results: UnsplashPhoto[] }- return data.results.map((photo) => ({- url: pickUnsplashSize(photo.urls, 1080),- width: photo.width,- height: photo.height,- photographer: photo.user.name,- sourceId: photo.id- }))+ return data.map((photo) => unsplashResult(photo, targetDim))+ },+ async reportUse(photo) {+ const location = unsplashDownloads.get(photo.sourceId)+ if (!location) return+ await ofetch(location, {+ headers: await unsplashHeaders(),+ retry: 0,+ timeout: REPORT_USE_TIMEOUT_MS+ })+ }+}++/** The registered service called `name`, such as "pexels", or null without its key. */+export function getStockPhotoProvider(name: string): StockPhotoProvider | null {+ return providers.get(name) ?? null+}++/**+ * What one request with a key says about it: it works, the service refused it, the hourly+ * limit is used up, or the service could not be reached or answered something else.+ */+export type StockPhotoKeyCheck = 'ok' | 'rejected' | 'rate-limited' | 'network' | 'failed'++/**+ * Checks a key with the cheapest request each service has, one photo from the list shown before a+ * search; it counts against the hourly limit like any other.+ */+export async function checkStockPhotoKey(+ service: 'pexels' | 'unsplash',+ key: string+): Promise<StockPhotoKeyCheck> {+ const request: { url: string; headers: Record<string, string> } =+ service === 'pexels'+ ? { url: 'https://api.pexels.com/v1/curated', headers: { Authorization: key } }+ : {+ url: 'https://api.unsplash.com/photos',+ headers: { Authorization: `Client-ID ${key}`, 'Accept-Version': 'v1' }+ }+ let response+ try {+ response = await ofetch.raw(request.url, {+ headers: request.headers,+ ignoreResponseError: true,+ query: { per_page: 1 },+ responseType: 'text',+ retry: 0+ })+ } catch {+ return 'network'+ }+ if (response.ok) return 'ok'+ // Unsplash answers a used-up hour with 403 and no requests remaining; Pexels with 429.+ if (response.status === 429 || response.headers.get('x-ratelimit-remaining') === '0') {+ return 'rate-limited'}+ return response.status === 401 || response.status === 403 ? 'rejected' : 'failed'}diff --git a/packages/core/tests/tools/stock-photo/providers.test.ts b/packages/core/tests/tools/stock-photo/providers.test.tsnew file mode 100644index 000000000..0e3c1e870--- /dev/null+++ b/packages/core/tests/tools/stock-photo/providers.test.ts@@ -0,0 +1,169 @@+import { afterEach, expect, test } from 'bun:test'++import {+ checkStockPhotoKey,+ getStockPhotoProvider,+ setPexelsAPIKey,+ setUnsplashAccessKey+} from '#core/tools/stock-photo/providers'++const realFetch = globalThis.fetch+/** Each request the providers sent, and an answer per path. */+let requests: URL[] = []++function answer(byPath: Record<string, unknown>) {+ requests = []+ globalThis.fetch = Object.assign(+ async (input: string | URL | Request) => {+ const url = new URL(input instanceof Request ? input.url : input)+ requests.push(url)+ const body = byPath[url.pathname]+ return body === undefined ? new Response('missing', { status: 404 }) : Response.json(body)+ },+ { preconnect: realFetch.preconnect }+ )+}++afterEach(() => {+ globalThis.fetch = realFetch+ setPexelsAPIKey(null)+ setUnsplashAccessKey(null)+})++test('Unsplash results credit the photographer with referral links, and a used photo is reported', async () => {+ answer({+ '/search/photos': {+ results: [+ {+ id: 'abc',+ width: 1200,+ height: 800,+ urls: { raw: 'r', full: 'f', regular: 'g', small: 's', thumb: 't' },+ user: { name: 'Ann Lee', links: { html: 'https://unsplash.com/@ann' } },+ links: {+ html: 'https://unsplash.com/photos/abc',+ download_location: 'https://api.unsplash.com/photos/abc/download?ixid=1'+ }+ }+ ]+ },+ '/photos/abc/download': { url: 'f' }+ })+ setUnsplashAccessKey('key')+ const provider = getStockPhotoProvider('unsplash')+ if (!provider) throw new Error('Unsplash was not registered')++ const [photo] = await provider.search('hills', { perPage: 3, page: 2, targetDim: 1080 })+ expect(photo).toEqual({+ url: 'g',+ thumbnailURL: 's',+ width: 1200,+ height: 800,+ photographer: 'Ann Lee',+ photographerURL: 'https://unsplash.com/@ann?utm_source=openpencil&utm_medium=referral',+ pageURL: 'https://unsplash.com/photos/abc?utm_source=openpencil&utm_medium=referral',+ sourceId: 'abc'+ })+ expect(Object.fromEntries(requests[0].searchParams)).toEqual({+ query: 'hills',+ per_page: '3',+ page: '2'+ })++ await provider.reportUse?.(photo)+ expect(requests[1].pathname).toBe('/photos/abc/download')+})++test('a malformed answer fails the search instead of returning half a photo', async () => {+ answer({ '/v1/search': { photos: [{ id: 1, width: 10 }] } })+ setPexelsAPIKey('key')+ const provider = getStockPhotoProvider('pexels')+ if (!provider) throw new Error('Pexels was not registered')+ await expect(provider.search('sea', { perPage: 1, targetDim: 100 })).rejects.toThrow()+})++test('removing a key unregisters its service', () => {+ setPexelsAPIKey('key')+ expect(getStockPhotoProvider('pexels')).not.toBeNull()+ setPexelsAPIKey(null)+ expect(getStockPhotoProvider('pexels')).toBeNull()+})++const UNSPLASH_PHOTO = {+ id: 'abc',+ width: 1200,+ height: 800,+ urls: { raw: 'r', full: 'f', regular: 'g', small: 's', thumb: 't' },+ user: { name: 'Ann Lee', links: { html: 'https://unsplash.com/@ann' } },+ links: {+ html: 'https://unsplash.com/photos/abc',+ download_location: 'https://api.unsplash.com/photos/abc/download'+ }+}++test('before a search, Unsplash lists its editorial feed and Pexels its curated photos', async () => {+ answer({+ '/photos': [UNSPLASH_PHOTO],+ '/v1/curated': {+ photos: [+ {+ id: 7,+ width: 10,+ height: 10,+ url: 'https://www.pexels.com/photo/7',+ photographer: 'Bo',+ photographer_url: 'https://www.pexels.com/@bo',+ src: { original: 'o', large2x: 'l2', large: 'l', medium: 'm', small: 's' }+ }+ ]+ }+ })+ setUnsplashAccessKey('key')+ setPexelsAPIKey('key')+ const unsplash = await getStockPhotoProvider('unsplash')?.browse?.({+ perPage: 24,+ targetDim: 1080+ })+ const pexels = await getStockPhotoProvider('pexels')?.browse?.({ perPage: 24, targetDim: 1080 })+ expect(unsplash?.map((photo) => photo.sourceId)).toEqual(['abc'])+ expect(pexels?.map((photo) => photo.sourceId)).toEqual(['7'])+ expect(requests.map((url) => `${url.pathname}?${url.searchParams}`)).toEqual([+ '/photos?per_page=24&page=1',+ '/v1/curated?per_page=24&page=1'+ ])+})++test('a key check tells a working key from a refused one, a used-up hour, and no answer', async () => {+ const answers: (Response | Error)[] = [+ new Response('[]'),+ new Response('OAuth error: The access token is invalid', { status: 401 }),+ new Response('Rate Limit Exceeded', {+ status: 403,+ headers: { 'X-Ratelimit-Remaining': '0' }+ }),+ new Response('', { status: 429 }),+ new TypeError('Load failed')+ ]+ requests = []+ globalThis.fetch = Object.assign(+ async (input: string | URL | Request) => {+ requests.push(new URL(input instanceof Request ? input.url : input))+ const next = answers.shift()+ if (!next || next instanceof Error) throw next ?? new Error('no answer')+ return next+ },+ { preconnect: realFetch.preconnect }+ )+ expect(await checkStockPhotoKey('unsplash', 'good')).toBe('ok')+ expect(await checkStockPhotoKey('unsplash', 'bad')).toBe('rejected')+ expect(await checkStockPhotoKey('unsplash', 'busy')).toBe('rate-limited')+ expect(await checkStockPhotoKey('pexels', 'busy')).toBe('rate-limited')+ expect(await checkStockPhotoKey('pexels', 'offline')).toBe('network')+ expect(requests.map((url) => url.pathname)).toEqual([+ '/photos',+ '/photos',+ '/photos',+ '/v1/curated',+ '/v1/curated'+ ])+})diff --git a/packages/docs/.vitepress/labels.ts b/packages/docs/.vitepress/labels.tsindex ae4bebfe5..8010d8a53 100644--- a/packages/docs/.vitepress/labels.ts+++ b/packages/docs/.vitepress/labels.ts@@ -10,6 +10,7 @@ export interface SidebarLabels {pen: stringvectorEditing: stringicons: string+ photos: stringlayers: stringcontextMenu: stringexporting: string@@ -174,6 +175,7 @@ export const EN: SidebarLabels = {openPencilCloud: 'OpenPencil Cloud',cloudStorage: 'Cloud Storage',icons: 'Icons',+ photos: 'Photos',overview: 'Overview',gettingStarted: 'Getting Started',features: 'Features',@@ -204,6 +206,7 @@ export const DE: SidebarLabels = {openPencilCloud: 'OpenPencil Cloud',cloudStorage: 'Cloud-Speicher',icons: 'Symbole',+ photos: 'Fotos',overview: 'Überblick',gettingStarted: 'Erste Schritte',features: 'Funktionen',@@ -234,6 +237,7 @@ export const IT: SidebarLabels = {openPencilCloud: 'OpenPencil Cloud',cloudStorage: 'Archiviazione cloud',icons: 'Icone',+ photos: 'Foto',overview: 'Panoramica',gettingStarted: 'Per iniziare',features: 'Funzionalità',@@ -264,6 +268,7 @@ export const FR: SidebarLabels = {openPencilCloud: 'OpenPencil Cloud',cloudStorage: 'Stockage cloud',icons: 'Icônes',+ photos: 'Photos',overview: 'Vue d’ensemble',gettingStarted: 'Premiers pas',features: 'Fonctionnalités',@@ -294,6 +299,7 @@ export const ES: SidebarLabels = {openPencilCloud: 'OpenPencil Cloud',cloudStorage: 'Almacenamiento en la nube',icons: 'Iconos',+ photos: 'Fotos',overview: 'Resumen',gettingStarted: 'Primeros pasos',features: 'Características',@@ -324,6 +330,7 @@ export const PL: SidebarLabels = {openPencilCloud: 'OpenPencil Cloud',cloudStorage: 'Przechowywanie w chmurze',icons: 'Ikony',+ photos: 'Zdjęcia',overview: 'Przegląd',gettingStarted: 'Rozpoczęcie pracy',features: 'Funkcje',@@ -354,6 +361,7 @@ export const RU: SidebarLabels = {openPencilCloud: 'OpenPencil Cloud',cloudStorage: 'Облачное хранилище',icons: 'Иконки',+ photos: 'Фото',overview: 'Обзор',gettingStarted: 'Начало работы',features: 'Возможности',diff --git a/packages/docs/.vitepress/sidebars.ts b/packages/docs/.vitepress/sidebars.tsindex 663f14b76..b76d26557 100644--- a/packages/docs/.vitepress/sidebars.ts+++ b/packages/docs/.vitepress/sidebars.ts@@ -35,6 +35,7 @@ export const userGuideSidebar = ({ text: labels.vectorEditing, link: `${prefix}/user-guide/vector-edit` },// English only until translated; locales link to the canonical page.{ text: labels.icons, link: '/user-guide/icons' },+ { text: labels.photos, link: '/user-guide/photos' },],},{diff --git a/packages/docs/overview/privacy.md b/packages/docs/overview/privacy.mdindex 86875bc3e..b8a755372 100644--- a/packages/docs/overview/privacy.md+++ b/packages/docs/overview/privacy.md@@ -90,6 +90,6 @@ OpenPencil is local-first, but some features reach the network. The desktop app| Cloud storage | The storage provider you configure || Fonts | Google Fonts, which can supply a font a document uses that is not installed || Icons | The Iconify API, when you search or insert icons |-| Stock images | Unsplash or Pexels, when you search them |+| Stock photos | Unsplash or Pexels, with your own key, when you search them or place one of their photos |The app, the feedback service, and this page are open source. The event list lives in [`packages/feedback/src/contract`](https://github.com/open-pencil/open-pencil/tree/master/packages/feedback/src/contract), and the tables above are generated from it.diff --git a/packages/docs/user-guide/photos.md b/packages/docs/user-guide/photos.mdnew file mode 100644index 000000000..2d8f311fb--- /dev/null+++ b/packages/docs/user-guide/photos.md@@ -0,0 +1,31 @@+---+title: Photos+description: Fill a layer with a free stock photo from Unsplash or Pexels in OpenPencil.+---++# Photos++OpenPencil searches the free photo libraries of [Unsplash](https://unsplash.com) and [Pexels](https://www.pexels.com) from a layer's image fill. Both let anyone use their photos for free, and both ask for an API key to search them, which is free too. The key stays on your device.++Searching and using photos needs a network connection to the service you search.++## Filling a Layer with a Photo++Draw the frame or shape the photo should fill, then:++1. Open its fill and switch it to **Image**.+2. Choose **Stock photo** in the preview.+3. Before you type, the picker shows the service's own picks: Unsplash's editorial feed or Pexels' curated photos. Type what you're looking for, such as `mountains` or `coffee`; more results load as you scroll. Hover over a photo, or move to it with the arrow keys, to see who took it.+4. Pick one. It becomes the layer's image fill and keeps the fill's scale mode, so **Fill**, **Fit**, **Crop**, and **Tile** work on it as on any image.++The service button in the picker's header switches between Unsplash and Pexels. The picker opens on the one you used last, or on one with a key when that one has none. Until a service has a key, the picker says so: choose **Open Settings**, open the service in **Settings → Media**, follow **Get API key** to create one, paste it, and choose **Save**. **Test connection** tries the key you typed, or the saved one, with one request to the service.++An Unsplash app has two keys: paste its **Access Key**, not its Secret key. A new Unsplash app allows 50 requests an hour until Unsplash approves it for production; each search, each page of results, and each test counts.++Pexels has paused issuing new API keys. If you already have a Pexels key, it still works; otherwise use Unsplash.++## Credits and Keys++Unsplash and Pexels ask that photos are credited to the people who took them; the picker names the photographer of each photo. OpenPencil tells Unsplash when one of its photos is used, as its API terms require.++Change or remove the keys in **Settings → Media**. The AI chat's stock photo tool uses the same keys.diff --git a/packages/vue/src/i18n/locales/de/media.json b/packages/vue/src/i18n/locales/de/media.jsonindex feb3449aa..641d67eea 100644--- a/packages/vue/src/i18n/locales/de/media.json+++ b/packages/vue/src/i18n/locales/de/media.json@@ -7,5 +7,11 @@"stockPhotoToolOptional": "Optional — Zugangsdaten für das stock_photo-Werkzeug","pexelsAlternativeOptional": "Optional — Alternative zu Pexels","getPexelsAPIKey": "Kostenlosen Pexels-API-Schlüssel abrufen →",- "getUnsplashAccessKey": "Kostenlosen Unsplash-Zugriffsschlüssel abrufen →"+ "getUnsplashAccessKey": "Kostenlosen Unsplash-Zugriffsschlüssel abrufen →",+ "photoKeyWorks": "{service} hat diesen Schlüssel akzeptiert.",+ "photoKeyRejected": "{service} hat diesen Schlüssel abgelehnt. Prüfe, ob du ihn vollständig kopiert hast.",+ "unsplashKeyRejected": "Unsplash hat diesen Schlüssel abgelehnt. Füge den Access Key deiner App ein, nicht den Secret Key.",+ "photoKeyRateLimited": "Dieser Schlüssel hat seine {service}-Anfragen für diese Stunde aufgebraucht. Versuche es später erneut.",+ "photoKeyUnreachable": "{service} ist nicht erreichbar. Prüfe deine Netzwerkverbindung.",+ "photoKeyCheckFailed": "{service} hat auf den Test nicht geantwortet. Versuche es später erneut."}diff --git a/packages/vue/src/i18n/locales/de/panels.json b/packages/vue/src/i18n/locales/de/panels.jsonindex 46a61ec2b..ff6c4194e 100644--- a/packages/vue/src/i18n/locales/de/panels.json+++ b/packages/vue/src/i18n/locales/de/panels.json@@ -516,6 +516,17 @@"recentIcons": "Zuletzt verwendet","iconsInFile": "In dieser Datei","otherIconSets": "Andere",+ "stockPhoto": "Stockfoto",+ "searchPhotos": "Fotos suchen...",+ "noPhotosFound": "Keine Fotos gefunden",+ "photoSearchHint": "Tippe, um kostenlose Fotos auf {service} zu suchen",+ "photoSearchFailed": "{service} konnte nicht durchsucht werden. Prüfe deine Verbindung und deinen Schlüssel.",+ "insertPhotoFailed": "Das Foto konnte nicht eingefügt werden.",+ "photoService": "Fotodienst",+ "photoCredit": "Foto von {photographer} auf {service}",+ "photoKeyHeading": "{service} verbinden",+ "photoKeyDescription": "{service}-Fotos sind kostenlos nutzbar. Füge in den Einstellungen den kostenlosen API-Schlüssel hinzu, um sie hier zu durchsuchen.",+ "photoKeyAction": "Einstellungen öffnen","iconResultCount": {"one": "{count} Ergebnis","many": "{count} Ergebnisse"diff --git a/packages/vue/src/i18n/locales/es/media.json b/packages/vue/src/i18n/locales/es/media.jsonindex 64fd82b0b..3081bc3a5 100644--- a/packages/vue/src/i18n/locales/es/media.json+++ b/packages/vue/src/i18n/locales/es/media.json@@ -7,5 +7,11 @@"stockPhotoToolOptional": "Opcional — para herramienta stock_photo","pexelsAlternativeOptional": "Opcional — alternativa a Pexels","getPexelsAPIKey": "Obtener clave API gratuita de Pexels →",- "getUnsplashAccessKey": "Obtener clave de acceso gratuita de Unsplash →"+ "getUnsplashAccessKey": "Obtener clave de acceso gratuita de Unsplash →",+ "photoKeyWorks": "{service} aceptó esta clave.",+ "photoKeyRejected": "{service} rechazó esta clave. Comprueba que la copiaste completa.",+ "unsplashKeyRejected": "Unsplash rechazó esta clave. Pega la Access Key de tu aplicación, no la Secret key.",+ "photoKeyRateLimited": "Esta clave agotó sus solicitudes a {service} de esta hora. Inténtalo más tarde.",+ "photoKeyUnreachable": "No se pudo conectar con {service}. Comprueba tu conexión de red.",+ "photoKeyCheckFailed": "{service} no respondió a la prueba. Inténtalo más tarde."}diff --git a/packages/vue/src/i18n/locales/es/panels.json b/packages/vue/src/i18n/locales/es/panels.jsonindex 6f8d57eda..77c7b50a5 100644--- a/packages/vue/src/i18n/locales/es/panels.json+++ b/packages/vue/src/i18n/locales/es/panels.json@@ -516,6 +516,17 @@"recentIcons": "Recientes","iconsInFile": "En este archivo","otherIconSets": "Otros",+ "stockPhoto": "Foto de stock",+ "searchPhotos": "Buscar fotos...",+ "noPhotosFound": "No se encontraron fotos",+ "photoSearchHint": "Escribe para buscar fotos gratuitas en {service}",+ "photoSearchFailed": "No se pudo buscar en {service}. Comprueba tu conexión y tu clave.",+ "insertPhotoFailed": "No se pudo insertar la foto.",+ "photoService": "Servicio de fotos",+ "photoCredit": "Foto de {photographer} en {service}",+ "photoKeyHeading": "Conectar {service}",+ "photoKeyDescription": "Las fotos de {service} son de uso gratuito. Añade su clave de API gratuita en Ajustes para buscarlas aquí.",+ "photoKeyAction": "Abrir Ajustes","iconResultCount": {"one": "{count} resultado","many": "{count} resultados"diff --git a/packages/vue/src/i18n/locales/fr/media.json b/packages/vue/src/i18n/locales/fr/media.jsonindex a4187779a..385c05f0d 100644--- a/packages/vue/src/i18n/locales/fr/media.json+++ b/packages/vue/src/i18n/locales/fr/media.json@@ -7,5 +7,11 @@"stockPhotoToolOptional": "Facultatif — active l’outil de photos de stock","pexelsAlternativeOptional": "Facultatif — source alternative de photos","getPexelsAPIKey": "Obtenir une clé API Pexels gratuite →",- "getUnsplashAccessKey": "Obtenir une clé d’accès Unsplash gratuite →"+ "getUnsplashAccessKey": "Obtenir une clé d’accès Unsplash gratuite →",+ "photoKeyWorks": "{service} a accepté cette clé.",+ "photoKeyRejected": "{service} a refusé cette clé. Vérifiez que vous l’avez copiée en entier.",+ "unsplashKeyRejected": "Unsplash a refusé cette clé. Collez l’Access Key de votre application, pas sa Secret key.",+ "photoKeyRateLimited": "Cette clé a épuisé ses requêtes {service} pour cette heure. Réessayez plus tard.",+ "photoKeyUnreachable": "Impossible de joindre {service}. Vérifiez votre connexion réseau.",+ "photoKeyCheckFailed": "{service} n’a pas répondu au test. Réessayez plus tard."}diff --git a/packages/vue/src/i18n/locales/fr/panels.json b/packages/vue/src/i18n/locales/fr/panels.jsonindex 39d1c87f1..9651b8e3b 100644--- a/packages/vue/src/i18n/locales/fr/panels.json+++ b/packages/vue/src/i18n/locales/fr/panels.json@@ -516,6 +516,17 @@"recentIcons": "Récentes","iconsInFile": "Dans ce fichier","otherIconSets": "Autres",+ "stockPhoto": "Photo de stock",+ "searchPhotos": "Rechercher des photos...",+ "noPhotosFound": "Aucune photo trouvée",+ "photoSearchHint": "Tapez pour rechercher des photos gratuites sur {service}",+ "photoSearchFailed": "Impossible de rechercher sur {service}. Vérifiez votre connexion et votre clé.",+ "insertPhotoFailed": "La photo n'a pas pu être insérée.",+ "photoService": "Service de photos",+ "photoCredit": "Photo de {photographer} sur {service}",+ "photoKeyHeading": "Connecter {service}",+ "photoKeyDescription": "Les photos {service} sont gratuites. Ajoutez sa clé d'API gratuite dans les Réglages pour les rechercher ici.",+ "photoKeyAction": "Ouvrir les Réglages","iconResultCount": {"one": "{count} résultat","many": "{count} résultats"diff --git a/packages/vue/src/i18n/locales/it/media.json b/packages/vue/src/i18n/locales/it/media.jsonindex 401972c70..bf109b234 100644--- a/packages/vue/src/i18n/locales/it/media.json+++ b/packages/vue/src/i18n/locales/it/media.json@@ -7,5 +7,11 @@"stockPhotoToolOptional": "Facoltativo — abilita lo strumento foto stock","pexelsAlternativeOptional": "Facoltativo — fonte alternativa di foto stock","getPexelsAPIKey": "Ottieni una chiave API Pexels gratuita →",- "getUnsplashAccessKey": "Ottieni una chiave di accesso Unsplash gratuita →"+ "getUnsplashAccessKey": "Ottieni una chiave di accesso Unsplash gratuita →",+ "photoKeyWorks": "{service} ha accettato questa chiave.",+ "photoKeyRejected": "{service} ha rifiutato questa chiave. Controlla di averla copiata per intero.",+ "unsplashKeyRejected": "Unsplash ha rifiutato questa chiave. Incolla l’Access Key della tua app, non la Secret key.",+ "photoKeyRateLimited": "Questa chiave ha esaurito le richieste a {service} per quest’ora. Riprova più tardi.",+ "photoKeyUnreachable": "Impossibile raggiungere {service}. Controlla la connessione di rete.",+ "photoKeyCheckFailed": "{service} non ha risposto al test. Riprova più tardi."}diff --git a/packages/vue/src/i18n/locales/it/panels.json b/packages/vue/src/i18n/locales/it/panels.jsonindex 9061798f5..90fdf2b70 100644--- a/packages/vue/src/i18n/locales/it/panels.json+++ b/packages/vue/src/i18n/locales/it/panels.json@@ -516,6 +516,17 @@"recentIcons": "Recenti","iconsInFile": "In questo file","otherIconSets": "Altri",+ "stockPhoto": "Foto stock",+ "searchPhotos": "Cerca foto...",+ "noPhotosFound": "Nessuna foto trovata",+ "photoSearchHint": "Digita per cercare foto gratuite su {service}",+ "photoSearchFailed": "Impossibile cercare su {service}. Controlla la connessione e la chiave.",+ "insertPhotoFailed": "Impossibile inserire la foto.",+ "photoService": "Servizio di foto",+ "photoCredit": "Foto di {photographer} su {service}",+ "photoKeyHeading": "Collega {service}",+ "photoKeyDescription": "Le foto di {service} sono gratuite. Aggiungi la sua chiave API gratuita nelle Impostazioni per cercarle qui.",+ "photoKeyAction": "Apri Impostazioni","iconResultCount": {"one": "{count} risultato","many": "{count} risultati"diff --git a/packages/vue/src/i18n/locales/ja/media.json b/packages/vue/src/i18n/locales/ja/media.jsonindex e67f7ad01..796aa509e 100644--- a/packages/vue/src/i18n/locales/ja/media.json+++ b/packages/vue/src/i18n/locales/ja/media.json@@ -7,5 +7,11 @@"stockPhotoToolOptional": "任意 — stock_photoツール用","pexelsAlternativeOptional": "任意 — Pexelsの代替案","getPexelsAPIKey": "Pexelsの無料APIキーを取得 →",- "getUnsplashAccessKey": "Unsplashの無料アクセスキーを取得 →"+ "getUnsplashAccessKey": "Unsplashの無料アクセスキーを取得 →",+ "photoKeyWorks": "{service} はこのキーを受け付けました。",+ "photoKeyRejected": "{service} がこのキーを拒否しました。キー全体をコピーしたか確認してください。",+ "unsplashKeyRejected": "Unsplash がこのキーを拒否しました。Secret key ではなく、アプリの Access Key を貼り付けてください。",+ "photoKeyRateLimited": "このキーは今の 1 時間の {service} リクエスト上限に達しました。しばらくしてからお試しください。",+ "photoKeyUnreachable": "{service} に接続できませんでした。ネットワーク接続を確認してください。",+ "photoKeyCheckFailed": "{service} がテストに応答しませんでした。しばらくしてからお試しください。"}diff --git a/packages/vue/src/i18n/locales/ja/panels.json b/packages/vue/src/i18n/locales/ja/panels.jsonindex 684c40bcf..1870b80b2 100644--- a/packages/vue/src/i18n/locales/ja/panels.json+++ b/packages/vue/src/i18n/locales/ja/panels.json@@ -510,6 +510,17 @@"recentIcons": "最近使用","iconsInFile": "このファイル内","otherIconSets": "その他",+ "stockPhoto": "ストック写真",+ "searchPhotos": "写真を検索...",+ "noPhotosFound": "写真が見つかりません",+ "photoSearchHint": "入力して {service} の無料写真を検索",+ "photoSearchFailed": "{service} を検索できませんでした。接続とキーを確認してください。",+ "insertPhotoFailed": "写真を挿入できませんでした。",+ "photoService": "写真サービス",+ "photoCredit": "{photographer} による写真({service})",+ "photoKeyHeading": "{service} を接続",+ "photoKeyDescription": "{service} の写真は無料で使えます。設定で無料の API キーを追加すると、ここで検索できます。",+ "photoKeyAction": "設定を開く","iconResultCount": {"many": "{count} 件の結果"},diff --git a/packages/vue/src/i18n/locales/pl/media.json b/packages/vue/src/i18n/locales/pl/media.jsonindex c23078dd1..1cb159457 100644--- a/packages/vue/src/i18n/locales/pl/media.json+++ b/packages/vue/src/i18n/locales/pl/media.json@@ -7,5 +7,11 @@"stockPhotoToolOptional": "Opcjonalne — dane dostępowe dla narzędzia stock_photo","pexelsAlternativeOptional": "Opcjonalne — alternatywa dla Pexels","getPexelsAPIKey": "Pobierz bezpłatny klucz API Pexels →",- "getUnsplashAccessKey": "Pobierz bezpłatny klucz dostępu Unsplash →"+ "getUnsplashAccessKey": "Pobierz bezpłatny klucz dostępu Unsplash →",+ "photoKeyWorks": "{service} zaakceptował ten klucz.",+ "photoKeyRejected": "{service} odrzucił ten klucz. Sprawdź, czy skopiowano go w całości.",+ "unsplashKeyRejected": "Unsplash odrzucił ten klucz. Wklej Access Key swojej aplikacji, a nie Secret key.",+ "photoKeyRateLimited": "Ten klucz wykorzystał limit zapytań do {service} na tę godzinę. Spróbuj później.",+ "photoKeyUnreachable": "Nie udało się połączyć z {service}. Sprawdź połączenie sieciowe.",+ "photoKeyCheckFailed": "{service} nie odpowiedział na test. Spróbuj później."}diff --git a/packages/vue/src/i18n/locales/pl/panels.json b/packages/vue/src/i18n/locales/pl/panels.jsonindex e2a1e967c..a40c95dbe 100644--- a/packages/vue/src/i18n/locales/pl/panels.json+++ b/packages/vue/src/i18n/locales/pl/panels.json@@ -522,6 +522,17 @@"recentIcons": "Ostatnie","iconsInFile": "W tym pliku","otherIconSets": "Inne",+ "stockPhoto": "Zdjęcie stockowe",+ "searchPhotos": "Szukaj zdjęć...",+ "noPhotosFound": "Nie znaleziono zdjęć",+ "photoSearchHint": "Wpisz, aby szukać darmowych zdjęć w {service}",+ "photoSearchFailed": "Nie udało się przeszukać {service}. Sprawdź połączenie i klucz.",+ "insertPhotoFailed": "Nie udało się wstawić zdjęcia.",+ "photoService": "Serwis ze zdjęciami",+ "photoCredit": "Zdjęcie: {photographer}, {service}",+ "photoKeyHeading": "Połącz {service}",+ "photoKeyDescription": "Zdjęcia z {service} są darmowe. Dodaj jego darmowy klucz API w Ustawieniach, aby wyszukiwać je tutaj.",+ "photoKeyAction": "Otwórz Ustawienia","iconResultCount": {"one": "{count} wynik","few": "{count} wyniki",diff --git a/packages/vue/src/i18n/locales/ru/media.json b/packages/vue/src/i18n/locales/ru/media.jsonindex 834a894d1..51b2b9ba6 100644--- a/packages/vue/src/i18n/locales/ru/media.json+++ b/packages/vue/src/i18n/locales/ru/media.json@@ -7,5 +7,11 @@"stockPhotoToolOptional": "Необязательно — включает инструмент стоковых фото","pexelsAlternativeOptional": "Необязательно — альтернативный источник фото","getPexelsAPIKey": "Получить бесплатный API-ключ Pexels →",- "getUnsplashAccessKey": "Получить бесплатный ключ доступа Unsplash →"+ "getUnsplashAccessKey": "Получить бесплатный ключ доступа Unsplash →",+ "photoKeyWorks": "{service} принял этот ключ.",+ "photoKeyRejected": "{service} не принял этот ключ. Проверьте, что скопировали его целиком.",+ "unsplashKeyRejected": "Unsplash не принял этот ключ. Вставьте Access Key вашего приложения, а не Secret key.",+ "photoKeyRateLimited": "Этот ключ исчерпал запросы к {service} на этот час. Попробуйте позже.",+ "photoKeyUnreachable": "Не удалось связаться с {service}. Проверьте подключение к сети.",+ "photoKeyCheckFailed": "{service} не ответил на проверку. Попробуйте позже."}diff --git a/packages/vue/src/i18n/locales/ru/panels.json b/packages/vue/src/i18n/locales/ru/panels.jsonindex 058929dd3..a064305ab 100644--- a/packages/vue/src/i18n/locales/ru/panels.json+++ b/packages/vue/src/i18n/locales/ru/panels.json@@ -522,6 +522,17 @@"recentIcons": "Недавние","iconsInFile": "В этом файле","otherIconSets": "Другие",+ "stockPhoto": "Стоковое фото",+ "searchPhotos": "Поиск фото...",+ "noPhotosFound": "Фото не найдены",+ "photoSearchHint": "Начните вводить, чтобы найти бесплатные фото на {service}",+ "photoSearchFailed": "Не удалось выполнить поиск на {service}. Проверьте подключение и ключ.",+ "insertPhotoFailed": "Не удалось вставить фото.",+ "photoService": "Фотосервис",+ "photoCredit": "Фото: {photographer}, {service}",+ "photoKeyHeading": "Подключить {service}",+ "photoKeyDescription": "Фото с {service} можно использовать бесплатно. Добавьте бесплатный API-ключ в Настройках, чтобы искать их здесь.",+ "photoKeyAction": "Открыть настройки","iconResultCount": {"one": "{count} результат","few": "{count} результата",diff --git a/packages/vue/src/i18n/locales/zh-cn/media.json b/packages/vue/src/i18n/locales/zh-cn/media.jsonindex bc339cbe1..019ce9668 100644--- a/packages/vue/src/i18n/locales/zh-cn/media.json+++ b/packages/vue/src/i18n/locales/zh-cn/media.json@@ -7,5 +7,11 @@"stockPhotoToolOptional": "可选,用于 stock_photo 工具","pexelsAlternativeOptional": "可选,作为 Pexels 的替代","getPexelsAPIKey": "获取免费 Pexels API 密钥 →",- "getUnsplashAccessKey": "获取免费的 Unsplash 访问密钥 →"+ "getUnsplashAccessKey": "获取免费的 Unsplash 访问密钥 →",+ "photoKeyWorks": "{service} 接受了此密钥。",+ "photoKeyRejected": "{service} 拒绝了此密钥。请检查是否完整复制。",+ "unsplashKeyRejected": "Unsplash 拒绝了此密钥。请粘贴应用的 Access Key,而不是 Secret key。",+ "photoKeyRateLimited": "此密钥本小时的 {service} 请求已用完。请稍后再试。",+ "photoKeyUnreachable": "无法连接 {service}。请检查网络连接。",+ "photoKeyCheckFailed": "{service} 没有响应测试。请稍后再试。"}diff --git a/packages/vue/src/i18n/locales/zh-cn/panels.json b/packages/vue/src/i18n/locales/zh-cn/panels.jsonindex 727665ba2..e496b968d 100644--- a/packages/vue/src/i18n/locales/zh-cn/panels.json+++ b/packages/vue/src/i18n/locales/zh-cn/panels.json@@ -510,6 +510,17 @@"recentIcons": "最近使用","iconsInFile": "此文件中","otherIconSets": "其他",+ "stockPhoto": "图库照片",+ "searchPhotos": "搜索照片...",+ "noPhotosFound": "未找到照片",+ "photoSearchHint": "输入以搜索 {service} 上的免费照片",+ "photoSearchFailed": "无法搜索 {service},请检查网络连接和密钥。",+ "insertPhotoFailed": "无法插入照片。",+ "photoService": "照片服务",+ "photoCredit": "{photographer} 拍摄,来自 {service}",+ "photoKeyHeading": "连接 {service}",+ "photoKeyDescription": "{service} 的照片可免费使用。在设置中添加其免费 API 密钥即可在此搜索。",+ "photoKeyAction": "打开设置","iconResultCount": {"many": "{count} 个结果"},diff --git a/packages/vue/src/i18n/messages/media.ts b/packages/vue/src/i18n/messages/media.tsindex ad4f632f6..7b0641127 100644--- a/packages/vue/src/i18n/messages/media.ts+++ b/packages/vue/src/i18n/messages/media.ts@@ -1,3 +1,5 @@+import { params } from '@nanostores/i18n'+import { i18n } from '#vue/i18n/create'export const mediaMessageDefaults = {@@ -10,7 +12,16 @@ export const mediaMessageDefaults = {stockPhotoToolOptional: 'Optional — for stock_photo tool',pexelsAlternativeOptional: 'Optional — alternative to Pexels',getPexelsAPIKey: 'Get free Pexels API key →',- getUnsplashAccessKey: 'Get free Unsplash access key →'+ getUnsplashAccessKey: 'Get free Unsplash access key →',+ photoKeyWorks: params('{service} accepted this key.'),+ photoKeyRejected: params('{service} refused this key. Check that you copied all of it.'),+ unsplashKeyRejected:+ 'Unsplash refused this key. Paste your app’s Access Key, not its Secret key.',+ photoKeyRateLimited: params(+ 'This key has used up its {service} requests for this hour. Try again later.'+ ),+ photoKeyUnreachable: params('Couldn’t reach {service}. Check your network connection.'),+ photoKeyCheckFailed: params('{service} didn’t answer the test. Try again later.')} as constexport const mediaMessages = i18n('media', mediaMessageDefaults)diff --git a/packages/vue/src/i18n/messages/panels.ts b/packages/vue/src/i18n/messages/panels.tsindex b384e0f38..9a306fcfa 100644--- a/packages/vue/src/i18n/messages/panels.ts+++ b/packages/vue/src/i18n/messages/panels.ts@@ -615,6 +615,21 @@ export const panelMessageDefaults = {recentIcons: 'Recent',iconsInFile: 'In this file',otherIconSets: 'Other',+ /** The image fill's button that fills it with a photo from Unsplash or Pexels. */+ stockPhoto: 'Stock photo',+ searchPhotos: 'Search photos...',+ noPhotosFound: 'No photos found',+ photoSearchHint: params('Type to search free photos on {service}'),+ photoSearchFailed: params('{service} could not be searched. Check your connection and key.'),+ insertPhotoFailed: 'The photo could not be inserted.',+ photoService: 'Photo service',+ /** The picker's credit for a photo, as the services ask to be credited. */+ photoCredit: params('Photo by {photographer} on {service}'),+ photoKeyHeading: params('Connect {service}'),+ photoKeyDescription: params(+ '{service} photos are free to use. Add its free API key in Settings to search them here.'+ ),+ photoKeyAction: 'Open Settings',iconResultCount: count({ one: '{count} result', many: '{count} results' }),/** More icons match than a search returns. */iconResultCountCapped: params('{count}+ results'),diff --git a/src/AGENTS.md b/src/AGENTS.mdindex 0c3cc526c..03d0b40c2 100644--- a/src/AGENTS.md+++ b/src/AGENTS.md@@ -58,7 +58,7 @@ The supported browser baseline lives in `src/app/shell/support/baseline.ts` and## UI-`src/components/ui/**` is generic, store-free design-system code grouped by family: `{binding,button,collapsible,date,dialog,feedback,input,list,menu,overlay,paint,panel,select,table,tabs,toggle}/`. Do not create a folder named after a single component. Feature controls stay in their domain. Theme families mirror these under `src/theme/`; feature themes stay separate. Use explicit imports without old-path forwarding shims.+`src/components/ui/**` is generic, store-free design-system code grouped by family: `{binding,button,collapsible,date,dialog,drop,feedback,input,list,menu,overlay,paint,panel,select,table,tabs,toggle}/`. Do not create a folder named after a single component. Feature controls stay in their domain. Theme families mirror these under `src/theme/`; feature themes stay separate. Use explicit imports without old-path forwarding shims.### Namingdiff --git a/src/app/editor/photos/download.ts b/src/app/editor/photos/download.tsnew file mode 100644index 000000000..729b90fc8--- /dev/null+++ b/src/app/editor/photos/download.ts@@ -0,0 +1,25 @@+import { getStockPhotoProvider, type StockPhotoResult } from '@open-pencil/core/tools'+import { IMPORTABLE_RASTER_TYPES } from '@open-pencil/scene-graph/images'++import type { PhotoService } from './search'++/**+ * Downloads `photo` at the size it is placed at and tells its service it was used, as Unsplash's+ * terms ask; a failed report does not stop the photo.+ */+export async function downloadPhoto(service: PhotoService, photo: StockPhotoResult) {+ const response = await fetch(photo.url)+ if (!response.ok) throw new Error(`Download ${response.status}`)+ // "image/jpeg; charset=binary" is still a JPEG; anything that cannot be placed fails here,+ // before the service is told the photo was used.+ const type = (response.headers.get('content-type') ?? 'image/jpeg')+ .split(';')[0]+ .trim()+ .toLowerCase()+ if (!IMPORTABLE_RASTER_TYPES.has(type)) throw new Error(`Unsupported photo type ${type}`)+ const bytes = new Uint8Array(await response.arrayBuffer())+ void getStockPhotoProvider(service)+ ?.reportUse?.(photo)+ .catch(() => undefined)+ return { bytes, type }+}diff --git a/src/app/editor/photos/search.ts b/src/app/editor/photos/search.tsnew file mode 100644index 000000000..2b20e261e--- /dev/null+++ b/src/app/editor/photos/search.ts@@ -0,0 +1,155 @@+import { useLocalStorage, watchDebounced } from '@vueuse/core'+import { computed, ref, shallowRef, watch } from 'vue'++import { getStockPhotoProvider, type StockPhotoResult } from '@open-pencil/core/tools'++import { pexelsKeyStatus, unsplashKeyStatus } from '@/app/settings/credentials/media'++export type PhotoService = 'unsplash' | 'pexels'++/** The services, with where to get a key and the site the picker credits, as both ask. */+export const PHOTO_SERVICES: readonly {+ id: PhotoService+ name: string+ keyURL: string+ siteURL: string+}[] = [+ {+ id: 'unsplash',+ name: 'Unsplash',+ keyURL: 'https://unsplash.com/oauth/applications',+ siteURL: 'https://unsplash.com/?utm_source=openpencil&utm_medium=referral'+ },+ {+ id: 'pexels',+ name: 'Pexels',+ keyURL: 'https://www.pexels.com/api/',+ siteURL: 'https://www.pexels.com'+ }+]++const PHOTO_SERVICE_STORAGE_KEY = 'open-pencil:photo-service'+/** Results a page; a multiple of the picker's three columns. */+const PHOTOS_PER_PAGE = 24+/** The width a placed photo is downloaded at; the services' regular size. */+export const PLACED_PHOTO_SIZE = 1080+const SEARCH_DEBOUNCE_MS = 300++/** The service the picker searched last. */+export const lastPhotoService = useLocalStorage<PhotoService>(PHOTO_SERVICE_STORAGE_KEY, 'unsplash')++export function photoServiceHasKey(service: PhotoService): boolean {+ const status = service === 'pexels' ? pexelsKeyStatus.value : unsplashKeyStatus.value+ return status === 'configured'+}++/**+ * Searches the chosen stock photo service as the query changes, a page at a time, and shows its+ * own picks (Unsplash's editorial feed, Pexels' curated photos) while the query is empty. A newer+ * request drops the answers to older ones.+ */+export function usePhotoSearch() {+ const query = ref('')+ const service = lastPhotoService+ const photos = shallowRef<StockPhotoResult[]>([])+ const loading = ref(false)+ const failed = ref(false)+ const hasMore = ref(false)+ const hasKey = computed(() => photoServiceHasKey(service.value))+ let page = 0+ let generation = 0+ /**+ * The picks last listed, kept so clearing a search shows them again without another request:+ * a new Unsplash key has 50 requests an hour.+ */+ let picks: {+ service: PhotoService+ photos: StockPhotoResult[]+ page: number+ hasMore: boolean+ } | null = null++ function show(found: StockPhotoResult[], next: number, more: boolean) {+ page = next+ const shown = next === 1 ? [] : photos.value+ const seen = new Set(shown.map((photo) => photo.sourceId))+ photos.value = [...shown, ...found.filter((photo) => !seen.has(photo.sourceId))]+ hasMore.value = more+ }++ async function load(next: number) {+ const term = query.value.trim()+ const provider = getStockPhotoProvider(service.value)+ const current = ++generation+ if (!provider || (!term && !provider.browse)) {+ photos.value = []+ loading.value = false+ failed.value = false+ hasMore.value = false+ return+ }+ if (!term && next === 1 && picks?.service === service.value) {+ photos.value = picks.photos+ page = picks.page+ hasMore.value = picks.hasMore+ loading.value = false+ failed.value = false+ return+ }+ loading.value = true+ failed.value = false+ const options = { perPage: PHOTOS_PER_PAGE, page: next, targetDim: PLACED_PHOTO_SIZE }+ try {+ const found = term+ ? await provider.search(term, options)+ : ((await provider.browse?.(options)) ?? [])+ if (current !== generation) return+ show(found, next, found.length === PHOTOS_PER_PAGE)+ if (!term) {+ picks = { service: service.value, photos: photos.value, page, hasMore: hasMore.value }+ }+ } catch {+ if (current !== generation) return+ failed.value = true+ hasMore.value = false+ } finally {+ if (current === generation) loading.value = false+ }+ }++ // Another service's photos must not stay pickable while the new search waits out the+ // debounce: they would be placed and reported as the new service's.+ watch(service, () => {+ generation+++ photos.value = []+ hasMore.value = false+ failed.value = false+ })+ // Placeholders show from the first keystroke, not only once the search goes out.+ watch([query, service], () => {+ if (hasKey.value) loading.value = true+ })+ watchDebounced([query, service, hasKey], () => void load(1), { debounce: SEARCH_DEBOUNCE_MS })++ /**+ * Readies the picker as it opens: on the service last searched, or on one with a key when that+ * one has none, showing its picks unless photos are already listed.+ */+ function open() {+ if (!hasKey.value) {+ const configured = PHOTO_SERVICES.find((item) => photoServiceHasKey(item.id))+ if (configured) service.value = configured.id+ }+ if (photos.value.length === 0 && !loading.value) void load(1)+ }++ function loadMore() {+ if (!loading.value && hasMore.value) void load(page + 1)+ }++ function find(id: string) {+ return photos.value.find((photo) => photo.sourceId === id)+ }++ return { query, service, photos, loading, failed, hasMore, hasKey, open, loadMore, find }+}diff --git a/src/app/settings/credentials/media.ts b/src/app/settings/credentials/media.tsindex d624d2dd0..4cf4e8e03 100644--- a/src/app/settings/credentials/media.ts+++ b/src/app/settings/credentials/media.ts@@ -1,6 +1,11 @@import { ref } from 'vue'-import { setPexelsAPIKey, setUnsplashAccessKey } from '@open-pencil/core/tools'+import {+ checkStockPhotoKey,+ setPexelsAPIKey,+ setUnsplashAccessKey,+ type StockPhotoKeyCheck+} from '@open-pencil/core/tools'import { appCredentialServices } from './app'import {@@ -58,6 +63,19 @@ export async function setUnsplashKey(key: string): Promise<void> {: null)}+/**+ * Checks the key typed in Settings, or the saved one when nothing is typed, with one request to+ * the service; `missing` when there is neither.+ */+export async function checkMediaKey(+ service: 'pexels' | 'unsplash',+ typed: string,+ useSaved: boolean+): Promise<StockPhotoKeyCheck | 'missing'> {+ const reference = service === 'pexels' ? PEXELS_CREDENTIAL : UNSPLASH_CREDENTIAL+ const key = typed.trim() || (useSaved ? await resolveMediaCredential(reference) : null)+ return key ? checkStockPhotoKey(service, key) : 'missing'+}export async function setRememberCredentials(remembered: boolean): Promise<void> {await initializeCredentialMigration()await setAppCredentialPersistence(remembered)diff --git a/src/app/settings/media/use.ts b/src/app/settings/media/use.tsindex 0ec6e0cc3..eaf32235e 100644--- a/src/app/settings/media/use.ts+++ b/src/app/settings/media/use.ts@@ -1,9 +1,12 @@import { tryOnScopeDispose } from '@vueuse/core'import { computed, ref, watch } from 'vue'+import type { StockPhotoKeyCheck } from '@open-pencil/core/tools'+import { vectorizeProviderID } from '@/app/editor/vectorize'import { useVectorizeSettings } from '@/app/editor/vectorize/settings/use'import {+ checkMediaKey,pexelsKeyStatus,setPexelsKey,unsplashKeyStatus,@@ -24,12 +27,17 @@ export function useMediaSettingsEditor(service: MediaSettingsService, services =const removeKey = ref(false)const busy = ref(false)const saveError = ref('')+ const keyCheck = ref<StockPhotoKeyCheck | 'missing' | 'checking' | null>(null)const vector = service === 'vectorize' ? useVectorizeSettings(key, providerID) : nulllet disposed = falsetryOnScopeDispose(() => {disposed = truekey.value = ''})+ // A result says nothing about a key typed since.+ watch(key, () => {+ if (keyCheck.value !== 'checking') keyCheck.value = null+ })watch(providerID,() => {@@ -53,6 +61,15 @@ export function useMediaSettingsEditor(service: MediaSettingsService, services =if (busy.value) returnkey.value = ''removeKey.value = true+ keyCheck.value = null+ }++ /** Tries the key typed, or the saved one, against the service; stock photo services only. */+ async function checkKey() {+ if (service === 'vectorize' || keyCheck.value === 'checking') return+ keyCheck.value = 'checking'+ const result = await checkMediaKey(service, key.value, !removeKey.value)+ if (!isDisposed()) keyCheck.value = result}function isDisposed() {@@ -83,5 +100,17 @@ export function useMediaSettingsEditor(service: MediaSettingsService, services =}}- return { key, providerID, vector, keyStatus, error, dirty, busy, clearCredential, save }+ return {+ key,+ providerID,+ vector,+ keyStatus,+ keyCheck,+ error,+ dirty,+ busy,+ clearCredential,+ checkKey,+ save+ }}diff --git a/src/app/shell/external-links.ts b/src/app/shell/external-links.tsnew file mode 100644index 000000000..70aaf68af--- /dev/null+++ b/src/app/shell/external-links.ts@@ -0,0 +1,37 @@+import { useEventListener } from '@vueuse/core'++import { isTauri } from '@/app/tauri/env'++import { openExternalLink } from './ui'++/**+ * Opens links meant for a new tab, `<a target="_blank">`, in the system browser on the desktop,+ * after the link's own handlers. The shell plugin's handler on `<body>` would open them with+ * `shell:allow-open`, which the app does not grant, even when the link handles its click itself,+ * as a chat link does to ask first; such a link opens with `window.open`, which the desktop shell+ * sends to the browser (`open_new_window_externally` in `desktop/src/system/opener.rs`).+ */+export function useExternalLinks() {+ if (!isTauri()) return+ useEventListener(+ document,+ 'click',+ (event: MouseEvent) => {+ if (!(event.target instanceof Element)) return+ const anchor = event.target.closest('a[href]')+ if (!(anchor instanceof HTMLAnchorElement) || anchor.target !== '_blank') return+ // Added while the click is captured, it runs after the link's own handlers in this click.+ anchor.addEventListener(+ 'click',+ (click) => {+ click.stopPropagation()+ if (click.defaultPrevented) return+ click.preventDefault()+ void openExternalLink(anchor.href)+ },+ { once: true }+ )+ },+ { capture: true }+ )+}diff --git a/src/app/shell/menu/actions/editor.ts b/src/app/shell/menu/actions/editor.tsindex 6694166ae..a116fd955 100644--- a/src/app/shell/menu/actions/editor.ts+++ b/src/app/shell/menu/actions/editor.ts@@ -86,6 +86,9 @@ export function createSharedEditorMenuActions(store.state.showUI = !store.state.showUI},'toggle-preview': () => store.togglePlay(),+ 'insert-icon': () => {+ store.state.iconPickerOpen = true+ },'theme-light': () => setTheme('light'),'theme-dark': () => setTheme('dark'),'theme-auto': () => setTheme('auto'),diff --git a/src/app/shell/menu/app-menu.ts b/src/app/shell/menu/app-menu.tsindex ccecdd716..bae3e8f44 100644--- a/src/app/shell/menu/app-menu.ts+++ b/src/app/shell/menu/app-menu.ts@@ -199,9 +199,6 @@ export function useAppMenu() {settings: openSettingsDialog,diagnostics: () => openSettingsDialog('diagnostics'),variables: () => openVariablesDialog(store),- 'insert-icon': () => {- store.state.iconPickerOpen = true- },'export-png': () => exportSelection('png'),'export-svg': () => exportSelection('svg'),'export-pptx': () => exportSelection('pptx'),diff --git a/src/components/chat/ChatPanel.vue b/src/components/chat/ChatPanel.vueindex 385657716..1bfd323c0 100644--- a/src/components/chat/ChatPanel.vue+++ b/src/components/chat/ChatPanel.vue@@ -5,7 +5,7 @@ import { computed, shallowRef, useTemplateRef, watch } from 'vue'import { useI18n } from '@open-pencil/vue/i18n'-import { revokeImagePreviewURL } from '@/app/ai/attachment/image/prepare'+import { isAttachableImageFile, revokeImagePreviewURL } from '@/app/ai/attachment/image/prepare'import { chatDocumentId } from '@/app/ai/chat/history/document'import {clearQueuedMessages,@@ -34,7 +34,7 @@ import ChatPermissionDialog from '@/components/chat/ChatPermissionDialog.vue'import ChatProviderSetup from '@/components/chat/ChatProviderSetup.vue'import ChatRunLocation from '@/components/chat/ChatRunLocation.vue'import ChatTranscript from '@/components/chat/ChatTranscript.vue'-import { useImageDrop } from '@/components/chat/input/useImageDrop'+import { useImageDrop } from '@/components/ui/drop/useImageDrop'const { isConfigured, ensureChat, history, chatFailure, clearChatFailure, providerID } = useAIChat()const { ai } = useI18n()@@ -75,6 +75,7 @@ const panel = useTemplateRef<HTMLElement>('panel')// Images dropped anywhere on the chat go to the composer, when there is one to take them.const { dragging: draggingImages } = useImageDrop(panel, {enabled: () => chatInput.value !== null,+ accepts: isAttachableImageFile,onImages: (files) => chatInput.value?.dropFiles(files)})let viewGeneration = 0diff --git a/src/components/fill-picker/ImageFillPicker.vue b/src/components/fill-picker/ImageFillPicker.vueindex 3a76227ba..975afa43a 100644--- a/src/components/fill-picker/ImageFillPicker.vue+++ b/src/components/fill-picker/ImageFillPicker.vue@@ -1,15 +1,21 @@<script setup lang="ts">import { useFileDialog } from '@vueuse/core'-import { computed } from 'vue'+import { computed, useTemplateRef } from 'vue'+import type { StockPhotoResult } from '@open-pencil/core/tools'import type { Fill, ImageScaleMode } from '@open-pencil/scene-graph'import { coverImageTransform } from '@open-pencil/scene-graph/images'import { useI18n } from '@open-pencil/vue/i18n'import { useEditorStore } from '@/app/editor/active-store'+import { downloadPhoto } from '@/app/editor/photos/download'+import type { PhotoService } from '@/app/editor/photos/search'+import { toast } from '@/app/shell/ui'import NumberField from '@/components/inputs/NumberField.vue'+import PhotoPicker from '@/components/photo-picker/PhotoPicker.vue'import AppButton from '@/components/ui/button/AppButton.vue'import IconButton from '@/components/ui/button/IconButton.vue'+import { useImageDrop } from '@/components/ui/drop/useImageDrop'import AppSelect from '@/components/ui/select/AppSelect.vue'import { useImageFill } from './useImageFill'@@ -35,15 +41,14 @@ const { url: imagePreviewURL, size: imageSize } = useImageFill(() => fill.imageHmeasure: true})+const IMAGE_TYPES = ['image/png', 'image/jpeg', 'image/webp']+const { open: pickImage, onChange: onFileChange } = useFileDialog({- accept: 'image/png,image/jpeg,image/webp',+ accept: IMAGE_TYPES.join(','),multiple: false})-onFileChange(async (files) => {- const file = files?.[0]- if (!file) return- const bytes = new Uint8Array(await file.arrayBuffer())+function fillWith(bytes: Uint8Array) {const hash = store.storeImage(bytes)emit('update', {...fill,@@ -51,8 +56,34 @@ onFileChange(async (files) => {imageHash: hash,imageScaleMode: fill.imageScaleMode ?? 'FILL'})+}++async function fillWithFile(file: File) {+ fillWith(new Uint8Array(await file.arrayBuffer()))+}++onFileChange((files) => {+ const file = files?.[0]+ if (file) void fillWithFile(file)})+// An image dropped on the well fills as one chosen with the button does; with several, the first.+const well = useTemplateRef<HTMLElement>('well')+const { dragging } = useImageDrop(well, {+ accepts: (file) => IMAGE_TYPES.includes(file.type),+ onImages: ([file]) => {+ if (file) void fillWithFile(file)+ }+})++async function fillWithPhoto(photo: StockPhotoResult, service: PhotoService) {+ try {+ fillWith((await downloadPhoto(service, photo)).bytes)+ } catch {+ toast.error(panels.value.insertPhotoFailed)+ }+}+/*** Figma keeps a crop through other modes, which ignore it, but a new crop starts over from the* Fill framing; without the layer's or image's size the renderer frames it as Fill does.@@ -86,21 +117,51 @@ function rotate() {<template><div class="space-y-2">+ <!--+ As Figma's image fill: the image, with its actions in the middle. With no image they show at+ once; over an image they show on hover or when the keyboard reaches them.+ --><div- v-if="imagePreviewURL"- class="flex h-24 items-center justify-center overflow-hidden rounded border border-border"+ ref="well"+ class="group relative flex h-28 items-center justify-center overflow-hidden rounded border border-border bg-panel-secondary data-[dragging]:border-accent"+ :data-empty="imagePreviewURL ? undefined : ''"+ :data-dragging="dragging ? '' : undefined"+ data-test-id="fill-picker-image-well">- <img :src="imagePreviewURL" class="max-h-full max-w-full object-contain" />+ <img+ v-if="imagePreviewURL"+ :src="imagePreviewURL"+ alt=""+ class="max-h-full max-w-full object-contain"+ />+ <div+ class="absolute inset-0 flex flex-col items-center justify-center gap-1.5 bg-black/45 opacity-0 transition-opacity group-hover:opacity-100 group-data-[empty]:bg-transparent group-data-[empty]:opacity-100 has-[:focus-visible]:opacity-100 motion-reduce:transition-none"+ >+ <AppButton+ size="sm"+ variant="outline"+ class="w-32 bg-panel"+ data-test-id="fill-picker-choose-image"+ @click="pickImage()"+ >+ <template #leading><icon-lucide-upload class="size-3" /></template>+ {{ fill.imageHash ? 'Replace' : 'Choose image' }}+ </AppButton>+ <PhotoPicker :heading="panels.stockPhoto" @select="fillWithPhoto">+ <template #trigger>+ <AppButton+ size="sm"+ variant="outline"+ class="w-32 bg-panel"+ data-test-id="fill-picker-stock-photo"+ >+ <template #leading><icon-lucide-image-plus class="size-3" /></template>+ {{ panels.stockPhoto }}+ </AppButton>+ </template>+ </PhotoPicker>+ </div></div>- <AppButton- variant="outline"- class="w-full"- data-test-id="fill-picker-choose-image"- @click="pickImage()"- >- <template #leading><icon-lucide-image class="size-3" /></template>- {{ fill.imageHash ? 'Replace' : 'Choose image' }}- </AppButton><div class="flex items-center gap-1.5"><AppSelect:ui="{ trigger: 'min-w-0 flex-1' }"diff --git a/src/components/icon-picker/IconPicker.vue b/src/components/icon-picker/IconPicker.vueindex 97bd9bab6..8c8eb477e 100644--- a/src/components/icon-picker/IconPicker.vue+++ b/src/components/icon-picker/IconPicker.vue@@ -174,9 +174,12 @@ function pick(name: string) {@select="pick"@load-more="loadMore">- <template #trigger>+ <template v-if="$slots.trigger" #trigger><slot name="trigger" /></template>+ <template v-else #anchor>+ <slot name="anchor" />+ </template><template #search-trailing><AppComboboxv-model="chosenSet"diff --git a/src/components/icon-picker/InsertIconButton.vue b/src/components/icon-picker/InsertIconButton.vueindex b1fae4f4d..1caa32852 100644--- a/src/components/icon-picker/InsertIconButton.vue+++ b/src/components/icon-picker/InsertIconButton.vue@@ -10,8 +10,15 @@ import type { ToolbarUI } from '@/components/toolbar/types'import IconPicker from './IconPicker.vue'-/** The toolbar's icon picker, also opened by the Insert Icon command. */-const { ui, mobile = false } = defineProps<{ ui?: ToolbarUI; mobile?: boolean }>()+/**+ * The toolbar's icon picker, also opened by the Insert Icon command. `anchored` mounts it without+ * its button, over the toolbar, while the button is hidden from it.+ */+const {+ ui,+ mobile = false,+ anchored = false+} = defineProps<{ ui?: ToolbarUI; mobile?: boolean; anchored?: boolean }>()const store = useEditorStore()const panels = usePanelMessages()@@ -29,7 +36,10 @@ function insert(name: string) {align="center"@select="insert">- <template #trigger>+ <template v-if="anchored" #anchor>+ <span aria-hidden="true" class="pointer-events-none absolute inset-x-0 top-0" />+ </template>+ <template v-else #trigger><ToolButton:icon="IconSmilePlus":label="panels.insertIcon"diff --git a/src/components/links/ExternalLink.vue b/src/components/links/ExternalLink.vueindex d523744b1..063555d7c 100644--- a/src/components/links/ExternalLink.vue+++ b/src/components/links/ExternalLink.vue@@ -2,9 +2,7 @@import { tv } from 'tailwind-variants'import { computed } from 'vue'-import { openExternalLink } from '@/app/shell/ui'import type { ComponentUI } from '@/components/ui/types'-import { IS_TAURI } from '@/constants'import linkTheme from '@/theme/link'const { href, ui } = defineProps<{@@ -20,16 +18,12 @@ const styles = computed(() => {}})-/** Desktop WebViews cannot open external pages themselves, so route them to the system browser. */-function navigate(event: MouseEvent) {- if (!IS_TAURI) return- event.preventDefault()- void openExternalLink(href)-}+// On the desktop the shell opens the link in the system browser, as it does every link that opens+// a new tab (`useExternalLinks`).</script><template>- <a :href="href" target="_blank" rel="noopener noreferrer" :class="styles.base" @click="navigate">+ <a :href="href" target="_blank" rel="noopener noreferrer" :class="styles.base"><slot /><icon-lucide-external-link :class="styles.icon" aria-hidden="true" /></a>diff --git a/src/components/photo-picker/PhotoPicker.vue b/src/components/photo-picker/PhotoPicker.vuenew file mode 100644index 000000000..e29806b54--- /dev/null+++ b/src/components/photo-picker/PhotoPicker.vue@@ -0,0 +1,156 @@+<script setup lang="ts">+import { computed, watch } from 'vue'++import type { StockPhotoResult } from '@open-pencil/core/tools'+import { useCommonMessages, usePanelMessages } from '@open-pencil/vue/i18n'++import { PHOTO_SERVICES, usePhotoSearch, type PhotoService } from '@/app/editor/photos/search'+import { refreshMediaCredentials } from '@/app/settings/credentials/media'+import { openSettingsDialog } from '@/app/settings/dialog'+import SettingsLink from '@/components/settings/layout/SettingsLink.vue'+import AppButton from '@/components/ui/button/AppButton.vue'+import AppPlaceholder from '@/components/ui/feedback/AppPlaceholder.vue'+import AppPicker from '@/components/ui/select/AppPicker.vue'+import type { AppPickerItem } from '@/components/ui/select/AppPicker.vue'+import AppSelect from '@/components/ui/select/AppSelect.vue'++/**+ * Searches Unsplash or Pexels and hands back the photo picked, crediting each as the services+ * ask. Without the chosen service's key it asks for one in place of the results.+ */+const {+ heading,+ tooltip,+ side = 'left',+ align = 'start'+} = defineProps<{+ heading: string+ tooltip?: string+ side?: 'left' | 'right' | 'top' | 'bottom'+ align?: 'start' | 'center' | 'end'+}>()+const emit = defineEmits<{+ select: [photo: StockPhotoResult, service: PhotoService, serviceName: string]+}>()+const open = defineModel<boolean>('open', { default: false })++const panels = usePanelMessages()+const common = useCommonMessages()+const search = usePhotoSearch()+const { query, service, photos, loading, failed, hasMore, hasKey } = search++// The keys may have changed elsewhere, such as in Settings, since the picker last opened.+watch(open, async (isOpen) => {+ if (!isOpen) return+ await refreshMediaCredentials()+ search.open()+})++const serviceInfo = computed(() => PHOTO_SERVICES.find((item) => item.id === service.value))+const serviceName = computed(() => serviceInfo.value?.name ?? service.value)+const serviceOptions = PHOTO_SERVICES.map((item) => ({ value: item.id, label: item.name }))++function credit(photo: StockPhotoResult) {+ return panels.value.photoCredit({ photographer: photo.photographer, service: serviceName.value })+}+const items = computed<AppPickerItem[]>(() =>+ photos.value.map((photo) => ({ value: photo.sourceId, label: credit(photo) }))+)++const emptyLabel = computed(() => {+ if (failed.value) return panels.value.photoSearchFailed({ service: serviceName.value })+ if (loading.value) return panels.value.searchingIcons+ return query.value.trim()+ ? panels.value.noPhotosFound+ : panels.value.photoSearchHint({ service: serviceName.value })+})++/** The keys are set where every service's are, in Settings, with room to read and paste. */+function openKeySettings() {+ open.value = false+ openSettingsDialog('services')+}++/** Both services ask for the credit to link to the photographer's page with the service. */+function photographerURL(id: string) {+ return search.find(id)?.photographerURL ?? serviceInfo.value?.siteURL ?? ''+}++function pick(id: string) {+ const photo = search.find(id)+ if (photo) emit('select', photo, service.value, serviceName.value)+}+</script>++<template>+ <AppPicker+ v-model:open="open"+ v-model:query="query"+ search="remote"+ layout="gallery"+ :ui="hasKey ? undefined : { content: 'h-auto' }"+ :has-more="hasMore"+ :loading="loading"+ :heading="heading"+ :items="items"+ :tooltip="tooltip"+ :side="side"+ :align="align"+ :search-placeholder="panels.searchPhotos"+ :empty-label="emptyLabel"+ :close-label="common.close"+ @select="pick"+ @load-more="search.loadMore"+ >+ <template v-if="$slots.trigger" #trigger>+ <slot name="trigger" />+ </template>+ <template v-else #anchor>+ <slot name="anchor" />+ </template>+ <template #actions>+ <AppSelect+ v-model="service"+ :options="serviceOptions"+ :label="panels.photoService"+ :ui="{+ trigger: 'h-6 w-auto shrink-0 border-0 bg-transparent px-1.5 hover:bg-hover',+ value: 'text-muted'+ }"+ />+ </template>+ <template v-if="!hasKey" #setup>+ <AppPlaceholder+ :label="panels.photoKeyHeading({ service: serviceName })"+ :description="panels.photoKeyDescription({ service: serviceName })"+ data-test-id="photo-picker-key-needed"+ >+ <template #icon><icon-lucide-key-round class="size-5" /></template>+ <template #action>+ <AppButton color="primary" variant="solid" @click="openKeySettings">{{+ panels.photoKeyAction+ }}</AppButton>+ </template>+ </AppPlaceholder>+ </template>+ <template #leading="{ item: entry }">+ <img+ :src="search.find(entry.value)?.thumbnailURL"+ alt=""+ loading="lazy"+ draggable="false"+ class="size-full rounded object-cover"+ />+ </template>+ <template v-if="hasKey" #footer="{ highlighted }">+ <p class="flex h-5 items-center gap-1 truncate px-1 text-[11px] text-muted">+ <SettingsLink v-if="highlighted" :href="photographerURL(highlighted.value)">{{+ highlighted.label+ }}</SettingsLink>+ <SettingsLink v-else-if="serviceInfo" :href="serviceInfo.siteURL">{{+ serviceName+ }}</SettingsLink>+ </p>+ </template>+ </AppPicker>+</template>diff --git a/src/components/settings/media/MediaCredentialEditor.vue b/src/components/settings/media/MediaCredentialEditor.vueindex 00c82e92c..17bb07386 100644--- a/src/components/settings/media/MediaCredentialEditor.vue+++ b/src/components/settings/media/MediaCredentialEditor.vue@@ -2,6 +2,7 @@import { computed } from 'vue'import {+ useAIMessages,useCommonMessages,useCredentialMessages,useMediaMessages,@@ -12,6 +13,7 @@ import { useMediaSettingsEditor, type MediaSettingsService } from '@/app/settingimport { useSettingsFormGuard } from '@/app/settings/navigation/use'import SettingsPage from '@/components/settings/layout/SettingsPage.vue'import SettingsSaveFeedback from '@/components/settings/layout/SettingsSaveFeedback.vue'+import ProviderConnectionTestButton from '@/components/settings/provider/ProviderConnectionTestButton.vue'import ProviderSettingsField from '@/components/settings/provider/ProviderSettingsField.vue'import ProviderSettingsKeyField from '@/components/settings/provider/ProviderSettingsKeyField.vue'import AppButton from '@/components/ui/button/AppButton.vue'@@ -20,7 +22,9 @@ import AppSelect from '@/components/ui/select/AppSelect.vue'const { service } = defineProps<{ service: MediaSettingsService }>()const emit = defineEmits<{ done: [] }>()const editor = useMediaSettingsEditor(service)-const { key, providerID, keyStatus, error, dirty, busy, clearCredential } = editor+const { key, providerID, keyStatus, keyCheck, error, dirty, busy, clearCredential, checkKey } =+ editor+const ai = useAIMessages()const common = useCommonMessages()const credentials = useCredentialMessages()const media = useMediaMessages()@@ -49,6 +53,32 @@ const placeholder = computed(() => {if (keyStatus.value === 'configured') return credentials.value.savedReplacereturn provider.value?.keyPlaceholder ?? ''})+const keyCheckStatus = computed(() => {+ if (keyCheck.value === null) return 'idle'+ if (keyCheck.value === 'checking') return 'testing'+ return keyCheck.value === 'ok' ? 'success' : 'error'+})+const keyCheckMessage = computed(() => {+ const service = title.value+ switch (keyCheck.value) {+ case 'ok':+ return media.value.photoKeyWorks({ service })+ case 'missing':+ return ai.value.connectionTestMissingAPIKey+ case 'rejected':+ return service === 'Unsplash'+ ? media.value.unsplashKeyRejected+ : media.value.photoKeyRejected({ service })+ case 'rate-limited':+ return media.value.photoKeyRateLimited({ service })+ case 'network':+ return media.value.photoKeyUnreachable({ service })+ case 'failed':+ return media.value.photoKeyCheckFailed({ service })+ default:+ return undefined+ }+})async function save() {if (await editor.save()) emit('done')}@@ -87,6 +117,13 @@ async function save() {:key-u-r-l-label="credentials.getAPIKey"@clear="clearCredential"/>+ <ProviderConnectionTestButton+ v-if="service !== 'vectorize'"+ :status="keyCheckStatus"+ :message="keyCheckMessage"+ :disabled="busy"+ @test="checkKey"+ /></fieldset><SettingsSaveFeedback :error="error" /></div>diff --git a/src/components/settings/provider/ProviderConnectionTestButton.vue b/src/components/settings/provider/ProviderConnectionTestButton.vueindex e4c03da3b..0e16de022 100644--- a/src/components/settings/provider/ProviderConnectionTestButton.vue+++ b/src/components/settings/provider/ProviderConnectionTestButton.vue@@ -11,16 +11,24 @@ import statusTheme from '@/theme/feedback/status'interface ProviderConnectionTestButtonProps {status: 'idle' | 'testing' | 'success' | 'error'reason?: ProviderConnectionTestFailureReason | null+ /** The result in place of the model messages, for services that are not models. */+ message?: stringdisabled?: boolean}-const { status, reason, disabled = false } = defineProps<ProviderConnectionTestButtonProps>()+const {+ status,+ reason,+ message,+ disabled = false+} = defineProps<ProviderConnectionTestButtonProps>()const emit = defineEmits<{ test: [] }>()const { ai, common } = useI18n()const resultMessage = computed(() => {+ if (status !== 'success' && status !== 'error') return null+ if (message) return messageif (status === 'success') return ai.value.connectionTestSuccess- if (status !== 'error') return nullswitch (reason) {case 'missing-api-key':diff --git a/src/components/shell/AppShell.vue b/src/components/shell/AppShell.vueindex 96165f6c8..1ab411a43 100644--- a/src/components/shell/AppShell.vue+++ b/src/components/shell/AppShell.vue@@ -1,7 +1,9 @@<script setup lang="ts">+import { useExternalLinks } from '@/app/shell/external-links'import { useShellMenu } from '@/app/shell/menu/use'useShellMenu()+useExternalLinks()</script><template>diff --git a/src/components/toolbar/DesktopToolbar.vue b/src/components/toolbar/DesktopToolbar.vueindex 7765c791a..035a2ffc1 100644--- a/src/components/toolbar/DesktopToolbar.vue+++ b/src/components/toolbar/DesktopToolbar.vue@@ -40,6 +40,8 @@ function selectedTool(tool: EditorToolDef) {defineSlots<{/** A button that runs a command, such as placing an icon, rather than picking a tool. */action(props: { action: ToolbarAction }): unknown+ /** Pickers whose buttons are hidden, anchored to the toolbar's top edge. */+ hidden(): unknown}>()</script>@@ -89,5 +91,6 @@ defineSlots<{</ToolbarItem></template></ToolbarRoot>+ <slot name="hidden" /></div></template>diff --git a/src/components/toolbar/EditorToolbar.vue b/src/components/toolbar/EditorToolbar.vueindex 94fa4b29e..7fde08caa 100644--- a/src/components/toolbar/EditorToolbar.vue+++ b/src/components/toolbar/EditorToolbar.vue@@ -7,7 +7,7 @@ import { useI18n } from '@open-pencil/vue/i18n'import { ToolbarRoot, useToolbarState } from '@open-pencil/vue/primitives/Toolbar'import { useEditorStore } from '@/app/editor/active-store'-import { readOnlyToolbarLayout, toolbarItems } from '@/app/editor/toolbar/layout'+import { readOnlyToolbarLayout, TOOLBAR_ACTIONS, toolbarItems } from '@/app/editor/toolbar/layout'import { toolShortcutLabels } from '@/app/editor/toolbar/shortcuts'import { appPreferences } from '@/app/settings/preferences/store'import { useActionToast } from '@/app/shell/toast/action'@@ -44,6 +44,15 @@ const tools = computed(() =>const actionItems = computed(() =>items.value.flatMap((item) => (item.kind === 'action' ? [item.action] : [])))+/**+ * Commands hidden from the toolbar keep their pickers, which the menu and the palette still open;+ * a read-only document leaves them out, as it does the buttons.+ */+const hiddenActions = computed(() =>+ store.state.readOnly+ ? []+ : TOOLBAR_ACTIONS.filter((action) => !actionItems.value.includes(action))+)const flyoutMenuCls = useMenuUI({ content: 'min-w-32' })const toolbarUI = { flyoutContent: flyoutMenuCls.content }@@ -74,6 +83,11 @@ function onActionTap(item: ToolbarActionItem) {<template #action="{ action }"><InsertIconButton v-if="action === 'insert-icon'" :ui="toolbarUI" /></template>+ <template #hidden>+ <template v-for="action in hiddenActions" :key="action">+ <InsertIconButton v-if="action === 'insert-icon'" anchored />+ </template>+ </template></DesktopToolbar><MobileToolbar@@ -100,6 +114,9 @@ function onActionTap(item: ToolbarActionItem) {<template v-for="action in actionItems" :key="action"><InsertIconButton v-if="action === 'insert-icon'" mobile :ui="toolbarUI" /></template>+ <template v-for="action in hiddenActions" :key="action">+ <InsertIconButton v-if="action === 'insert-icon'" anchored />+ </template></template></MobileToolbar></ToolbarContextMenu>diff --git a/src/components/chat/input/useImageDrop.ts b/src/components/ui/drop/useImageDrop.tssimilarity index 79%rename from src/components/chat/input/useImageDrop.tsrename to src/components/ui/drop/useImageDrop.tsindex 68658e31c..c0f964158 100644--- a/src/components/chat/input/useImageDrop.ts+++ b/src/components/ui/drop/useImageDrop.ts@@ -1,12 +1,10 @@import { useEventListener } from '@vueuse/core'import { shallowRef, toValue, type MaybeRefOrGetter, type Ref } from 'vue'-import { isAttachableImageFile } from '@/app/ai/attachment/image/prepare'-/**- * Takes images dropped anywhere on `target` for the chat. A drag carrying no image, such as a- * `.fig`, is left to the window, which opens documents; the other files of a mixed drop go there- * too, since nothing here stops the event.+ * Takes images dropped anywhere on `target`, keeping the files `accepts` takes. A drag carrying no+ * image, such as a `.fig`, is left to the window, which opens documents; the other files of a+ * mixed drop go there too, since nothing here stops the event.** Whether a drag carries an image is decided once, when it enters. VueUse's `useDropZone` checks* every event and skips its enter/leave count when one fails, which WebKit outside Safari does for@@ -14,7 +12,11 @@ import { isAttachableImageFile } from '@/app/ai/attachment/image/prepare'*/export function useImageDrop(target: Ref<HTMLElement | null>,- options: { enabled: MaybeRefOrGetter<boolean>; onImages: (files: File[]) => void }+ options: {+ enabled?: MaybeRefOrGetter<boolean>+ accepts: (file: File) => boolean+ onImages: (files: File[]) => void+ }) {const dragging = shallowRef(false)// Enter and leave fire for every element the drag crosses inside the target.@@ -34,7 +36,7 @@ export function useImageDrop(useEventListener(target, 'dragenter', (event: DragEvent) => {depth += 1- if (depth === 1) dragging.value = toValue(options.enabled) && carriesImage(event)+ if (depth === 1) dragging.value = (toValue(options.enabled) ?? true) && carriesImage(event)if (dragging.value) event.preventDefault()})useEventListener(target, 'dragover', (event: DragEvent) => {@@ -51,7 +53,7 @@ export function useImageDrop(reset()if (!ours) returnevent.preventDefault()- const images = Array.from(event.dataTransfer?.files ?? []).filter(isAttachableImageFile)+ const images = Array.from(event.dataTransfer?.files ?? []).filter(options.accepts)if (images.length > 0) options.onImages(images)})// No pointer events reach the page during a drag, so the first one means it ended, even whendiff --git a/src/components/ui/select/AppPicker.vue b/src/components/ui/select/AppPicker.vueindex c34382329..d1b9407d2 100644--- a/src/components/ui/select/AppPicker.vue+++ b/src/components/ui/select/AppPicker.vue@@ -28,9 +28,10 @@ export interface AppPickerProps {density?: 'compact' | 'comfortable'/*** `grid` shows each item's thumbnail alone, eight to a row, with the highlighted item's label- * passed to the footer; for browsing many items by sight, such as icons.+ * passed to the footer; for browsing many items by sight, such as icons. `gallery` does the+ * same with larger thumbnails three to a row, for pictures such as photos.*/- layout?: 'list' | 'grid'+ layout?: 'list' | 'grid' | 'gallery'/** More items follow the shown ones; scrolling near the end emits `loadMore`. */hasMore?: boolean/** The items are on their way: placeholders stand in for them, and `emptyLabel` is announced. */@@ -55,9 +56,19 @@ export interface AppPickerSlots {anchor?(): VNode[]/** Thumbnail or icon before an item's label. */leading?(props: { item: AppPickerItem }): VNode[]+ /**+ * Controls in the header before the close button, for a choice the whole picker follows, such+ * as the service it searches; it stays put while the `setup` view replaces the list.+ */+ actions?(): VNode[]/** A control at the end of the search field that narrows the list, such as a category. */'search-trailing'?(): VNode[]trailing?(props: { item: AppPickerItem }): VNode[]+ /**+ * Shown instead of the search and list while the picker needs something before it can list+ * anything, such as a service's key.+ */+ setup?(): VNode[]/** Actions or details below the list; `highlighted` is the item under the pointer or keys. */footer?(props: { close: () => void; highlighted: AppPickerItem | null }): VNode[]}@@ -88,7 +99,7 @@ import { fuzzySearch } from '@open-pencil/vue/shared/search'import IconButton from '@/components/ui/button/IconButton.vue'import Tip from '@/components/ui/overlay/Tip.vue'-import theme, { APP_PICKER_GRID_COLUMNS } from '@/theme/select/picker'+import theme, { APP_PICKER_COLUMNS } from '@/theme/select/picker'const {heading,@@ -145,8 +156,12 @@ function highlight(payload: { value: AcceptableValue } | undefined) {highlighted.value = matches.value.find((item) => item.value === payload?.value) ?? null}-/** Placeholders shown while loading: the grid's visible rows, or a few list rows. */-const LOADING_PLACEHOLDERS = computed(() => (layout === 'grid' ? APP_PICKER_GRID_COLUMNS * 7 : 3))+/** Thumbnails a row in the grid and gallery layouts; null for a list. */+const columns = computed(() => (layout === 'list' ? null : APP_PICKER_COLUMNS[layout]))+/** Placeholders shown while loading: the visible rows of thumbnails, or a few list rows. */+const LOADING_PLACEHOLDERS = computed(+ () => ({ list: 3, grid: APP_PICKER_COLUMNS.grid * 7, gallery: 12 })[layout]+)const ROW_KEYS = new Map([['ArrowDown', 1],@@ -154,16 +169,17 @@ const ROW_KEYS = new Map([])// ListboxRoot is generic, so its instance type is spelled as the part used here.const listbox = useTemplateRef<{ highlightItem: (value: AcceptableValue) => void }>('listboxRoot')-// Reka moves through a listbox one item at a time. The grid lays it out horizontally, so+// Reka moves through a listbox one item at a time. A grid lays it out horizontally, so// left and right move an item, and up and down move a row here; with nothing highlighted, they// start at the first item.function moveRow(event: KeyboardEvent) {const rows = ROW_KEYS.get(event.key)- if (layout !== 'grid' || !rows) return+ const perRow = columns.value+ if (!perRow || !rows) returnevent.preventDefault()const current = highlighted.value?.valueconst index = matches.value.findIndex((item) => item.value === current)- const target = index === -1 ? 0 : index + rows * APP_PICKER_GRID_COLUMNS+ const target = index === -1 ? 0 : index + rows * perRowconst next = matches.value[clamp(target, 0, matches.value.length - 1)]if (next) listbox.value?.highlightItem(next.value)}@@ -212,17 +228,22 @@ function select(value: AcceptableValue) {><div :class="styles.header({ class: ui?.header })"><h3 :class="styles.title({ class: ui?.title })">{{ heading }}</h3>+ <slot name="actions" /><PopoverClose as-child><IconButton :label="closeLabel"><icon-lucide-x class="size-3.5" /></IconButton></PopoverClose></div>+ <div v-if="slots.setup" :class="styles.setup({ class: ui?.setup })">+ <slot name="setup" />+ </div><ListboxRoot+ v-elseref="listboxRoot"class="flex min-h-0 flex-1 flex-col"highlight-on-hover- :orientation="layout === 'grid' ? 'horizontal' : 'vertical'"+ :orientation="columns ? 'horizontal' : 'vertical'"@update:model-value="select"@highlight="highlight"@keydown="moveRow"@@ -270,7 +291,7 @@ function select(value: AcceptableValue) {:value="item.value":disabled="item.disabled":aria-disabled="item.disabled || undefined"- :aria-label="layout === 'grid' ? item.label : undefined"+ :aria-label="columns ? item.label : undefined":data-selected="item.value === selected || undefined":class="styles.item({ class: ui?.item })">diff --git a/src/theme/select/picker.ts b/src/theme/select/picker.tsindex 118c1308e..c55ad86aa 100644--- a/src/theme/select/picker.ts+++ b/src/theme/select/picker.ts@@ -2,8 +2,8 @@ import { motionStyles } from '../motion/styles'import { floatingSurface } from '../overlay'import { panelFieldBase } from '../panel/field/base'-/** Choices per row in the grid layout; keyboard navigation moves this many for a row. */-export const APP_PICKER_GRID_COLUMNS = 8+/** Choices per row in the grid and gallery layouts; keyboard navigation moves this many for a row. */+export const APP_PICKER_COLUMNS = { grid: 8, gallery: 3 } as const/** A searchable list of choices that opens beside the properties panel, as Figma's pickers do. */const appPickerTheme = {@@ -32,6 +32,7 @@ const appPickerTheme = {check: 'size-3 shrink-0 text-primary',empty: 'px-1 py-2 text-[11px] text-muted',placeholder: 'block h-10 rounded bg-hover motion-safe:animate-pulse',+ setup: 'flex min-h-0 flex-1 flex-col gap-3 overflow-y-auto p-3',footer: 'border-t border-border p-1'},variants: {@@ -57,6 +58,19 @@ const appPickerTheme = {leading: 'size-full border-0 bg-transparent text-surface',text: 'sr-only',check: 'hidden'+ },+ /** Larger thumbnails, three to a row, for pictures such as photos. */+ gallery: {+ content: 'h-[28rem] w-96',+ list: 'flex-1',+ empty: 'm-auto max-w-72 text-center',+ group: 'grid grid-cols-3 gap-1',+ groupLabel: 'col-span-full pt-1',+ item: 'aspect-[4/3] justify-center p-0 data-[highlighted]:bg-transparent data-[highlighted]:ring-2 data-[highlighted]:ring-accent',+ placeholder: 'aspect-[4/3] h-auto',+ leading: 'size-full rounded border-0',+ text: 'sr-only',+ check: 'hidden'}}},diff --git a/tests/e2e/design/icons.spec.ts b/tests/e2e/design/icons.spec.tsindex c8b31e310..7c8f1b065 100644--- a/tests/e2e/design/icons.spec.ts+++ b/tests/e2e/design/icons.spec.ts@@ -209,3 +209,29 @@ test('an edited icon says so, asks before a swap discards the edit, and resets oawait section.getByRole('button', { name: 'Detach icon' }).click()await expect(section).toBeHidden()})++test('Object › Insert Icon opens the picker while its button is hidden from the toolbar', async () => {+ const page = ctx.page+ const customizeToolbar = async () => {+ await page.getByTestId('toolbar').click({ button: 'right' })+ await page.getByRole('menuitem', { name: 'Customize toolbar…' }).click()+ return page.getByTestId('settings-toolbar-panel')+ }+ try {+ const settings = await customizeToolbar()+ await settings.getByRole('switch', { name: 'Show Insert icon', exact: true }).click()+ await page.getByTestId('app-settings-done').click()+ await expect(page.getByRole('button', { name: 'Insert icon' })).toHaveCount(0)++ const menu = await openAppMenu(page, 'Object')+ await menu.getByRole('menuitem', { name: 'Insert Icon…' }).click()+ const dialog = page.getByRole('dialog', { name: 'Insert icon' })+ await expect(dialog).toBeVisible()+ await page.keyboard.press('Escape')+ await expect(dialog).toBeHidden()+ } finally {+ const reset = await customizeToolbar()+ await reset.getByRole('button', { name: 'Reset to default' }).click()+ await page.getByTestId('app-settings-done').click()+ }+})diff --git a/tests/e2e/design/photos.spec.ts b/tests/e2e/design/photos.spec.tsnew file mode 100644index 000000000..48cce8a4c--- /dev/null+++ b/tests/e2e/design/photos.spec.ts@@ -0,0 +1,212 @@+import type { Page } from '@playwright/test'+import { toUint8Array } from 'js-base64'++import { expect, test, useEditorSetupWithClear } from '#tests/e2e/fixtures'+import { getSelectedNode } from '#tests/helpers/store'++/** A one-pixel PNG served for every photo, so the workflow needs no network. */+const PNG = Buffer.from(+ toUint8Array(+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII='+ )+)++const ctx = useEditorSetupWithClear()+/**+ * The searches each service answered, `(picks)` for the photos it lists before a search, and the+ * photos Unsplash was told were used.+ */+const requests = { unsplash: [] as string[], pexels: [] as string[], reported: [] as string[] }++function unsplashPhoto(id: string) {+ const url = `https://images.unsplash.test/${id}.png`+ return {+ id,+ width: 1200,+ height: 800,+ urls: { raw: url, full: url, regular: url, small: url, thumb: url },+ user: { name: 'Ann Lee', links: { html: 'https://unsplash.com/@ann' } },+ links: {+ html: `https://unsplash.com/photos/${id}`,+ download_location: `https://api.unsplash.com/photos/${id}/download`+ }+ }+}++test.beforeAll(async () => {+ await ctx.page.route('https://api.unsplash.com/**', async (route) => {+ const url = new URL(route.request().url())+ if (url.pathname === '/search/photos') {+ requests.unsplash.push(url.searchParams.get('query') ?? '')+ await route.fulfill({ json: { results: [unsplashPhoto('first'), unsplashPhoto('second')] } })+ } else if (url.pathname === '/photos') {+ requests.unsplash.push('(picks)')+ await route.fulfill({ json: [unsplashPhoto('editorial')] })+ } else {+ requests.reported.push(url.pathname)+ await route.fulfill({ json: { url: 'https://images.unsplash.test/first.png' } })+ }+ })+ await ctx.page.route('https://api.pexels.com/**', async (route) => {+ const url = new URL(route.request().url())+ requests.pexels.push(url.searchParams.get('query') ?? '(picks)')+ const src = 'https://images.pexels.test/one.png'+ await route.fulfill({+ json: {+ photos: [+ {+ id: 7,+ width: 900,+ height: 600,+ url: 'https://www.pexels.com/photo/7/',+ photographer: 'Jonas Berg',+ photographer_url: 'https://www.pexels.com/@jonas',+ src: { original: src, large2x: src, large: src, medium: src, small: src }+ }+ ]+ }+ })+ })+ await ctx.page.route(/https:\/\/images\.(unsplash|pexels)\.test\//, (route) =>+ route.fulfill({ contentType: 'image/png', body: PNG })+ )+})++test.beforeEach(() => {+ requests.unsplash = []+ requests.pexels = []+ requests.reported = []+})++/** Draws a rectangle, opens its fill as an image, and opens Stock photo. */+async function openPicker(page: Page) {+ await ctx.canvas.drawRect(120, 120, 160, 120)+ await page.getByTestId('fill-picker-swatch').first().click()+ await page.getByTestId('fill-picker-tab-image').click()+ await page.getByTestId('fill-picker-stock-photo').click()+ const dialog = page.getByRole('dialog', { name: 'Stock photo' })+ await expect(dialog).toBeVisible()+ return dialog+}++/**+ * Follows the picker's Open Settings to Settings › Image services, saves `service`'s key there, and comes+ * back to the picker.+ */+async function addKeyInSettings(page: Page, service: 'Unsplash' | 'Pexels', label: string) {+ const picker = page.getByRole('dialog', { name: 'Stock photo' })+ await expect(page.getByTestId('photo-picker-key-needed')).toContainText(`Connect ${service}`)+ await picker.getByRole('button', { name: 'Open Settings' }).click()+ await expect(picker).toBeHidden()+ const media = page.getByTestId('settings-media-panel')+ await media.getByRole('button', { name: new RegExp(service) }).click()+ await page.getByLabel(label).fill(`${service.toLowerCase()}-key`)+ await page.getByRole('button', { name: 'Save', exact: true }).click()+ await page.getByTestId('app-settings-done').click()+ await page.getByTestId('fill-picker-swatch').first().click()+ await page.getByTestId('fill-picker-stock-photo').click()+ await expect(picker).toBeVisible()+ return picker+}++/** The selected layer's image fill, or none. */+async function imageFill(page: Page) {+ const node = await getSelectedNode(page)+ return node?.fills.find((fill) => fill.type === 'IMAGE')+}++test('Stock photo sends a missing key to Settings, then fills the layer with the photo picked', async () => {+ const page = ctx.page+ await openPicker(page)+ const dialog = await addKeyInSettings(page, 'Unsplash', 'Access key')+ // Before a search, Unsplash's editorial feed.+ await expect(dialog.getByRole('option')).toHaveCount(1)++ await dialog.getByRole('textbox', { name: 'Search photos...' }).fill('mountains')+ await expect(dialog.getByRole('option')).toHaveCount(2)+ expect(requests.unsplash).toEqual(['(picks)', 'mountains'])+ await dialog.getByRole('option').first().hover()+ await expect(dialog).toContainText('Photo by Ann Lee on Unsplash')++ await dialog.getByRole('option').first().click()+ await expect(dialog).toBeHidden()+ await expect.poll(async () => (await imageFill(page))?.imageHash).toBeTruthy()+ // Unsplash's API terms ask to be told of every photo used.+ await expect.poll(() => requests.reported).toEqual(['/photos/first/download'])+})++test('switching to a service without a key asks for that one, and its photo fills the layer', async () => {+ const page = ctx.page+ const picker = await openPicker(page)+ await picker.getByRole('combobox', { name: 'Photo service' }).click()+ await page.getByRole('option', { name: 'Pexels' }).click()+ const dialog = await addKeyInSettings(page, 'Pexels', 'API key')+ // Before a search, Pexels' curated photos.+ await expect(dialog.getByRole('option')).toHaveCount(1)++ await dialog.getByRole('textbox', { name: 'Search photos...' }).fill('forest')+ await expect.poll(() => requests.pexels).toEqual(['(picks)', 'forest'])+ await dialog.getByRole('option').first().click()+ await expect.poll(async () => (await imageFill(page))?.imageHash).toBeTruthy()+ expect(requests.reported).toEqual([])+})++test('the picker opens on a service with a key when the last one searched has none', async () => {+ const page = ctx.page+ const picker = await openPicker(page)+ await expect(picker.getByRole('combobox', { name: 'Photo service' })).toHaveText('Pexels')+ await page.keyboard.press('Escape')+ await expect(picker).toBeHidden()++ // Pexels was searched last; its key goes, Unsplash's stays.+ await page.keyboard.press(process.platform === 'darwin' ? 'Meta+,' : 'Control+,')+ await page.getByTestId('settings-section-services').click()+ await page+ .getByTestId('settings-media-panel')+ .getByRole('button', { name: /Pexels/ })+ .click()+ await page.getByTestId('provider-settings-clear-key').click()+ await page.getByRole('button', { name: 'Save', exact: true }).click()+ await page.getByTestId('app-settings-done').click()++ await page.getByTestId('fill-picker-swatch').first().click()+ await page.getByTestId('fill-picker-stock-photo').click()+ await expect(picker.getByRole('combobox', { name: 'Photo service' })).toHaveText('Unsplash')+ await expect(picker.getByRole('option')).toHaveCount(1)+})++test('an image dropped on the image well fills the layer, and other files are left alone', async () => {+ const page = ctx.page+ await ctx.canvas.drawRect(120, 120, 160, 120)+ await page.getByTestId('fill-picker-swatch').first().click()+ await page.getByTestId('fill-picker-tab-image').click()+ const well = page.getByTestId('fill-picker-image-well')++ async function drop(name: string, type: string) {+ return well.evaluate(+ async (target, file) => {+ const canvas = new OffscreenCanvas(8, 8)+ const context = canvas.getContext('2d')+ if (!context) throw new Error('Canvas context unavailable')+ context.fillRect(0, 0, 8, 8)+ const transfer = new DataTransfer()+ transfer.items.add(+ new File([await canvas.convertToBlob({ type: 'image/png' })], file.name, {+ type: file.type+ })+ )+ const options = { bubbles: true, cancelable: true, dataTransfer: transfer }+ target.dispatchEvent(new DragEvent('dragenter', options))+ const accepted = !target.dispatchEvent(new DragEvent('dragover', options))+ target.dispatchEvent(new DragEvent('drop', options))+ return accepted+ },+ { name, type }+ )+ }++ await drop('anim.gif', 'image/gif')+ expect((await imageFill(page))?.imageHash).toBeFalsy()+ expect(await drop('photo.png', 'image/png')).toBe(true)+ await expect.poll(async () => (await imageFill(page))?.imageHash).toBeTruthy()+})diff --git a/tests/e2e/native/cloud-links.spec.ts b/tests/e2e/native/cloud-links.spec.tsindex 4a1667a1f..38a3ff2dc 100644--- a/tests/e2e/native/cloud-links.spec.ts+++ b/tests/e2e/native/cloud-links.spec.ts@@ -33,6 +33,50 @@ describe('native Cloud links', () => {assert.deepEqual(await invokeNative('take_native_test_opened_urls'), [])})+ it('sends a new-tab link to the browser unless the page handles its click', async () => {+ await invokeNative('take_native_test_opened_urls')+ await browser.execute(() => {+ const plain = document.createElement('a')+ plain.href = 'https://example.test/plain'+ plain.target = '_blank'+ plain.dataset.testId = 'native-link-plain'+ plain.textContent = 'plain'+ // Like a chat link, which asks before it opens anything.+ const handled = document.createElement('a')+ handled.href = 'https://example.test/handled'+ handled.target = '_blank'+ handled.dataset.testId = 'native-link-handled'+ handled.textContent = 'handled'+ handled.addEventListener('click', (event) => event.preventDefault())+ document.body.append(plain, handled)+ })+ try {+ // Clicked from the page: the driver's click on a link waits for a page load that the+ // browser, not this window, gets.+ await browser.execute(() => {+ for (const link of document.querySelectorAll<HTMLElement>('[data-test-id^="native-link-"]'))+ link.click()+ })+ // The link opens after the click returns, so it is collected as it arrives.+ const opened: string[] = []+ await browser.waitUntil(+ async () => {+ opened.push(...(await invokeNative<string[]>('take_native_test_opened_urls')))+ return opened.length > 0+ },+ { timeout: 5_000, timeoutMsg: 'The link did not open' }+ )+ assert.deepEqual(opened, ['https://example.test/plain'])+ // The shell plugin's refused open would have shown an error.+ assert.equal(await $('[data-slot="toast"]').isExisting(), false)+ } finally {+ await browser.execute(() => {+ for (const link of document.querySelectorAll('[data-test-id^="native-link-"]'))+ link.remove()+ })+ }+ })+it('opens an invitation link sent to the app', async () => {await invokeNative('native_test_open_deep_link', { url: invitationLink(SECRET) })const dialog = await $('[role="dialog"]')diff --git a/tests/e2e/settings/feedback.spec.ts b/tests/e2e/settings/feedback.spec.tsindex df06e08b4..fd6c21042 100644--- a/tests/e2e/settings/feedback.spec.ts+++ b/tests/e2e/settings/feedback.spec.ts@@ -122,6 +122,34 @@ test('media explains optional keys and preserves input after a failed save', asyawait expect(page.getByRole('button', { name: /Pexels/ })).toBeVisible()})+test('Test connection tries the photo key typed against the service and says what it answered', async ({+ page+}) => {+ await page.route('https://api.unsplash.com/photos?**', (route) =>+ route.request().headers().authorization === 'Client-ID working-key'+ ? route.fulfill({ json: [] })+ : route.fulfill({ status: 401, body: 'OAuth error: The access token is invalid' })+ )+ await openSettings(page)+ await page.getByTestId('settings-section-services').click()+ await page.getByRole('button', { name: /Unsplash/ }).click()+ const test = page.getByRole('button', { name: 'Test connection' })+ const result = page.getByTestId('provider-test-connection-result')++ await test.click()+ await expect(result).toHaveText('Enter an API key before testing.')+ await page.getByLabel('Access key').fill('secret-key')+ await expect(result).toHaveCount(0)+ await test.click()+ await expect(result).toHaveText(+ 'Unsplash refused this key. Paste your app’s Access Key, not its Secret key.'+ )+ await page.getByLabel('Access key').fill('working-key')+ await test.click()+ await expect(result).toHaveText('Unsplash accepted this key.')+ await expect(result).toHaveAttribute('data-tone', 'success')+})+test('MCP requires a token only for enabled bearer connections and preserves failed saves', async ({page}) => {diff --git a/tests/engine/tools/stock-photo/apply.test.ts b/tests/engine/tools/stock-photo/apply.test.tsindex c07855416..452f6e9ba 100644--- a/tests/engine/tools/stock-photo/apply.test.ts+++ b/tests/engine/tools/stock-photo/apply.test.ts@@ -5,18 +5,14 @@ import { SceneGraph, type NodeType } from '@open-pencil/scene-graph'import { copyFills } from '@open-pencil/scene-graph/copy'import { applyPhoto } from '#core/tools/stock-photo/apply'-import type { StockPhotoProvider } from '#core/tools/stock-photo/providers'+import type { StockPhotoProvider, StockPhotoSearchOptions } from '#core/tools/stock-photo/providers'const PNG_BYTES = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])const PHOTO_URL = `data:image/png;base64,${PNG_BYTES.toBase64()}`interface ProviderCall {query: string- options: {- perPage: number- orientation: 'landscape' | 'portrait' | 'square'- targetDim: number- }+ options: StockPhotoSearchOptions}function createProvider(calls: ProviderCall[]): StockPhotoProvider {@@ -27,9 +23,12 @@ function createProvider(calls: ProviderCall[]): StockPhotoProvider {return [{url: PHOTO_URL,+ thumbnailURL: PHOTO_URL,width: 1600,height: 900,photographer: 'Test Photographer',+ photographerURL: 'https://example.com/photographer',+ pageURL: 'https://example.com/photo-1',sourceId: 'photo-1'}]diff --git a/tools/checks/i18n/mixed-script-baseline.txt b/tools/checks/i18n/mixed-script-baseline.txtindex 454da5ff4..998f31c25 100644--- a/tools/checks/i18n/mixed-script-baseline.txt+++ b/tools/checks/i18n/mixed-script-baseline.txt@@ -176,6 +176,7 @@ ja:media.pexelsAlternativeOptionalja:media.stockPhotoToolOptionalja:media.unsplashAccessKeyja:media.vectorizationDescription+ja:media.unsplashKeyRejectedja:menu.copyAsJSXja:menu.copyAsPNGja:menu.copyAsSVG@@ -193,6 +194,7 @@ ja:panels.colorHintHslja:panels.colorHintOkhclja:panels.libraryIdja:panels.localFontsAccessHint+ja:panels.photoKeyDescriptionja:panels.sizingFillFrja:panels.sizingFixedPxja:panels.xAxis@@ -397,6 +399,7 @@ zh-cn:media.pexelsAlternativeOptionalzh-cn:media.stockPhotoToolOptionalzh-cn:media.unsplashAccessKeyzh-cn:media.vectorizationDescription+zh-cn:media.unsplashKeyRejectedzh-cn:menu.copyAsJSXzh-cn:menu.copyAsPNGzh-cn:menu.copyAsSVG@@ -413,6 +416,7 @@ zh-cn:panels.colorHintHslzh-cn:panels.colorHintOkhclzh-cn:panels.libraryIdzh-cn:panels.localFontsAccessHint+zh-cn:panels.photoKeyDescriptionzh-cn:panels.sizingFillFrzh-cn:panels.sizingFixedPxzh-cn:panels.xAxis