Compare commits

..
Author SHA1 Message Date
velzie 57fb5ec606 fix(peer): grant forgery bug and stale comment 2026-11-10 22:13:53 -05:00
182 changed files with 11705 additions and 2162 deletions

No files matched your search

+1 -1
View File
@@ -40,7 +40,7 @@ The following have already been reviewed and determined **not to be vulnerabilit
- **SSRF via `secureFetch`.** Production routes outbound requests through an isolated proxy that has no access to internal/SSRF-sensitive resources.
- **Attacks that depend on guessing an `appInstanceID` or app UID.** These are random 128-bit secret values and are not considered guessable.
- **Apps invoking drivers, creating workers, or using KV.** Applications are intended to do this; worker permissions are scoped to the owning app. This is by design.
- **App metadata or app user-count "leaks".** This information is currently public by design. This covers **private apps** too: private apps are an unreleased, admin-only beta for paid listings in the Puter App Center. Their `index_url` and other metadata are not secret, the flag is not user-settable, and no production app relies on it. Reports that a private app's metadata is reachable through a sibling route (`/get-launch-apps`, `index_url` drift on the hosting gate, etc.) are normalization work, not vulnerabilities.
- **App metadata or app user-count "leaks".** This information is currently public by design. This covers **private apps** too: private apps are an unreleased, admin-only beta for paid listings in the Puter App Center. Their `index_url` and other metadata are not secret, the flag is not user-settable, and no production app relies on it. Reports that a private app's metadata is reachable through a sibling route (taskbar items, `/get-launch-apps`, `index_url` drift on the hosting gate, etc.) are normalization work, not vulnerabilities.
- **Worker hot-reload driven by a share recipient.** Sharing a worker's source file with write access is how you let a collaborator change that worker's code and have it deploy live. The redeploy running as the file owner, with the owner's worker credentials, is the intended behavior of that grant — the owner chose to hand out write access to executable code. If you do not want that, do not share the source file with write access.
- **Re-claiming a site or worker name its owner deleted.** A hosted site or worker name that its owner deletes is treated as abandoned by that owner. If one of their apps still points at it, whoever claims the name next serves that app's `index_url` and receives what the app is launched with, and a new app on the same origin may share the old one's identity. Guarding app identities against being recycled this way is ongoing hardening, not a security boundary, so new ways to re-claim an abandoned name, or to inherit an app's tokens or data through one, are not eligible.
- **Share-mode downgrades that do not cascade.** Demoting a delegate does not retroactively revoke the grants that delegate already issued downstream. Shares are independent grants once issued, not a live-evaluated chain. Revoking the downstream grant is a separate, supported action.
+1 -31
View File
@@ -322,36 +322,6 @@ app reads from the desktop's answer. A call made while the frame shows settles
with it. A frame that is refused, never ready, or `unavailable` resolves
`{ response: false }`, since there's no popup to fall back to.
## Custom domains
`GET /embed/attach-custom-domain` is the custom domain dialog of
`puter.hosting.attach()`, the popup at `/action/attach-custom-domain`, served
like the upgrade: the GUI shell with the same framing rules, redirects and
`no-store`, run only when framed by an allowed page. puter.js frames it on a
signed-in first-party page (the same pages as the pickers).
The frame covers the page with no box or close button, over a transparent GUI
page, so the dialog floats over the host with its own scrim as it does on the
desktop. The frame allows `clipboard-write`, for the dialog's copy buttons, as
well as `otp-credentials`. Escape on the page is left to the dialog, which
doesn't close while a request is in flight. Its fragment names `user` (the
page's signed-in user), `subdomain` (the site to attach a domain to) and
`msg_id`.
The GUI reports `unavailable` unless its session belongs to `user` and the
account has no verification or password change waiting. It then runs the
popup's action unchanged, with the framing page as the requester the dialog
names: it posts `ready` once the dialog is on the page, answers
`{ msg: 'customDomainAttached', domain, original_msg_id }` once the dialog has
closed and its exit has played, and then posts `closed`. `domain` is the domain the user chose, or
null. `attach()` resolves it. A frame that closes without an answer, or a
loading scrim the user dismisses, resolves null.
A call made while the frame shows resolves null without replacing it, as a
second call does on the desktop. A frame that is refused, never ready, or
`unavailable` falls back to the popup, which can sign in, through a consent
dialog when the click has expired.
## Checks
Run the GUI component/browser tests (with the SDK bundle built and Playwright
@@ -359,7 +329,7 @@ Chromium installed), and the backend route tests:
```sh
npx vitest run --config src/gui/vitest.config.js src/gui/src/UI/Dashboard/AppBrowser src/feedbackEmbed
npx vitest run src/puter-js/src/lib/guiEmbed.test.js src/puter-js/src/modules/UI.showFeedbackDialog.test.js src/puter-js/src/modules/Auth.signInFrame.test.js src/puter-js/src/modules/UI.pickerFrame.test.js src/puter-js/src/modules/UI.requestUpgrade.test.js src/puter-js/src/modules/UI.showTopUp.test.js src/puter-js/src/modules/UI.attachCustomDomainFrame.test.js src/puter-js/src/lib/upgradePrompt.test.js src/puter-js/src/modules/UsageLimitDialog.upgrade.test.js
npx vitest run src/puter-js/src/lib/guiEmbed.test.js src/puter-js/src/modules/UI.showFeedbackDialog.test.js src/puter-js/src/modules/Auth.signInFrame.test.js src/puter-js/src/modules/UI.pickerFrame.test.js src/puter-js/src/modules/UI.requestUpgrade.test.js src/puter-js/src/modules/UI.showTopUp.test.js src/puter-js/src/lib/upgradePrompt.test.js src/puter-js/src/modules/UsageLimitDialog.upgrade.test.js
npx vitest run --config src/gui/vitest.config.js src/gui/src/helpers/popupFrame.test.js
npx vitest run --config src/backend/vitest.config.ts src/backend/server.test.ts
```
+10 -40
View File
@@ -257,41 +257,8 @@ describe('whoami extension — handleWhoami', () => {
expect(body.created_ts).toBeGreaterThan(0);
// `directories` is only sent to user actors — confirm it’s present.
expect(body.directories).toBeDefined();
});
it('leaves out taskbar items saved on the account', async () => {
const user = await seedUser();
await server.stores.user.update(user.id as number, {
taskbar_items: JSON.stringify([{ type: 'app', name: 'editor' }]),
});
const { res, captured } = makeRes();
await runWithContext(
{ actor: { user: { uuid: user.uuid, id: user.id as number } } },
() => handleWhoami(makeReq(), res),
);
expect(captured.body).not.toHaveProperty('taskbar_items');
});
it('leaves out a desktop background saved on the account', async () => {
const user = await seedUser();
await server.stores.user.update(user.id as number, {
desktop_bg_url: 'https://cdn.test/wallpaper.png',
desktop_bg_color: '#000000',
desktop_bg_fit: 'cover',
});
const { res, captured } = makeRes();
await runWithContext(
{ actor: { user: { uuid: user.uuid, id: user.id as number } } },
() => handleWhoami(makeReq(), res),
);
const body = captured.body as Record<string, unknown>;
expect(body).not.toHaveProperty('desktop_bg_url');
expect(body).not.toHaveProperty('desktop_bg_color');
expect(body).not.toHaveProperty('desktop_bg_fit');
// taskbar_items is only sent to user actors.
expect(body).toHaveProperty('taskbar_items');
});
it('reports the SMS-to-card fallback only once a send has opened it', async () => {
@@ -355,7 +322,7 @@ describe('whoami extension — handleWhoami', () => {
expect(flags.payment_bypass).toBeUndefined();
});
it('strips created_ts and human_readable_age fields for app actors', async () => {
it('strips desktop_bg_*, created_ts and human_readable_age fields for app actors', async () => {
const user = await seedUser();
const { res, captured } = makeRes();
@@ -373,6 +340,9 @@ describe('whoami extension — handleWhoami', () => {
expect(body.app_name).toBe('app-test-actor');
// is_user_token is stripped for app actors.
expect(body.is_user_token).toBeUndefined();
expect(body.desktop_bg_url).toBeUndefined();
expect(body.desktop_bg_color).toBeUndefined();
expect(body.desktop_bg_fit).toBeUndefined();
expect(body.human_readable_age).toBeUndefined();
// Account age, in either form, is not exposed to apps.
expect(body.created_ts).toBeUndefined();
@@ -462,7 +432,7 @@ describe('whoami extension — handleWhoami', () => {
});
});
it('cannot add directories for an app actor, which core omits', async () => {
it('cannot add taskbar_items for an app actor, which core omits', async () => {
const user = await seedUser();
const body = await whoamiWithListener(
makeActor({
@@ -470,11 +440,11 @@ describe('whoami extension — handleWhoami', () => {
app: { uid: 'app-test-actor' },
}),
(_key, event) => {
event.details.directories = { '/injected': 'uuid' };
event.details.taskbar_items = [{ name: 'injected' }];
},
);
expect(body).not.toHaveProperty('directories');
expect(body).not.toHaveProperty('taskbar_items');
});
});
@@ -555,7 +525,7 @@ describe('whoami extension — handleWhoami', () => {
expect(body.otp_secret).toBeUndefined();
expect(body.signup_ip).toBeUndefined();
// Not just absent as a key — the values must not appear anywhere
// in the payload (nested under metadata, …).
// in the payload (nested under metadata, taskbar items, …).
const serialized = JSON.stringify(body);
expect(serialized).not.toContain('5551234567');
expect(serialized).not.toContain('fp_ABC123');
+16 -2
View File
@@ -1,5 +1,6 @@
import { Context } from '@heyputer/backend/src/core';
import { extension } from '@heyputer/backend/src/extensions';
import { APP_ICON_SIZES } from '@heyputer/backend/src/util/appIcon.js';
import {
buildUserDetails,
scrubSensitive,
@@ -53,10 +54,19 @@ export const handleWhoami = async (
return;
}
const rawIconSize =
typeof req.query?.icon_size === 'string'
? Number(req.query.icon_size)
: undefined;
const iconSize =
rawIconSize !== undefined && APP_ICON_SIZES.includes(rawIconSize)
? rawIconSize
: undefined;
const details = await buildUserDetails(
user,
{ config: extension.config, clients, stores, services },
{ isUser },
{ isUser, iconSize, noIcons: !iconSize },
);
details.human_readable_age = user.timestamp
? timeago.format(new Date(user.timestamp as string))
@@ -71,6 +81,9 @@ export const handleWhoami = async (
delete details.email;
delete details.unconfirmed_email;
}
delete details.desktop_bg_url;
delete details.desktop_bg_color;
delete details.desktop_bg_fit;
delete details.human_readable_age;
delete details.created_ts;
delete details.is_user_token;
@@ -108,7 +121,8 @@ export const handleWhoami = async (
}
const subscription = details.subscription as
{ offering?: Record<string, unknown> } | undefined;
| { offering?: Record<string, unknown> }
| undefined;
if (subscription?.offering) {
delete subscription.offering.group;
delete subscription.offering.benefits;
@@ -52,8 +52,8 @@ const APP_READ_LIMIT = {
/**
* Unauthenticated icon serving; no actor to key on, so the bucket is the
* address — and an address is a NAT, a campus or a carrier gateway that can
* hold hundreds of desktops. Each dashboard load pulls its app icons at once,
* so a single burst from one network is already thousands of requests.
* hold hundreds of desktops. Each desktop boot pulls the taskbar's icons at
* once, so a single burst from one network is already thousands of requests.
* Responses are publicly cacheable and usually a redirect, so the ceiling is
* not protecting bandwidth; it is there so a client looping on a broken icon
* can't spin unbounded.
@@ -523,7 +523,7 @@ export class AppController extends PuterController {
};
// Icons are <img src> targets from the GUI (root) AND resolved via
// api_base_url in app summaries. Register on both so either origin
// api_base_url in taskbar payloads. Register on both so either origin
// works without a cross-subdomain redirect.
router.get(
'/app-icon/:app_uid',
@@ -1271,7 +1271,7 @@ describe('AppController app-icon rate limit', () => {
it('sizes the icon bucket for a whole network rather than one desktop', () => {
// Icons are unauthenticated `<img src>` targets, so the only key is
// the address — which one NAT shares across every desktop behind it,
// and each dashboard load pulls its app icons in a burst.
// and each boot pulls the taskbar's icons in a burst.
for (const path of ['/app-icon/:app_uid', '/app-icon/:app_uid/:size']) {
const route = router.routes.find(
(r) => r.method === 'get' && r.path === path,
@@ -1416,7 +1416,7 @@ describe('AuthController.handleLogin', () => {
is_user_token: true,
});
expect(body.user.directories).toBeTypeOf('object');
expect(body.user).not.toHaveProperty('taskbar_items');
expect(Array.isArray(body.user.taskbar_items)).toBe(true);
});
// A deleted row still answering from cache reaches the session INSERT.
@@ -25,13 +25,18 @@ const ALLOWED_SORT_BY = ['name', 'size', 'modified', 'type'];
const ALLOWED_SORT_ORDER = ['asc', 'desc'];
/**
* Folder view preference routes: layout and sort_by/sort_order, stored on the
* folder's fsentries row.
* Desktop/UI preference routes.
*
* Two categories:
*
* - User-level: desktop background, taskbar items (UserStore)
* - Folder-level: layout, sort_by/sort_order (fsentries table)
*/
/**
* Desktop preference writes — layout, sort order. Each persists on every call,
* and the GUI fires them on direct user action, so a per-minute ceiling well
* above human speed is enough to catch a stuck client.
* Desktop preference writes — background, taskbar, layout, sort order. All four
* persist to the user row on every call, and the GUI fires them on direct user
* action, so a per-minute ceiling well above human speed is enough to catch a
* stuck client.
*/
const PREFERENCE_WRITE_LIMIT = {
scope: 'desktop-preference',
@@ -42,6 +47,89 @@ const PREFERENCE_WRITE_LIMIT = {
export class DesktopController extends PuterController {
registerRoutes(router) {
// -- Desktop background --------------------------------------
router.post(
'/set-desktop-bg',
{
subdomain: 'api',
requireUserActor: true,
allowFullAccessToken: true,
rateLimit: PREFERENCE_WRITE_LIMIT,
},
async (req, res) => {
const { url, color, fit } = req.body ?? {};
const patch = {};
if (url !== undefined) {
if (url !== null && typeof url !== 'string') {
throw new HttpError(
400,
'`url` must be a string or null',
{ legacyCode: 'bad_request' },
);
}
patch.desktop_bg_url = url;
}
if (color !== undefined) {
if (color !== null && typeof color !== 'string') {
throw new HttpError(
400,
'`color` must be a string or null',
{ legacyCode: 'bad_request' },
);
}
patch.desktop_bg_color = color;
}
if (fit !== undefined) {
if (fit !== null && typeof fit !== 'string') {
throw new HttpError(
400,
'`fit` must be a string or null',
{ legacyCode: 'bad_request' },
);
}
patch.desktop_bg_fit = fit;
}
if (Object.keys(patch).length === 0) {
throw new HttpError(400, 'No fields provided', {
legacyCode: 'bad_request',
});
}
await this.stores.user.update(req.actor.user.id, patch);
res.json({});
},
);
// -- Taskbar items -------------------------------------------
router.post(
'/update-taskbar-items',
{
subdomain: 'api',
requireUserActor: true,
allowFullAccessToken: true,
rateLimit: PREFERENCE_WRITE_LIMIT,
},
async (req, res) => {
const { items } = req.body ?? {};
if (!Array.isArray(items)) {
throw new HttpError(
400,
'Missing or invalid `items` array',
{ legacyCode: 'bad_request' },
);
}
await this.stores.user.update(req.actor.user.id, {
taskbar_items: JSON.stringify(items),
});
res.json({});
},
);
// -- Folder layout -------------------------------------------
router.post(
@@ -130,17 +130,147 @@ const callRoute = async (
});
};
describe('DesktopController routes', () => {
it('has no desktop background route', () => {
expect(
router.routes.some((r) => r.path === '/set-desktop-bg'),
).toBe(false);
// ── /set-desktop-bg ─────────────────────────────────────────────────
describe('DesktopController POST /set-desktop-bg', () => {
it('persists url/color/fit on the user row', async () => {
const { actor, userId } = await makeUser();
const { res, captured } = makeRes();
await callRoute(
'post',
'/set-desktop-bg',
makeReq({
body: {
url: 'https://cdn.test/wallpaper.png',
color: '#000000',
fit: 'cover',
},
actor,
}),
res,
);
expect(captured.body).toEqual({});
const refreshed = await server.stores.user.getById(userId);
expect(refreshed?.desktop_bg_url).toBe(
'https://cdn.test/wallpaper.png',
);
expect(refreshed?.desktop_bg_color).toBe('#000000');
expect(refreshed?.desktop_bg_fit).toBe('cover');
});
it('has no taskbar items route', () => {
expect(
router.routes.some((r) => r.path === '/update-taskbar-items'),
).toBe(false);
it('persists only the supplied fields (partial update)', async () => {
const { actor, userId } = await makeUser();
const { res } = makeRes();
await callRoute(
'post',
'/set-desktop-bg',
makeReq({ body: { color: '#ffffff' }, actor }),
res,
);
const refreshed = await server.stores.user.getById(userId);
expect(refreshed?.desktop_bg_color).toBe('#ffffff');
// Untouched fields remain at their column default.
expect(refreshed?.desktop_bg_url).toBeFalsy();
expect(refreshed?.desktop_bg_fit).toBeFalsy();
});
it('passes through `null` to clear a field', async () => {
const { actor, userId } = await makeUser();
// First populate, then clear.
const populate = makeRes();
await callRoute(
'post',
'/set-desktop-bg',
makeReq({
body: { url: 'https://cdn.test/x.png' },
actor,
}),
populate.res,
);
const before = await server.stores.user.getById(userId);
expect(before?.desktop_bg_url).toBe('https://cdn.test/x.png');
const clear = makeRes();
await callRoute(
'post',
'/set-desktop-bg',
makeReq({ body: { url: null }, actor }),
clear.res,
);
const after = await server.stores.user.getById(userId);
expect(after?.desktop_bg_url).toBeNull();
});
it('throws 400 when url is not a string or null', async () => {
const { actor } = await makeUser();
const { res } = makeRes();
await expect(
callRoute(
'post',
'/set-desktop-bg',
makeReq({ body: { url: 123 }, actor }),
res,
),
).rejects.toMatchObject({ statusCode: 400 });
});
it('throws 400 when no fields are provided', async () => {
const { actor } = await makeUser();
const { res } = makeRes();
await expect(
callRoute(
'post',
'/set-desktop-bg',
makeReq({ body: {}, actor }),
res,
),
).rejects.toMatchObject({ statusCode: 400 });
});
});
// ── /update-taskbar-items ───────────────────────────────────────────
describe('DesktopController POST /update-taskbar-items', () => {
it('persists items as a JSON-encoded string', async () => {
const { actor, userId } = await makeUser();
const items = [{ name: 'editor' }, { name: 'browser' }];
const { res } = makeRes();
await callRoute(
'post',
'/update-taskbar-items',
makeReq({ body: { items }, actor }),
res,
);
const refreshed = await server.stores.user.getById(userId);
expect(refreshed?.taskbar_items).toBe(JSON.stringify(items));
});
it('throws 400 when items is missing', async () => {
const { actor } = await makeUser();
const { res } = makeRes();
await expect(
callRoute(
'post',
'/update-taskbar-items',
makeReq({ body: {}, actor }),
res,
),
).rejects.toMatchObject({ statusCode: 400 });
});
it('throws 400 when items is not an array', async () => {
const { actor } = await makeUser();
const { res } = makeRes();
await expect(
callRoute(
'post',
'/update-taskbar-items',
makeReq({ body: { items: 'oops' }, actor }),
res,
),
).rejects.toMatchObject({ statusCode: 400 });
});
});
@@ -5111,8 +5111,9 @@ describe('LegacyFSController.updateFsentryThumbnail', () => {
// ── GET /get-launch-apps ────────────────────────────────────────────
//
// `recent` is a launch-metadata producer: it returns `index_url` for
// apps the user has opened before. The field is served whoever reads it,
// so AppDriver's hosted-backing guard is applied here too.
// apps the user has opened before. The taskbar happens to launch these
// by name (so AppDriver's hosted-backing guard applies), but the field
// is served regardless, so the guard is applied here too.
describe('LegacyFSController GET /get-launch-apps', () => {
const hostedUrl = (sub: string) => `https://${sub}.site.puter.localhost/`;
@@ -401,9 +401,11 @@ export class LegacyFSController extends PuterController {
.filter(Boolean);
// Don't hand out an index_url whose puter-hosted backing is
// gone or reclaimed. This list is a launch-metadata producer
// like any other — a consumer reading index_url straight off
// it shouldn't inherit a stale origin.
// gone or reclaimed. The taskbar launches recents by name (so
// AppDriver's guard applies), but this list is a
// launch-metadata producer like any other — a future consumer
// reading index_url straight off it shouldn't inherit a stale
// origin.
let backingGoneFlags: boolean[];
try {
backingGoneFlags =
@@ -948,7 +950,9 @@ export class LegacyFSController extends PuterController {
// Trash, and `null`/`{}` when restoring. See
// `src/gui/src/helpers.js` → `window.move_items`.
newMetadata: (body.new_metadata ?? undefined) as
Record<string, unknown> | null | undefined,
| Record<string, unknown>
| null
| undefined,
});
const overwrittenEntry = replacedByMove(overwriteTarget, moved, name);
const oldPath = source.path;
@@ -1422,7 +1426,8 @@ export class LegacyFSController extends PuterController {
}
type SignedOrEmpty =
(SignedFile & { path?: string }) | Record<string, never>;
| (SignedFile & { path?: string })
| Record<string, never>;
const result: { signatures: SignedOrEmpty[]; token?: string } = {
signatures: [],
};
@@ -2049,7 +2054,10 @@ export class LegacyFSController extends PuterController {
const subjectRef = body.subject;
const appRef = body.app;
const mode = (getString(body, 'mode') ?? 'read') as
'see' | 'list' | 'read' | 'write';
| 'see'
| 'list'
| 'read'
| 'write';
if (!subjectRef || !appRef)
throw new HttpError(400, '`subject` and `app` are required', {
legacyCode: 'bad_request',
@@ -48,7 +48,6 @@ export const FRAMED_POPUP_ACTIONS = [
'upgrade',
'top-up',
'request-email-confirmation',
'attach-custom-domain',
] as const;
/** Longest description/og:description/twitter:description on `/app/<name>`. */
+20 -13
View File
@@ -24,11 +24,7 @@ import { computeNetworkFingerprint } from '../../core/http/middleware/rateLimit.
import type { PuterRouter } from '../../core/http/PuterRouter.js';
import { PuterController } from '../types.js';
import { PEER_COSTS } from './costs.js';
import {
readClaimedGrantIdentifier,
signGuestGrant,
verifyGuestGrant,
} from './guestGrant.js';
import { signGuestGrant, verifyGuestGrant } from './guestGrant.js';
import {
DEFAULT_FREE_SUBSCRIPTION,
DEFAULT_TEMP_SUBSCRIPTION,
@@ -191,19 +187,30 @@ export class PeerController extends PuterController {
// guests share one bucket and no host can be relayed for by
// more guests per minute than this — the only ceiling on guest
// spend we can apply before the bytes are already spent.
// A grant that doesn't parse can't name a bucket, so those
// requests fall back to the caller's own network.
// The limiter counts a request when it admits it, so only a
// grant that would redeem names a host; otherwise anyone
// holding the host's identifier could drain the bucket and
// lock out every real guest. Anything else - forged, expired,
// malformed, or no secret configured - is charged to the
// caller's own network.
rateLimit: {
scope: 'peer-guest-turn',
limit: 60,
window: 60_000,
key: (req: Request) => {
const claimed = readClaimedGrantIdentifier(
(req.body as { grant?: unknown } | undefined)
?.grant,
);
return claimed
? `host:${claimed}`
const secret =
this.config.peers?.guest_turn?.grant_secret;
const verified = secret
? verifyGuestGrant({
grant: (
req.body as
{ grant?: unknown } | undefined
)?.grant,
secret,
})
: null;
return verified?.status === 'ok'
? `host:${verified.customIdentifier}`
: `net:${computeNetworkFingerprint(req)}`;
},
},
+1 -1
View File
@@ -19,7 +19,7 @@
import { toMicroCents } from '../../services/metering/utils';
// Microcents per byte of TURN egress ($0.05/GB).
// Microcents per byte of TURN egress ($0.10/GB).
export const PEER_COSTS = {
'turn:egress-bytes': toMicroCents(0.1 / 1000 ** 3),
} as const;
@@ -1,7 +1,6 @@
import { createHmac } from 'node:crypto';
import { describe, expect, it } from 'vitest';
import {
readClaimedGrantIdentifier,
signGuestGrant,
verifyGuestGrant,
} from './guestGrant.js';
@@ -243,59 +242,3 @@ describe('signGuestGrant / verifyGuestGrant', () => {
});
});
});
describe('readClaimedGrantIdentifier', () => {
it('reads the identifier from a valid grant', () => {
const { grant } = signGuestGrant({
customIdentifier: USER_ID,
ttlSeconds: 60,
secret: SECRET,
});
expect(readClaimedGrantIdentifier(grant)).toBe(USER_ID);
});
it('reads the claimed identifier without checking the signature', () => {
// Bucketing runs before verification, so this is expected: a forged
// grant still names a bucket, and the handler still rejects it.
const grant = forgeGrant(
{ id: USER_ID, exp: 9_999_999_999, n: 'x' },
{ secret: 'wrong-secret' },
);
expect(readClaimedGrantIdentifier(grant)).toBe(USER_ID);
});
it('reads an expired grant, which the handler then rejects', () => {
const { grant } = signGuestGrant({
customIdentifier: USER_ID,
ttlSeconds: 60,
secret: SECRET,
now: 1_000_000_000_000,
});
expect(readClaimedGrantIdentifier(grant)).toBe(USER_ID);
expect(verifyGuestGrant({ grant, secret: SECRET })).toEqual({
status: 'expired',
});
});
it.each([
['a non-string', 42],
['undefined', undefined],
['a wrong-shaped string', 'not-a-grant'],
['an unknown version', 'pg2.abc.def'],
['an over-long string', `pg1.${'a'.repeat(600)}.sig`],
[
'a non-JSON payload',
`pg1.${Buffer.from('x').toString('base64url')}.sig`,
],
])('returns null for %s', (_label, grant) => {
expect(readClaimedGrantIdentifier(grant)).toBeNull();
});
it('returns null for an identifier of the wrong shape', () => {
const grant = forgeGrant({ id: 'nope', exp: 9_999_999_999 });
expect(readClaimedGrantIdentifier(grant)).toBeNull();
});
});
@@ -171,37 +171,3 @@ export const verifyGuestGrant = ({
expiresAt: payload.exp,
};
};
/**
* Read the claimed identifier out of a grant _without_ verifying it, for
* rate-limit bucketing only.
*
* Bucketing has to happen before the handler runs, and a forged grant is
* rejected there without reaching the upstream API — so an unverified read is
* enough to put a host's guests in one bucket, and the worst a forger achieves
* is choosing which bucket their own rejections land in. Never use this to
* decide attribution.
*
* @returns The claimed identifier, or null if the grant doesn't parse.
*/
export const readClaimedGrantIdentifier = (grant: unknown): string | null => {
if (typeof grant !== 'string' || grant.length > MAX_GRANT_LENGTH) {
return null;
}
const parts = grant.split('.');
if (parts.length !== 3 || parts[0] !== GRANT_VERSION) return null;
try {
const payload = JSON.parse(
Buffer.from(parts[1]!, 'base64url').toString('utf8'),
) as { id?: unknown };
if (
typeof payload?.id !== 'string' ||
!IDENTIFIER_RE.test(payload.id)
) {
return null;
}
return payload.id;
} catch {
return null;
}
};
@@ -224,7 +224,7 @@ const extractToken = (
}
}
// 5. Query string (used by e.g. asset URLs).
// 5. Query string (used by e.g. QR login, asset URLs).
const queryToken = (req.query as { auth_token?: unknown } | undefined)
?.auth_token;
if (typeof queryToken === 'string' && queryToken.length > 0) {
@@ -79,7 +79,6 @@ import type {
} from './types.js';
import { normalize_tools_object } from './utils/FunctionCalling.js';
import {
requestedServiceSpeed,
selectServiceSpeed,
lowerServiceSpeed,
isServiceSpeedUnavailable,
@@ -910,16 +909,18 @@ export class ChatCompletionDriver extends PuterDriver {
attemptProvider: IChatProvider,
baseModel: IChatModel,
) => {
let requestedSpeed = requestedServiceSpeed(
args,
baseModel.provider,
);
const offers =
requestedSpeed !== undefined && requestedSpeed !== 'standard'
args.serviceSpeed !== undefined &&
args.serviceSpeed !== 'standard'
? ((await attemptProvider.serviceSpeedModels?.(
baseModel,
)) ?? {})
: {};
let requestedSpeed =
args.serviceSpeed ??
(baseModel.provider === 'claude' && args.speed === 'fast'
? 'fast'
: undefined);
for (;;) {
const selection = selectServiceSpeed(
baseModel,
@@ -44,9 +44,7 @@ import {
type MockInstance,
} from 'vitest';
import { SYSTEM_ACTOR, type Actor } from '../../../../core/actor.js';
import { v4 as uuidv4 } from 'uuid';
import { ChatCompletionDriver } from '../../ChatCompletionDriver.js';
import { SYSTEM_ACTOR } from '../../../../core/actor.js';
import type { MeteringService } from '../../../../services/metering/MeteringService.js';
import { PuterServer } from '../../../../server.js';
import { setupTestServer } from '../../../../testUtil.js';
@@ -1582,117 +1580,3 @@ describe('OpenAiResponsesChatProvider.complete error mapping', () => {
expect(recordSpy).not.toHaveBeenCalled();
});
});
describe('ChatCompletionDriver OpenAI billing', () => {
const makeBillingUser = async () => {
const user = await server.stores.user.create({
username: `billing-${uuidv4().slice(0, 8)}`,
uuid: uuidv4(),
password: null,
email: null,
free_storage: 1000000,
requires_email_confirmation: false,
});
return { user: { ...user, email_confirmed: true } } as Actor;
};
const makeBillingDriver = async () => {
const driver = new ChatCompletionDriver(
{
providers: {
ollama: { enabled: false },
'openai-completion': { apiKey: 'test-key' },
},
} as never,
server.clients,
server.stores,
server.services,
);
await driver.onServerStart();
return driver;
};
it('meters an empty Responses completion before returning its error', async () => {
const actor = await makeBillingUser();
const driver = await makeBillingDriver();
const before = await server.services.metering.getRemainingUsage(actor);
responsesCreateMock.mockResolvedValueOnce({
status: 'incomplete',
incomplete_details: { reason: 'max_output_tokens' },
output: [],
output_text: '',
usage: {
input_tokens: 1200,
output_tokens: 2000,
output_tokens_details: { reasoning_tokens: 2000 },
},
});
await expect(
withTestActor(
() =>
driver.complete({
model: 'gpt-5.4-mini',
provider: 'openai-responses',
messages: [{ role: 'user', content: 'hello' }],
max_tokens: 1,
fallback: false,
}),
actor,
),
).rejects.toMatchObject({ statusCode: 400 });
expect(responsesCreateMock).toHaveBeenCalledTimes(1);
expect(recordSpy).toHaveBeenCalledTimes(1);
expect(recordSpy.mock.calls[0][0]).toMatchObject({
prompt_tokens: 1200,
completion_tokens: 2000,
});
await Promise.all(recordSpy.mock.results.map((result) => result.value));
expect(
await server.services.metering.getRemainingUsage(actor),
).toBeLessThan(before);
});
it('prices a raw priority tier with the same rate card as fast service', async () => {
const actor = await makeBillingUser();
const driver = await makeBillingDriver();
const charges: number[] = [];
for (const extra of [
{},
{ service_tier: 'priority' },
{ serviceSpeed: 'fast' },
]) {
responsesCreateMock.mockResolvedValueOnce({
output: [],
output_text: 'hi',
service_tier: Object.keys(extra).length
? 'priority'
: 'default',
usage: { input_tokens: 100, output_tokens: 100 },
});
const before =
await server.services.metering.getRemainingUsage(actor);
await withTestActor(
() =>
driver.complete({
model: 'gpt-6.1-terra',
provider: 'openai-responses',
messages: [{ role: 'user', content: 'hello' }],
max_tokens: 100,
fallback: false,
...extra,
} as never),
actor,
);
await Promise.all(
recordSpy.mock.results.map((result) => result.value),
);
charges.push(
before -
(await server.services.metering.getRemainingUsage(actor)),
);
}
expect(responsesCreateMock.mock.calls[1][0].service_tier).toBe(
'priority',
);
expect(charges[0]).toBeGreaterThan(0);
expect(charges[1]).toBe(charges[2]);
expect(charges[2]).toBe(charges[0] * 2);
});
});
@@ -1122,6 +1122,16 @@ export const handle_completion_output_responses_api = async ({
// Inline-compaction artifact, if the upstream compacted this turn.
const compactionItem = output.find((item) => item?.type === 'compaction');
const is_empty = completion.output_text.trim() === '';
if (is_empty && responseToolCalls.length < 1 && !compactionItem) {
// GPT refuses to generate an empty response if you ask it to,
// so this will probably only happen on an error condition.
// A compaction-only output is legitimate, so don't reject it.
throw new HttpError(400, 'an empty response was generated', {
legacyCode: 'bad_response',
});
}
// Reasoning models return `reasoning` output items; their human-readable
// text only exists when the caller requested summaries via
// `reasoning: { summary: ... }` (raw chain-of-thought is never returned).
@@ -1224,14 +1234,6 @@ export const handle_completion_output_responses_api = async ({
if (usageDetails) ret.usageDetails = usageDetails;
}
// Empty output can still include paid reasoning and input tokens.
const isEmpty = completion.output_text.trim() === '';
if (isEmpty && responseToolCalls.length < 1 && !compactionItem) {
throw new HttpError(400, 'an empty response was generated', {
legacyCode: 'bad_response',
});
}
const mod_text = completion.output_text;
if (moderate && mod_text !== null) {
await applyModeration(moderate, mod_text);
@@ -26,7 +26,6 @@ import {
} from './OpenAIUtil.js';
import type { IChatModel, ServiceSpeed } from '../types.js';
import {
requestedServiceSpeed,
selectServiceSpeed,
servedServiceSpeed,
serviceSpeedBillingModel,
@@ -84,31 +83,6 @@ describe('service speed selection', () => {
expect(selected.model).toBe(entry);
expect(selected.args).toBe(args);
});
it.each([
[{ service_tier: 'priority' }, 'openai-responses', 'fast'],
[{ service_tier: 'ultrafast' }, 'openai-responses', 'ultrafast'],
[{ service_tier: 'auto' }, 'mistral', 'fast'],
[{ speed: 'fast' }, 'claude', 'fast'],
[{ service_tier: 'auto' }, 'openai-responses', undefined],
[{ service_tier: 'flex' }, 'openai-responses', undefined],
[{ speed: 'fast' }, 'openai-responses', undefined],
[{ serviceSpeed: 'standard', service_tier: 'priority' }, 'openai-responses', 'standard'],
] as const)('reads %j on %s as speed %s', (args, provider, speed) => {
expect(requestedServiceSpeed(args, provider)).toBe(speed);
});
it('prices a native priority tier like fast service', () => {
const entry = model('openai-responses', 'gpt-6.1-sol');
const args = { ...request(), service_tier: 'priority' as const };
const selected = selectServiceSpeed(
entry,
{ ...args, serviceSpeed: requestedServiceSpeed(args, entry.provider) },
noVariant,
);
const explicit = selectServiceSpeed(entry, request('fast'), noVariant);
expect(selected.speed).toBe('fast');
expect(selected.model).toEqual(explicit.model);
expect(selected.args.service_tier).toBe('priority');
});
it.each([
'deepseek',
'zai',
@@ -274,33 +248,6 @@ describe('served speed billing', () => {
expect(recorded).toEqual([result.costs]);
},
);
it.each([
['fast', 2],
['ultrafast', 6],
] as const)(
'bills a served %s tier at its catalog rate without a selection snapshot',
(speed, multiplier) => {
const entry = model('openai-responses', 'gpt-6.1-sol');
entry.pricingOverrides = [
{
minPromptTokens: 100,
costs: { prompt_tokens: 400, completion_tokens: 1500 },
},
];
const billed = serviceSpeedBillingModel(entry, speed);
expect(billed.costs.prompt_tokens).toBe(200 * multiplier);
expect(billed.pricingOverrides?.[0]?.costs.prompt_tokens).toBe(
400 * multiplier,
);
expect(serviceSpeedBillingModel(entry, 'standard')).toBe(entry);
},
);
it('bills a served premium tier as standard when the catalog has no rate for it', () => {
const entry = model('groq', 'some-model');
expect(serviceSpeedBillingModel(entry, 'fast').costs).toEqual(
entry.costs,
);
});
it('restores standard scheduled and long-context rates after a downgrade', () => {
const entry = model('openai-responses', 'gpt-6.1-sol');
entry.pricingOverrides = [
@@ -59,26 +59,6 @@ export interface ServiceSpeedSelection {
speed: ServiceSpeed;
}
/**
* The speed a request asks for. Native premium tier parameters count as the
* matching `serviceSpeed`, so they are priced like it; `serviceSpeed` wins.
*/
export const requestedServiceSpeed = (
args: Pick<ICompleteArguments, 'serviceSpeed' | 'service_tier' | 'speed'>,
provider: string | undefined,
): ServiceSpeed | undefined => {
if (args.serviceSpeed !== undefined) return args.serviceSpeed;
if (args.service_tier === 'ultrafast') return 'ultrafast';
if (
args.service_tier === 'priority' ||
(provider === 'claude' && args.speed === 'fast') ||
// Mistral's `auto` tier is its priority tier.
(provider === 'mistral' && args.service_tier === 'auto')
)
return 'fast';
return undefined;
};
/** Select only an equivalent model from the same provider's loaded catalog. */
export const selectServiceSpeed = (
model: IChatModel,
@@ -221,27 +201,16 @@ export const servedServiceSpeed = (
: 'standard';
};
/**
* The model priced at the speed the provider served. Without a selection
* snapshot the catalog's rates for that speed apply, so a premium tier reached
* some other way is never billed as standard.
*/
export const serviceSpeedBillingModel = (
model: IChatModel,
speed: ServiceSpeed,
): IChatModel => {
const pricing = model.serviceSpeedPricing ?? {
speed: 'standard',
standardCosts: model.costs,
standardOverrides: model.pricingOverrides,
fastCosts: serviceSpeedCosts(model, 'fast'),
ultrafastCosts: serviceSpeedCosts(model, 'ultrafast'),
};
if (pricing.speed === speed) return model;
const pricing = model.serviceSpeedPricing;
if (!pricing || pricing.speed === speed) return model;
const costs =
(speed === 'ultrafast' ? pricing.ultrafastCosts : undefined) ??
(speed !== 'standard' ? pricing.fastCosts : undefined) ??
pricing.standardCosts;
speed === 'fast'
? (pricing.fastCosts ?? pricing.standardCosts)
: pricing.standardCosts;
return {
...model,
costs,
@@ -190,39 +190,6 @@ describe('VoiceChangerDriver.convert argument validation', () => {
withActor(actor, () => driver.convert({ audio: undefined })),
).rejects.toMatchObject({ statusCode: 400 });
});
it.each([
['an unpriced', 'eleven_multilingual_sts_v1'],
['a malformed', 'eleven_english_sts_v2&x=1'],
])(
'rejects %s model before loading audio or calling ElevenLabs',
async (_label, model) => {
const { actor } = await makeUser();
await expect(
withActor(actor, () =>
driver.convert({
audio: 'https://audio.example/sample.wav',
model,
}),
),
).rejects.toMatchObject({
statusCode: 400,
legacyCode: 'field_invalid',
fields: {
key: 'model',
expected: [
'eleven_multilingual_sts_v2',
'eleven_english_sts_v2',
],
got: model,
},
});
expect(webFetchMock).not.toHaveBeenCalled();
expect(fetchSpy).not.toHaveBeenCalled();
expect(admitSpy).not.toHaveBeenCalled();
expect(incrementUsageSpy).not.toHaveBeenCalled();
},
);
});
// ── Credit gate ─────────────────────────────────────────────────────
@@ -51,10 +51,6 @@ const MAX_AUDIO_FILE_SIZE = 25 * 1024 * 1024;
// Covers the upload as well as the conversion.
const CONVERT_TIMEOUT_MS = 10 * 60 * 1000;
const SUPPORTED_MODELS = Object.keys(VOICE_CHANGER_COSTS).map(
(key) => key.split(':')[1]!,
);
const VOICE_CHANGER_CATALOG: ProviderCatalog = {
label: 'Speech-to-speech',
ids: ['elevenlabs'],
@@ -169,6 +165,14 @@ export class VoiceChangerDriver extends PuterDriver {
});
}
const loaded = await loadFileInput(
this.stores,
this.services.fs,
actor,
args.audio,
{ maxBytes: MAX_AUDIO_FILE_SIZE, acceptWebInput: true },
);
const modelId =
args.model_id || args.model || elevenlabs.defaultModelId;
const voiceId =
@@ -180,41 +184,21 @@ export class VoiceChangerDriver extends PuterDriver {
throw new HttpError(400, '`voice` is required', {
legacyCode: 'bad_request',
});
// `voiceId` lands in the request URL path, which carries our API key,
// so anything outside ElevenLabs' `[A-Za-z0-9_-]+` id shape could
// steer the request at a different endpoint.
if (!/^[A-Za-z0-9_-]+$/.test(voiceId))
// `voiceId` lands in the request URL path; `modelId` lands in a
// multipart field. Both are forwarded to ElevenLabs with our
// long-lived API key, so anything other than a strict alphanumeric
// shape lets a caller steer the request at a different endpoint or
// inject parameters. ElevenLabs voice/model IDs are always
// `[A-Za-z0-9_-]+` in practice.
const ID_REGEX = /^[A-Za-z0-9_-]+$/;
if (!ID_REGEX.test(voiceId))
throw new HttpError(400, '`voice` must be alphanumeric', {
legacyCode: 'bad_request',
});
// Gate on the cost table: an id we can't price is one we can't bill
// for, and ElevenLabs bills us for it either way. This also keeps
// anything but a known id out of the multipart `model_id` field.
const usageKey = `elevenlabs:${modelId}:second`;
if (!Object.hasOwn(VOICE_CHANGER_COSTS, usageKey)) {
throw new HttpError(
400,
`Invalid model: ${modelId}. Expected: ${SUPPORTED_MODELS.join(', ')}`,
{
legacyCode: 'field_invalid',
fields: {
key: 'model',
expected: SUPPORTED_MODELS,
got: modelId,
},
},
);
}
const ucentsPerSecond = VOICE_CHANGER_COSTS[usageKey]!;
const loaded = await loadFileInput(
this.stores,
this.services.fs,
actor,
args.audio,
{ maxBytes: MAX_AUDIO_FILE_SIZE, acceptWebInput: true },
);
if (!ID_REGEX.test(modelId))
throw new HttpError(400, '`model` must be alphanumeric', {
legacyCode: 'bad_request',
});
// The hold estimates seconds from the input at 128 kbps: compact audio
// is under-held rather than refused. Usage is metered from the length
@@ -223,6 +207,8 @@ export class VoiceChangerDriver extends PuterDriver {
1,
Math.ceil(loaded.buffer.byteLength / 16000),
);
const usageKey = `elevenlabs:${modelId}:second`;
const ucentsPerSecond = VOICE_CHANGER_COSTS[usageKey] ?? 0;
const estimatedCost = ucentsPerSecond * estimatedSeconds;
const formData = new FormData();
-1
View File
@@ -416,7 +416,6 @@ describe('PuterServer host header validation', () => {
'upgrade',
'top-up',
'request-email-confirmation',
'attach-custom-domain',
])('lets a deployment subdomain frame the %s popup and names it to the GUI', async (action) => {
const parent = `http://spreadsheet.puter.localhost:${port}`;
const guiParams = (body: string) =>
@@ -31,13 +31,24 @@ export const RECOMMENDED_APP_NAMES = [
'spreadsheet',
'presentation',
'whiteboard',
'notes',
'pdf-editor',
'contacts',
'calendar',
'meetings',
'teamchat',
'email',
'dev-center',
'cap-table',
'invoices',
'crm',
'signatures',
'projects',
'point-of-sale',
'inventory',
'hiring',
'time-tracking',
'shift-planner',
'equipment',
'chess',
'checkers',
'backgammon',
+1 -1
View File
@@ -2864,7 +2864,7 @@ export class AuthService extends PuterService {
#actorUserFromRow(user: UserRow) {
// Strip the password hash; pass everything else through so callers
// can read metadata, otp_enabled, etc. without
// can read metadata, desktop_bg_*, otp_enabled, etc. without
// re-fetching the user. Mirrors what /whoami exposes off of UserRow.
const { password: _password, ...rest } = user;
return {
+4 -2
View File
@@ -43,7 +43,7 @@ export type TokenType = 'session' | 'gui' | 'app-under-user' | 'access-token';
/**
* Browser session token. `'session'` is the HTTP-only-cookie flavor, `'gui'`
* the same shape served in a response body (e.g. the login response).
* the same shape served in a response body (e.g. QR login).
*/
export interface SessionTokenPayload extends TokenPayloadBase {
type: 'session' | 'gui';
@@ -109,7 +109,9 @@ export interface AccessTokenPayload extends TokenPayloadBase {
}
export type AnyTokenPayload =
SessionTokenPayload | AppUnderUserTokenPayload | AccessTokenPayload;
| SessionTokenPayload
| AppUnderUserTokenPayload
| AccessTokenPayload;
// -- Session row (from `sessions` table) ----------------------------
@@ -517,6 +517,8 @@ export class PuterHomepageService extends PuterService {
<meta name="theme-color" content="#ffffff">
${bundled ? `<link rel="stylesheet" href="${guiCss}">` : ''}
<link rel="preload" as="image" href="https://puter-assets.b-cdn.net/wallpaper.webp">
<script>
if ( ! window.service_script ) {
window.service_script_api_promise = (() => {
+2 -2
View File
@@ -159,8 +159,8 @@ export interface AppSummaryOptions {
/**
* The summary the desktop launches from directly, without re-reading the app
* (suggested, recommended and recent apps), so every launch-relevant flag
* belongs here.
* (suggested, recommended, recent and taskbar apps), so every launch-relevant
* flag belongs here.
*/
export function toAppSummary(
app: AppRow,
+271
View File
@@ -0,0 +1,271 @@
/**
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
*
* Puter is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import { v4 as uuidv4 } from 'uuid';
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
import { PuterServer } from '../server.ts';
import { setupTestServer } from '../testUtil.ts';
import { getTaskbarItems } from './taskbarItems.ts';
describe('getTaskbarItems', () => {
let server: PuterServer;
let deps: Parameters<typeof getTaskbarItems>[1];
beforeAll(async () => {
server = await setupTestServer();
deps = {
clients: server.clients,
stores: server.stores,
apiBaseUrl: 'https://api.puter.com',
config: { static_hosting_domain: 'puter.site' },
} as unknown as Parameters<typeof getTaskbarItems>[1];
});
afterAll(async () => {
await server?.shutdown();
});
const makeUser = async (taskbarItems?: unknown) => {
const username = `tb-${Math.random().toString(36).slice(2, 10)}`;
const created = await server.stores.user.create({
username,
uuid: uuidv4(),
password: null,
email: `${username}@test.local`,
} as never);
if (taskbarItems !== undefined) {
await server.stores.user.update(created.id, {
taskbar_items:
typeof taskbarItems === 'string'
? taskbarItems
: JSON.stringify(taskbarItems),
});
}
return (await server.stores.user.getById(created.id))!;
};
const makeApp = async (ownerUserId: number, overrides = {}) => {
const name = `tb-app-${Math.random().toString(36).slice(2, 10)}`;
return server.stores.app.create(
{
name,
title: `Title ${name}`,
index_url: `https://${name}.example.com/`,
description: 'a test app',
...overrides,
},
{ ownerUserId },
);
};
it('seeds the default taskbar for a user that has none, and persists it', async () => {
const user = await makeUser();
expect(user.taskbar_items).toBeFalsy();
await getTaskbarItems(user as never, deps);
const [row] = await server.clients.db.read(
'SELECT `taskbar_items` FROM `user` WHERE `id` = ?',
[user.id],
);
const stored = JSON.parse(String(row.taskbar_items));
expect(stored.map((e: { name: string }) => e.name)).toContain(
'app-center',
);
// The cached row must not keep serving the pre-seed value.
expect(
(await server.stores.user.getById(user.id))?.taskbar_items,
).toBeTruthy();
});
it('resolves entries by name, uid and id', async () => {
const owner = await makeUser([]);
const byName = await makeApp(owner.id);
const byUid = await makeApp(owner.id);
const byId = await makeApp(owner.id);
const user = await makeUser([
{ name: byName.name, type: 'app' },
{ uid: byUid.uid, type: 'app' },
{ id: byId.id, type: 'app' },
]);
const items = await getTaskbarItems(user as never, deps);
expect(items.map((i) => i.uid)).toEqual([
byName.uid,
byUid.uid,
byId.uid,
]);
expect(items[0]).toMatchObject({
uuid: byName.uid,
name: byName.name,
title: byName.title,
godmode: false,
maximize_on_start: false,
description: 'a test app',
});
});
it('resolves the whole taskbar with one batched lookup per key, not one per entry', async () => {
const owner = await makeUser([]);
const apps = await Promise.all([0, 1, 2].map(() => makeApp(owner.id)));
const byUid = await makeApp(owner.id);
const user = await makeUser([
...apps.map((app) => ({ name: app.name, type: 'app' })),
{ uid: byUid.uid, type: 'app' },
]);
const appStore = server.stores.app;
const spies = {
getByName: vi.spyOn(appStore, 'getByName'),
getByUid: vi.spyOn(appStore, 'getByUid'),
getById: vi.spyOn(appStore, 'getById'),
getByNames: vi.spyOn(appStore, 'getByNames'),
getByUids: vi.spyOn(appStore, 'getByUids'),
};
try {
const items = await getTaskbarItems(user as never, deps);
expect(items.map((i) => i.uid)).toEqual([
...apps.map((app) => app.uid),
byUid.uid,
]);
expect(spies.getByName).not.toHaveBeenCalled();
expect(spies.getByUid).not.toHaveBeenCalled();
expect(spies.getById).not.toHaveBeenCalled();
expect(spies.getByNames).toHaveBeenCalledTimes(1);
expect(spies.getByUids).toHaveBeenCalledTimes(1);
} finally {
for (const spy of Object.values(spies)) spy.mockRestore();
}
});
it('skips non-app entries, the explorer pin, and unresolvable apps', async () => {
const owner = await makeUser([]);
const app = await makeApp(owner.id);
const user = await makeUser([
{ name: 'explorer', type: 'app' },
{ name: 'nothing-here', type: 'app' },
{ name: app.name, type: 'separator' },
{ type: 'app' },
{ name: app.name, type: 'app' },
]);
const items = await getTaskbarItems(user as never, deps);
expect(items).toHaveLength(1);
expect(items[0].name).toBe(app.name);
});
it('falls back to an empty taskbar when the stored JSON is corrupt', async () => {
const user = await makeUser('{not json');
expect(await getTaskbarItems(user as never, deps)).toEqual([]);
});
it('accepts an already-parsed taskbar array on the user row', async () => {
const owner = await makeUser([]);
const app = await makeApp(owner.id);
const user = await makeUser([]);
const items = await getTaskbarItems(
{ ...user, taskbar_items: [{ name: app.name, type: 'app' }] },
deps,
);
expect(items.map((i) => i.name)).toEqual([app.name]);
});
it('builds a sized icon URL by default and drops the icon on request', async () => {
const owner = await makeUser([]);
const app = await makeApp(owner.id);
const user = await makeUser([{ name: app.name, type: 'app' }]);
const withIcon = await getTaskbarItems(user as never, deps, {
iconSize: 64,
});
expect(withIcon[0].icon).toBe(
`https://api.puter.com/app-icon/${app.uid}/64`,
);
const withoutIcon = await getTaskbarItems(user as never, deps, {
noIcons: true,
});
expect('icon' in withoutIcon[0]).toBe(false);
});
it('pairs the icon URL with the direct subdomain URL when one exists', async () => {
const owner = await makeUser([]);
// An http(s) icon column is what the resize pipeline leaves behind, so
// the sized PNG is on the subdomain.
const app = await makeApp(owner.id, {
icon: 'https://api.puter.com/app-icon/x',
});
const user = await makeUser([{ name: app.name, type: 'app' }]);
const items = await getTaskbarItems(user as never, deps, {
iconSize: 64,
});
expect(items[0].icon).toBe(
`https://api.puter.com/app-icon/${app.uid}/64`,
);
expect(items[0].iconCdnUrl).toBe(
`https://puter-app-icons.puter.site/${app.uid}-64.png`,
);
});
it('reports no subdomain URL for an app whose icon was never generated', async () => {
const owner = await makeUser([]);
const app = await makeApp(owner.id);
const user = await makeUser([{ name: app.name, type: 'app' }]);
const items = await getTaskbarItems(user as never, deps, {
iconSize: 64,
});
expect(items[0].iconCdnUrl).toBeNull();
});
it('falls back to the raw icon column when no API base URL is configured', async () => {
const owner = await makeUser([]);
const app = await makeApp(owner.id, {
icon: 'https://cdn.example.com/i.png',
});
const user = await makeUser([{ name: app.name, type: 'app' }]);
const items = await getTaskbarItems(
user as never,
{
...deps,
apiBaseUrl: undefined,
} as never,
);
expect(items[0].icon).toBe('https://cdn.example.com/i.png');
});
it('reports null for an app with no icon and no API base URL', async () => {
const owner = await makeUser([]);
const app = await makeApp(owner.id);
const user = await makeUser([{ name: app.name, type: 'app' }]);
const items = await getTaskbarItems(
user as never,
{
...deps,
apiBaseUrl: undefined,
} as never,
);
expect(items[0].icon).toBeNull();
});
});
+134
View File
@@ -0,0 +1,134 @@
/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
*
* Puter is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import type { AppIconHostConfig } from './appIcon.js';
import { toAppSummary, type AppRow } from './appView.js';
interface TaskbarEntry {
name?: string;
id?: number;
uid?: string;
type?: string;
}
interface TaskbarOptions {
iconSize?: number;
noIcons?: boolean;
}
interface TaskbarDeps {
apiBaseUrl?: string;
config?: AppIconHostConfig;
stores: {
app: {
getByNames: (names: string[]) => Promise<Map<string, AppRow>>;
getByUids: (uids: string[]) => Promise<Map<string, AppRow>>;
getByIds: (ids: number[]) => Promise<Map<number, AppRow>>;
};
user: {
update: (
id: number,
patch: Record<string, unknown>,
) => Promise<unknown>;
};
};
}
const DEFAULT_TASKBAR_ITEMS: TaskbarEntry[] = [
{ name: 'app-center', type: 'app' },
{ name: 'builder', type: 'app' },
{ name: 'dev-center', type: 'app' },
{ name: 'editor', type: 'app' },
{ name: 'code', type: 'app' },
{ name: 'camera', type: 'app' },
{ name: 'recorder', type: 'app' },
{ name: 'browser', type: 'app' },
];
export async function getTaskbarItems(
user: Record<string, unknown>,
deps: TaskbarDeps,
options: TaskbarOptions = {},
): Promise<Array<Record<string, unknown>>> {
let raw: TaskbarEntry[];
if (!user.taskbar_items) {
raw = DEFAULT_TASKBAR_ITEMS;
await deps.stores.user.update(user.id as number, {
taskbar_items: JSON.stringify(raw),
});
} else {
try {
raw =
typeof user.taskbar_items === 'string'
? JSON.parse(user.taskbar_items as string)
: (user.taskbar_items as TaskbarEntry[]);
} catch {
raw = [];
}
}
const entries = raw.filter(
(entry) => entry.type === 'app' && entry.name !== 'explorer',
);
const [byName, byUid, byId] = await Promise.all([
deps.stores.app.getByNames(
entries.flatMap((entry) => (entry.name ? [entry.name] : [])),
),
deps.stores.app.getByUids(
entries.flatMap((entry) =>
!entry.name && entry.uid ? [entry.uid] : [],
),
),
deps.stores.app.getByIds(
entries.flatMap((entry) =>
!entry.name && !entry.uid && entry.id ? [entry.id] : [],
),
),
]);
const items: Array<Record<string, unknown>> = [];
for (const entry of entries) {
const app = entry.name
? byName.get(entry.name)
: entry.uid
? byUid.get(entry.uid)
: entry.id
? byId.get(entry.id)
: undefined;
if (!app) continue;
const item: Record<string, unknown> = {
uid: app.uid,
...toAppSummary(app, {
apiBaseUrl: deps.apiBaseUrl,
config: deps.config,
iconSize: options.iconSize,
}),
description: app.description,
};
if (options.noIcons) {
delete item.icon;
delete item.iconCdnUrl;
}
items.push(item);
}
return items;
}
+21 -13
View File
@@ -85,17 +85,7 @@ describe('buildUserDetails', () => {
[`/${user.username}/Desktop`]: user.desktop_uuid,
[`/${user.username}/Trash`]: user.trash_uuid,
});
});
it('leaves out taskbar items saved on the account', async () => {
const user = {
...(await makeUser()),
taskbar_items: JSON.stringify([{ type: 'app', name: 'editor' }]),
};
const details = await buildUserDetails(user, deps(), {
isUser: true,
});
expect(details).not.toHaveProperty('taskbar_items');
expect(Array.isArray(details.taskbar_items)).toBe(true);
});
it('leaves the desktop-only parts out for an app actor', async () => {
@@ -103,6 +93,7 @@ describe('buildUserDetails', () => {
const details = await buildUserDetails(user, deps(), {
isUser: false,
});
expect(details).not.toHaveProperty('taskbar_items');
expect(details).not.toHaveProperty('directories');
expect(details.card_fallback_available).toBe(false);
});
@@ -133,7 +124,7 @@ describe('buildUserDetails lookups', () => {
return keys.slice(keys.indexOf('hasDevAccountAccess') + 1);
};
it('reads the linked provider and seat together, listed in a fixed order', async () => {
it('reads the linked provider, taskbar and seat together, listed in a fixed order', async () => {
const user = {
...(await makeUser()),
password: null,
@@ -171,6 +162,7 @@ describe('buildUserDetails lookups', () => {
);
expect(tailKeys(details)).toEqual([
'oidc_revalidate_url',
'taskbar_items',
'directories',
'team',
'last_activity_ts',
@@ -185,6 +177,7 @@ describe('buildUserDetails lookups', () => {
const user = {
...(await makeUser()),
password: null,
taskbar_items: JSON.stringify([{ type: 'app', name: 'editor' }]),
last_activity_ts: '2026-01-02 03:04:05',
};
const events: string[] = [];
@@ -206,6 +199,15 @@ describe('buildUserDetails lookups', () => {
},
},
stores: Object.assign(Object.create(d.stores), {
app: {
getByNames: () =>
timed(events, 'taskbar', 20, () => {
throw new Error('taskbar down');
}),
getByUids: async () => new Map(),
getByIds: async () => new Map(),
},
// Fails first, but is reported after the taskbar.
team: {
getOrgSeat: () =>
timed(events, 'seat', 5, () => {
@@ -217,12 +219,18 @@ describe('buildUserDetails lookups', () => {
{ isUser: true },
);
expect(warn.mock.calls).toEqual([
['[user-details] taskbar_items failed:', expect.any(Error)],
['[user-details] team lookup failed:', expect.any(Error)],
]);
} finally {
warn.mockRestore();
}
expect(tailKeys(details)).toEqual(['directories', 'last_activity_ts']);
expect(tailKeys(details)).toEqual([
'taskbar_items',
'directories',
'last_activity_ts',
]);
expect(details.taskbar_items).toEqual([]);
});
});
+49 -7
View File
@@ -27,12 +27,18 @@ import {
isCardFallbackEligible,
type CardFallbackClients,
} from './cardFallback.js';
import { getTaskbarItems } from './taskbarItems.js';
import { isEmailGateLast } from './verificationOrder.js';
type TaskbarDeps = Parameters<typeof getTaskbarItems>[1];
export interface UserDetailsDeps {
config: IConfig;
clients: CardFallbackClients;
stores: {
// `db.write` backs the taskbar's first-read default row.
clients: CardFallbackClients & {
db: { write: (query: string, params?: unknown[]) => Promise<unknown> };
};
stores: TaskbarDeps['stores'] & {
kv: Pick<SystemKVStore, 'get'>;
team?: Pick<TeamStoreContract, 'getOrgSeat'>;
};
@@ -72,8 +78,8 @@ const SENSITIVE_KEYS: ReadonlySet<string> = new Set([
]);
/**
* Delete every sensitive key at any depth (`metadata` is nested). Depth-limited
* and cycle-safe. Runs last over a whole payload.
* Delete every sensitive key at any depth (`metadata` and `taskbar_items` are
* nested). Depth-limited and cycle-safe. Runs last over a whole payload.
*/
export const scrubSensitive = (
value: unknown,
@@ -118,7 +124,7 @@ export const toUnixSeconds = (value: unknown): number | undefined => {
export async function buildUserDetails(
user: UserRow,
deps: UserDetailsDeps,
opts: { isUser: boolean },
opts: { isUser: boolean; iconSize?: number; noIcons?: boolean },
): Promise<Record<string, unknown>> {
const { config, clients, stores, services } = deps;
const { isUser } = opts;
@@ -164,6 +170,9 @@ export async function buildUserDetails(
cardFallbackDepsFrom(clients),
)
: false,
desktop_bg_url: user.desktop_bg_url,
desktop_bg_color: user.desktop_bg_color,
desktop_bg_fit: user.desktop_bg_fit,
is_temp: user.password === null && user.email === null,
is_user_token: true,
// Null until the account asks for a code; never minted here.
@@ -176,6 +185,14 @@ export async function buildUserDetails(
hasDevAccountAccess: !!user.metadata?.hasDevAccountAccess,
};
// Not an inline literal, so a `TaskbarDeps` without `clients` still
// accepts it.
const taskbarDeps = {
clients,
stores,
apiBaseUrl: String(config.api_base_url ?? ''),
config,
};
const linkedProvider = async () => {
if (!oidcOnly) return null;
try {
@@ -185,6 +202,19 @@ export async function buildUserDetails(
return null;
}
};
const taskbarItems = async () => {
if (!isUser) return null;
try {
return {
items: await getTaskbarItems(user, taskbarDeps, {
iconSize: opts.iconSize,
noIcons: opts.noIcons,
}),
};
} catch (error) {
return { error };
}
};
// The team that pays for the account; every seat restriction keys on it.
const orgSeat = async () => {
if (!isUser || config.teams_enabled !== true) return null;
@@ -196,14 +226,26 @@ export async function buildUserDetails(
};
// Independent and each best-effort, so read together; the results land
// below in the order the payload has always listed them.
const [provider, team] = await Promise.all([linkedProvider(), orgSeat()]);
const [provider, taskbar, team] = await Promise.all([
linkedProvider(),
taskbarItems(),
orgSeat(),
]);
if (provider) {
const origin = (config.origin ?? '').replace(/\/$/, '');
details.oidc_revalidate_url = `${origin}/auth/oidc/${provider}/start?flow=revalidate&user_uuid=${encodeURIComponent(user.uuid)}`;
}
if (isUser) {
if (taskbar) {
// Best-effort: the account still works without them.
if ('error' in taskbar) {
console.warn('[user-details] taskbar_items failed:', taskbar.error);
details.taskbar_items = [];
} else {
details.taskbar_items = taskbar.items;
}
const directories: Record<string, unknown> = {};
const nameToProp: Record<string, string> = {
desktop_uuid: `/${user.username}/Desktop`,
-6
View File
@@ -385,10 +385,6 @@ The `usageDetails.serviceSpeed` field reports the served speed. Billing uses the
### OpenAI models
Passing `service_tier: "priority"` selects fast service, and `service_tier: "ultrafast"` selects ultrafast service. These requests use the same prices and supported-speed selection as `serviceSpeed`. An explicit `serviceSpeed` takes precedence.
Input and reasoning tokens reported by a non-streaming Responses API call are billed even when its output is empty. These charges apply whether the request fails or retries another provider.
Fast service is available on models with a published Fast rate card. Ultrafast is available for GPT-6.1 Sol and GPT-6 Astra. Other models fall back to fast or standard. Cache and long-context rates apply to the served tier.
#### `temperature`
@@ -592,8 +588,6 @@ MiniMax M3 uses Priority admission for fast service. Earlier models with an equi
Fast service requests Priority when the account and model are eligible. The provider can serve the request at standard speed.
Passing `service_tier: "auto"` selects fast service, with the same prices as `serviceSpeed: "fast"`. An explicit `serviceSpeed` takes precedence.
### Alibaba Cloud models
Models with an equivalent Prime or Fast variant select that variant for fast service. Other models use standard service.
+1 -1
View File
@@ -32,7 +32,7 @@ Fine-tune the conversion:
| Option | Type | Description |
|--------|------|-------------|
| `voice` | `String` | Target ElevenLabs voice ID. Defaults to `21m00Tcm4TlvDq8ikWAM`. |
| `model` | `String` | Voice-changer model, either `eleven_multilingual_sts_v2` or `eleven_english_sts_v2` (English-only inputs). Defaults to `eleven_multilingual_sts_v2`. Any other value fails with a `field_invalid` error. |
| `model` | `String` | Voice-changer model. Defaults to `eleven_multilingual_sts_v2`. You can also use `eleven_english_sts_v2` for English-only inputs. |
| `output_format` | `String` | Desired output codec and bitrate, e.g. `mp3_44100_128`, `opus_48000_64`, or `pcm_48000`. Defaults to `mp3_44100_128`. |
| `voice_settings` | `Object \| String` | ElevenLabs voice settings payload (e.g. `{"stability":0.5,"similarity_boost":0.75}`). |
| `remove_background_noise` | `Boolean` | Apply background noise removal. |
+1 -1
View File
@@ -12,7 +12,7 @@ When the user adds a new domain, the dialog shows the DNS records to set at thei
Your app doesn't need any permission to call this method. The user makes the choice in the dialog, and your app only receives the domain they chose. Custom domains are billed to the user's Puter account, and the dialog shows the price before the user adds one.
Inside Puter, the dialog is rendered by the desktop environment. On a website, a puter.com popup hosts the dialog and signs the user in first if needed. Puter's own apps on puter.com subdomains show it in a frame over the page instead, when the user is signed in to both.
Inside Puter, the dialog is rendered by the desktop environment. On a website, a puter.com popup hosts the dialog and signs the user in first if needed.
## Syntax
+2 -1
View File
@@ -27,7 +27,7 @@ A set of key/value pairs that configure the window.
| `is_resizable` | `Boolean` | If set to `true`, the user can resize the window. |
| `has_head` | `Boolean` | If set to `true`, the window has a head which contains the icon and the close, minimize, and maximize buttons. |
| `disable_parent_window` | `Boolean` | If set to `true`, the parent window is blocked until the current window is closed. |
| `show_in_taskbar` | `Boolean` | Deprecated. It has no effect. |
| `show_in_taskbar` | `Boolean` | If set to `true`, the window is represented in the taskbar. |
## Return value
A `Promise` that resolves to a window handle object with an `id` (String) property identifying the created window. This `id` can be passed as the `window_id` argument to the `setWindow*` methods.
@@ -50,6 +50,7 @@ A `Promise` that resolves to a window handle object with an `id` (String) proper
is_resizable: false,
has_head: true,
center: true,
show_in_taskbar: false,
})
</script>
</body>
+6 -5
View File
@@ -36,11 +36,12 @@ Without `background`, Puter creates and shows the window before the app's own co
runs, so a service app cannot avoid briefly appearing on screen.
A background instance stays private to your app for as long as it is hidden: it has no
running mark on its icon, and opening the app from Puter's app list starts a
separate, ordinary instance for the user rather than handing them the one you
are talking to. It can show itself at any time with
[`puter.ui.showWindow()`](/UI/showWindow), and from that moment it is an
ordinary window that the user can return to, hide, or close like any other.
taskbar item and no running mark on its icon, and opening the app from the
taskbar or from Puter's app list starts a separate, ordinary instance for the
user rather than handing them the one you are talking to. It can show itself at
any time with [`puter.ui.showWindow()`](/UI/showWindow), and from that moment it
is an ordinary window. It takes its place in the taskbar, and the user can
return to it, hide it, or close it like any other.
A background app closes when the app that launched it closes: it was launched to
serve that app, and the user never saw it. Once it has shown itself it keeps
+1 -17
View File
@@ -13,20 +13,6 @@ puter.ui.showColorPicker(defaultColor)
puter.ui.showColorPicker(options)
```
## Parameters
#### `defaultColor` (String)
The color to select when the color picker is opened, as a hex string such as `#3b82f6` or `#38f`.
#### `options` (Object)
An object with the following properties:
| Option | Type | Description |
|--------|------|-------------|
| `defaultColor` | `String` | The color to select when the color picker is opened, as a hex string. The picker has no alpha, so the alpha in an 8-digit hex such as `#3b82f680` is ignored. If the value isn't a valid hex color, the picker opens on `#3b82f6`. The `defaultValue` and `default` options are accepted as aliases. If more than one is given, `defaultValue` is used, then `defaultColor`, then `default`. |
## Return value
A `Promise` that resolves to the selected color as a lowercase 6-digit hex string, such as `#ff0000`. If the user closes the picker without selecting a color, the promise resolves to `null`.
## Examples
### Change the background to the picked color
@@ -37,9 +23,7 @@ A `Promise` that resolves to the selected color as a lowercase 6-digit hex strin
<script src="https://js.puter.com/v2/"></script>
<script>
puter.ui.showColorPicker().then((color)=>{
if (color) {
document.body.style.backgroundColor = color;
}
document.body.style.backgroundColor = color;
})
</script>
</body>
@@ -6,10 +6,8 @@
<script>
document.getElementById('pick-color').addEventListener('click', () => {
puter.ui.showColorPicker().then((color) => {
if (color) {
document.body.style.backgroundColor = color;
puter.print('Selected color: ' + color);
}
document.body.style.backgroundColor = color;
puter.print('Selected color: ' + color);
});
});
</script>
+2
View File
@@ -1,5 +1,7 @@
## Credits
The default wallpaper is created by [Milad Fakurian](https://unsplash.com/photos/blue-orange-and-yellow-wallpaper-E8Ufcyxz514) and published on [Unsplash](https://unsplash.com/).
Icons by [Papirus](https://github.com/PapirusDevelopmentTeam/papirus-icon-theme) under GPL-3.0 license.
Icons by [Iconoir](https://iconoir.com/) under MIT license.
+1
View File
@@ -11,6 +11,7 @@
"/lib/jquery.dragster.js",
"/lib/html-entities.js",
"/lib/timeago.min.js",
"/lib/iro.min.js",
"/lib/isMobile.min.js",
"/lib/fflate-0.8.2.min.js"
],
+1
View File
@@ -40,6 +40,7 @@ vi.mock('./UI/UIPopover.js', stub);
vi.mock('./UI/UIPrompt.js', stub);
vi.mock('./UI/UIWindow.js', stub);
vi.mock('./UI/UIWindowAppFeedback.js', stub);
vi.mock('./UI/UIWindowColorPicker.js', stub);
vi.mock('./UI/UIWindowEmailConfirmationRequired.js', stub);
vi.mock('./UI/UIWindowFontPicker.js', stub);
vi.mock('./UI/UIPermissionDialog.js', () => ({ default: permissionDialog }));
+1
View File
@@ -18,6 +18,7 @@ vi.mock('./UI/UIPopover.js', stub);
vi.mock('./UI/UIPrompt.js', stub);
vi.mock('./UI/UIWindow.js', stub);
vi.mock('./UI/UIWindowAppFeedback.js', stub);
vi.mock('./UI/UIWindowColorPicker.js', stub);
vi.mock('./UI/UIWindowEmailConfirmationRequired.js', stub);
vi.mock('./UI/UIWindowFontPicker.js', stub);
vi.mock('./UI/UIPermissionDialog.js', stub);
+22 -28
View File
@@ -32,6 +32,7 @@ import UIPrompt from './UI/UIPrompt.js';
import UIWindow from './UI/UIWindow.js';
import UIWindowAppFeedback from './UI/UIWindowAppFeedback.js';
import UIWindowAttachCustomDomain from './UI/UIWindowAttachCustomDomain.js';
import UIWindowColorPicker from './UI/UIWindowColorPicker.js';
import UIWindowFontPicker from './UI/UIWindowFontPicker.js';
import UIPermissionDialog from './UI/UIPermissionDialog.js';
import UIEnablePushDialog from './UI/UIEnablePushDialog.js';
@@ -484,6 +485,7 @@ const ipc_listener = async (event, handled) => {
is_resizable: event.data.options.is_resizable,
has_head: event.data.options.has_head,
center: event.data.options.center,
show_in_taskbar: event.data.options.show_in_taskbar,
iframe_srcdoc: event.data.options.content,
parent_uuid: event.data.appInstanceID,
});
@@ -1148,9 +1150,9 @@ const ipc_listener = async (event, handled) => {
if ( event.data.y !== undefined ) {
event.data.y = parseFloat(event.data.y);
// we don't want the window to go off the top edge of the screen
if ( event.data.y < 0 )
if ( event.data.y < window.taskbar_height )
{
event.data.y = 0;
event.data.y = window.taskbar_height;
}
// we don't want the window to go off the bottom edge of the screen
if ( event.data.y > window.innerHeight - 100 )
@@ -1216,9 +1218,9 @@ const ipc_listener = async (event, handled) => {
if ( event.data.y !== undefined ) {
event.data.y = parseFloat(event.data.y);
// we don't want the window to go off the top edge of the screen
if ( event.data.y < 0 )
if ( event.data.y < window.taskbar_height )
{
event.data.y = 0;
event.data.y = window.taskbar_height;
}
// we don't want the window to go off the bottom edge of the screen
if ( event.data.y > window.innerHeight - 100 )
@@ -1623,34 +1625,26 @@ const ipc_listener = async (event, handled) => {
return;
}
const options = typeof event.data.options === 'string'
? { defaultColor: event.data.options }
: (event.data.options ?? {});
const requested_color = options.defaultValue ?? options.defaultColor ?? options.default;
// The picker has no alpha, so an 8-digit hex loses its last two digits.
// Anything still not a 3- or 6-digit hex is left out: older builds of
// the picker fail to open on it.
const default_color = typeof requested_color === 'string'
? requested_color.trim().replace(/^(#?[0-9a-f]{6})[0-9a-f]{2}$/i, '$1')
: '';
// set options
if ( typeof event.data.options === 'string' ) {
event.data.options = { defaultColor: event.data.options };
}
event.data.options = event.data.options ?? {};
// The same picker puter.js shows outside Puter, so an app gets one
// answer shape everywhere: a 6-digit hex string, or null on cancel.
const picker = document.createElement('puter-color-picker');
if ( /^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.test(default_color) ) picker.setAttribute('default-color', default_color);
const selected_color = await new Promise((resolve) => {
picker.addEventListener('response', (e) => resolve(e.detail ?? null), { once: true });
document.body.appendChild(picker);
picker.open();
});
// Older builds leave the element behind when Escape closes it.
picker.remove();
// Clear window_options for security reasons
event.data.options.window_options = {};
// The app may have closed while the picker was up.
target_iframe.contentWindow?.postMessage({
// Set app as parent window of the font picker window
event.data.options.window_options.parent_uuid = event.data.appInstanceID;
// Open color picker
let selected_color = await UIWindowColorPicker(event.data.options);
// Send selected color to requester window
target_iframe.contentWindow.postMessage({
msg: 'colorPicked',
original_msg_id: msg_id,
color: selected_color,
color: selected_color ? selected_color.color : undefined,
}, '*');
$(target_iframe).get(0).focus({ preventScroll: true });
}
@@ -41,6 +41,7 @@ vi.mock('./UI/UIPopover.js', stub);
vi.mock('./UI/UIPrompt.js', stub);
vi.mock('./UI/UIWindow.js', stub);
vi.mock('./UI/UIWindowAppFeedback.js', stub);
vi.mock('./UI/UIWindowColorPicker.js', stub);
vi.mock('./UI/UIWindowEmailConfirmationRequired.js', () => ({ default: confirmEmail }));
vi.mock('./UI/UIWindowFontPicker.js', stub);
vi.mock('./UI/UIPermissionDialog.js', stub);
-152
View File
@@ -1,152 +0,0 @@
// @vitest-environment jsdom
/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
*
* Puter is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
import jQuery from './lib/jquery-3.6.1/jquery-3.6.1.min.js';
globalThis.def = globalThis.def ?? ((cls) => cls);
globalThis.use = globalThis.use ?? (() => ({}));
globalThis.$ = globalThis.jQuery = jQuery;
globalThis.i18n = (key) => key;
const { stub } = vi.hoisted(() => ({ stub: () => ({ default: () => {} }) }));
vi.mock('./helpers/download.js', stub);
vi.mock('./helpers/itemIcon.js', stub);
vi.mock('./helpers/socialLink.js', stub);
vi.mock('./helpers/updateMousePosition.js', stub);
vi.mock('./UI/UIAlert.js', stub);
vi.mock('./UI/UIContextMenu.js', stub);
vi.mock('./UI/UIItem.js', stub);
vi.mock('./UI/UIPopover.js', stub);
vi.mock('./UI/UIPrompt.js', stub);
vi.mock('./UI/UIWindow.js', stub);
vi.mock('./UI/UIWindowAppFeedback.js', stub);
vi.mock('./UI/UIWindowEmailConfirmationRequired.js', stub);
vi.mock('./UI/UIWindowFontPicker.js', stub);
vi.mock('./UI/UIPermissionDialog.js', stub);
vi.mock('./UI/UIEnablePushDialog.js', stub);
vi.mock('./UI/UIWindowSaveAccount.js', stub);
vi.mock('./UI/Auth/UIAuthSignup.js', stub);
vi.mock('./UI/UINotification.js', stub);
vi.mock('./helpers/godmodeTokens.js', () => ({ renewGodmodeToken: vi.fn() }));
vi.mock('./helpers/watchItems.js', () => ({ addItemWatcher: vi.fn() }));
vi.mock('./helpers/verification_gates.js', () => ({
openVerificationGateWindow: vi.fn(),
}));
// Stands in for puter.js's <puter-color-picker>, which the GUI page gets from
// the SDK: it records how it was opened, and the test answers for the user.
const opened = [];
class FakeColorPicker extends HTMLElement {
open () {
opened.push(this);
}
answer (color) {
this.dispatchEvent(new CustomEvent('response', { detail: color }));
}
}
customElements.define('puter-color-picker', FakeColorPicker);
let iframe;
let posted;
beforeAll(async () => {
window.when_puter_happens = [];
window.appCallbackFunctions = {};
await import('./IPC.js');
globalThis.puter = { services: undefined, util: { rpc: { send: vi.fn() } } };
for (const fn of window.when_puter_happens) await fn();
});
beforeEach(() => {
opened.length = 0;
document.body.innerHTML = '';
const win = document.createElement('div');
win.setAttribute('data-app_uuid', 'app-1');
iframe = document.createElement('iframe');
iframe.setAttribute('data-app', 'notes');
win.append(iframe);
document.body.append(win);
posted = vi.spyOn(iframe.contentWindow, 'postMessage').mockImplementation(() => {});
window.app_instance_ids = new Set(['inst-1']);
window.iframe_for_app_instance = (id) => (id === 'inst-1' ? iframe : null);
window.window_for_app_instance = () => win;
window.is_auth = () => true;
window.ipc_handlers = {};
globalThis.services = { get: () => ({ get_by_uuid: () => ({ name: 'caller', uuid: 'inst-1' }) }) };
});
const request = (options) =>
window.dispatchEvent(
new MessageEvent('message', {
data: { appInstanceID: 'inst-1', env: 'app', msg: 'showColorPicker', uuid: 'cb-1', options },
source: iframe.contentWindow,
origin: 'https://app.example',
}),
);
const settle = () => new Promise((r) => setTimeout(r, 20));
const replies = () => posted.mock.calls
.map(([data]) => data)
.filter((data) => data.msg === 'colorPicked');
describe('showColorPicker', () => {
it.each([
['a string', '#abcdef'],
['defaultColor', { defaultColor: '#abcdef' }],
['the legacy default alias', { default: '#abcdef' }],
['the legacy defaultValue alias', { defaultValue: '#abcdef' }],
['an 8-digit hex, without its alpha', '#abcdef80'],
])('opens the picker on the color given as %s', async (_, options) => {
request(options);
await settle();
expect(opened).toHaveLength(1);
expect(opened[0].getAttribute('default-color')).toBe('#abcdef');
expect(opened[0].isConnected).toBe(true);
});
it.each([
['no color', undefined],
['a color that isn\'t hex', 'red'],
['a malformed hex', '#abcd'],
])('leaves the picker\'s own default when the app gives %s', async (_, options) => {
request(options);
await settle();
expect(opened[0].hasAttribute('default-color')).toBe(false);
});
it('replies with the picked color', async () => {
request('#abcdef');
await settle();
opened[0].answer('#123456');
await settle();
expect(replies()).toEqual([{ msg: 'colorPicked', original_msg_id: 'cb-1', color: '#123456' }]);
expect(opened[0].isConnected).toBe(false);
});
it('replies null when the user cancels', async () => {
request();
await settle();
opened[0].answer(null);
await settle();
expect(replies()).toEqual([{ msg: 'colorPicked', original_msg_id: 'cb-1', color: null }]);
expect(opened[0].isConnected).toBe(false);
});
});
+2 -19
View File
@@ -20,7 +20,6 @@
import UIWindow from '../UIWindow.js';
import {
openChangeEmailDialog,
openChangeLanguageDialog,
openChangePasswordDialog,
openChangeUsernameDialog,
openCreateTokenDialog,
@@ -142,21 +141,6 @@ const TabAccount = {
h += '</div>';
}
// Language card
const language = window.listSupportedLanguages().find((lang) => lang.code === window.locale);
h += '<div class="dashboard-card dashboard-settings-card">';
h += '<div class="dashboard-settings-card-content">';
h += '<div class="dashboard-settings-card-icon">';
h += '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><path d="M2 12h20"/><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/></svg>';
h += '</div>';
h += '<div class="dashboard-settings-card-info">';
h += `<strong>${i18n('language')}</strong>`;
h += `<span>${html_encode(language?.name ?? window.locale)}</span>`;
h += '</div>';
h += '</div>';
h += `<button class="button change-language">${i18n('change_language')}</button>`;
h += '</div>';
// API token card
h += '<div class="dashboard-card dashboard-settings-card">';
h += '<div class="dashboard-settings-card-content">';
@@ -229,9 +213,6 @@ const TabAccount = {
$el_window.find('.dashboard-section-account .change-email').on('click', function () {
openChangeEmailDialog(dialogOptions(this));
});
$el_window.find('.dashboard-section-account .change-language').on('click', function () {
openChangeLanguageDialog(dialogOptions(this));
});
$el_window.find('.dashboard-section-account .copy-auth-token').on('click', function () {
openCreateTokenDialog({ ...dialogOptions(this), $sessionsParent: $el_window });
});
@@ -270,6 +251,8 @@ const TabAccount = {
function showProfilePicture (picture) {
const url = picture ?? window.icons['profile.svg'];
$('.profile-pic').css('background-image', `url(${ html_encode(url) })`);
$('.profile-image').css('background-image', `url(${ html_encode(url) })`);
$('.profile-image').toggleClass('profile-image-has-picture', !! picture);
}
// A save started after another one owns the avatar and the hint; the
// earlier one's answer must not put its picture (or a failure) back.
+19
View File
@@ -296,6 +296,25 @@ const TabHome = {
h += '</div>';
h += '</div>';
// Open Desktop card (spans full width, links to the desktop interface)
h +=
'<a href="/desktop" target="_blank" rel="noopener" class="bento-card bento-desktop allow-native-ctxmenu">';
h +=
'<div class="bento-card-fancy-icon bento-card-fancy-icon-desktop">';
h +=
'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><rect x="2" y="3" width="20" height="14" rx="2"/><line x1="8" y1="21" x2="16" y2="21"/><line x1="12" y1="17" x2="12" y2="21"/></svg>';
h += '</div>';
h += '<div class="bento-card-fancy-text">';
h += `<h2>${i18n('open_desktop')}</h2>`;
h += '<span class="bento-card-fancy-subtitle">';
h +=
'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="5" y1="12" x2="19" y2="12"/><polyline points="12 5 19 12 12 19"/></svg>';
h += i18n('open_desktop_hint');
h += '</span>';
h += '</div>';
h += '<span class="bento-desktop-arrow">›</span>';
h += '</a>';
h += '</div>';
return h;
},
@@ -25,7 +25,6 @@ import check_password_strength from '../../helpers/checkPasswordStrength.js';
import create_access_token from '../../helpers/createAccessToken.js';
import postUserProtected from '../../helpers/postUserProtected.js';
import update_username_in_gui from '../../helpers/updateUsernameInGui.js';
import changeLanguage from '../../i18n/i18nChangeLanguage.js';
import UIWindowManageSessions from '../UIWindowManageSessions.js';
import UIDashboardFormDialog, { copyRowHtml } from './UIDashboardFormDialog.js';
@@ -120,42 +119,6 @@ export function openEditProfileDialog ({ onSave, ...opts } = {}) {
});
}
/**
* Changes the language Puter is shown in, then reloads the page in it.
*
* @param {AccountDialogOptions} [opts]
*/
export function openChangeLanguageDialog (opts = {}) {
return UIDashboardFormDialog({
...opts,
title: t('change_language'),
submitLabel: t('save'),
fields: [
{
name: 'language',
type: 'select',
label: i18n('language'),
value: window.locale,
options: window.listSupportedLanguages().map((lang) => ({
value: lang.code,
label: html_encode(lang.name),
})),
},
],
async onSubmit (dialog) {
const { language } = dialog.values();
if ( language === window.locale ) {
dialog.close();
return;
}
// On success the page reloads, so the dialog stays in progress.
if ( ! await changeLanguage(language) ) {
dialog.setStatus(t('language_save_failed'), { field: 'language' });
}
},
});
}
/**
* Changes the signed-in user's username.
*
@@ -293,57 +293,6 @@ describe('create API token', () => {
});
});
describe('change language', () => {
beforeEach(() => {
window.locale = 'en';
window.listSupportedLanguages = () => [
{ code: 'en', name: 'English' },
{ code: 'de', name: 'Deutsch' },
{ code: 'ja', name: '日本語' },
];
window.mutate_user_preferences = vi.fn();
globalThis.puter.kv = { set: vi.fn(async () => true) };
});
it('lists every language by its own name, with the current one selected', () => {
dialogs.openChangeLanguageDialog();
const options = field('language').find('option').map((_, el) => [[el.value, el.textContent]]).get();
expect(options).toEqual([['en', 'English'], ['de', 'Deutsch'], ['ja', '日本語']]);
expect(field('language').val()).toBe('en');
});
it('closes without saving when the language is unchanged', async () => {
dialogs.openChangeLanguageDialog();
await submitWith({ language: 'en' });
expect(puter.kv.set).not.toHaveBeenCalled();
expect(isOpen()).toBe(false);
});
it('saves the picked language to the account', async () => {
dialogs.openChangeLanguageDialog();
await submitWith({ language: 'de' });
expect(puter.kv.set).toHaveBeenCalledWith('user_preferences.language', 'de');
expect(window.mutate_user_preferences).toHaveBeenCalledWith({ language: 'de' });
expect(status()).toBe('');
});
it('stays open with an error when the save fails', async () => {
puter.kv.set.mockRejectedValue(new Error('offline'));
vi.spyOn(console, 'warn').mockImplementation(() => {});
dialogs.openChangeLanguageDialog();
await submitWith({ language: 'de' });
expect(window.mutate_user_preferences).not.toHaveBeenCalled();
expect(status()).toBe('language_save_failed');
expect(isOpen()).toBe(true);
});
});
describe('delete account', () => {
it('asks a temporary account to type confirm', async () => {
// What the server sends for a temporary account: no password, so `oidc_only` too.
+2 -1
View File
@@ -75,7 +75,8 @@ async function UIDashboard (options) {
// eslint-disable-next-line no-unused-vars
options = options ?? {};
// Mark dashboard mode on <body> so window chrome and notifications can adapt.
// Mark dashboard mode on <body> so window chrome can adapt — e.g. app
// windows keep their minimize button even though fullpage-mode hides it.
$('body').addClass('dashboard-mode');
// Create mutable tabs array from built-in tabs
+8 -6
View File
@@ -109,9 +109,10 @@ const count_label = (count) => (count === 1
: i18n('items_count_other', { count }));
/**
* A responsive sharing modal for the Dashboard's Files tab: a self-contained
* overlay that behaves as a centered card on desktop and a bottom sheet on
* mobile, styled with the dashboard's design tokens.
* A responsive, from-scratch sharing modal for the Dashboard's Files tab.
* Unlike UIWindowShare (which spawns a desktop UIWindow), this renders a
* self-contained overlay that behaves as a centered card on desktop and a
* bottom sheet on mobile, styled with the dashboard's design tokens.
*
* Shares one item or a whole selection. With several items the access list is
* one row per person folded across them ({@link aggregateShares}), so every
@@ -119,9 +120,10 @@ const count_label = (count) => (count === 1
* rather than a chore repeated per file. A person who holds only some of the
* selection says so, and can be extended to the rest in one click.
*
* Grants access by email or username, lists who has access (owner, direct
* grants, grants inherited from an ancestor folder), changes a grant's mode,
* and revokes, with the revoke confirmation inlined into the row.
* Feature-equivalent to UIWindowShare: grant access by email or username,
* list who has access (owner, direct grants, grants inherited from an
* ancestor folder), change a grant's mode, and revoke — with the revoke
* confirmation inlined into the row instead of a stacked alert window.
*
* @param {Object} opts
* @param {Array<Object>} [opts.items] - The items to share, each
@@ -221,7 +221,7 @@ describe('aggregateShares', () => {
it('falls back to the handle, then the uid, for an unnamed team', () => {
// Whatever team_label says, so a team reads the same here as it does
// in the recipient suggestions.
// in the desktop dialog's access list.
const named = (team) => aggregateShares(['/me/a'], new Map([
['/me/a', [grant(null, 'read', { holderTeam: team })]],
]))[0].name;
@@ -79,6 +79,7 @@ async function UIWindowDisable2FA (options) {
width: 350,
height: 'auto',
dominant: true,
show_in_taskbar: false,
on_before_exit: async () => {
if ( ! disabled_successfully ) {
promise.resolve(false);
+1
View File
@@ -136,6 +136,7 @@ function UIAlert (options) {
selectable_body: false,
draggable_body: options.draggable_body ?? true,
allow_context_menu: false,
show_in_taskbar: false,
window_class: 'window-alert',
dominant: true,
body_content: h,
+243
View File
@@ -0,0 +1,243 @@
/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
*
* Puter is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/**
* Creates a reusable color picker widget using iro.ColorPicker
* @param {HTMLElement|jQuery} container - Container element for the color picker
* @param {Object} options - Configuration options
* @param {string} options.default - Default color in hex format (e.g., "#f00" or "#ff0000ff")
* @param {Object} options.layout - Custom layout configuration for iro.ColorPicker
* @param {Function} options.onColorChange - Callback function called when color changes
* @returns {Object} Color picker instance with methods to interact with it
*/
export function UIColorPickerWidget (container, options = {}) {
// Get the DOM element if it's a jQuery object
const domElement = container instanceof HTMLElement
? container
: $(container).get(0);
if ( ! domElement ) {
throw new Error('Container element is required');
}
// Default layout configuration
const defaultLayout = [
{
component: iro.ui.Box,
options: {
layoutDirection: 'horizontal',
width: 265,
height: 265,
},
},
{
component: iro.ui.Slider,
options: {
sliderType: 'alpha',
layoutDirection: 'horizontal',
height: 265,
width: 265,
},
},
{
component: iro.ui.Slider,
options: {
sliderType: 'hue',
},
},
];
// Initialize the color picker
const colorPicker = new iro.ColorPicker(domElement, {
layout: options.layout ?? defaultLayout,
color: options.default ?? '#f00',
});
// Set up color change callback if provided
if ( options.onColorChange ) {
colorPicker.on('color:change', (color) => {
options.onColorChange(color);
});
}
return {
/**
* Get the current color
* @returns {Object} iro.Color object
*/
getColor: () => colorPicker.color,
/**
* Get the current color as hex8 string (includes alpha)
* @returns {string} Color in hex8 format (e.g., "#ff0000ff")
*/
getHex8String: () => colorPicker.color.hex8String,
/**
* Get the current color as hex string (no alpha)
* @returns {string} Color in hex format (e.g., "#ff0000")
*/
getHexString: () => colorPicker.color.hexString,
/**
* Get the current color as HSLA object
* @returns {Object} Object with h, s, l, a properties
*/
getHSLA: () => {
const color = colorPicker.color;
return color.hsla;
},
/**
* Set the color
* @param {string|Object} color - Color in hex format (e.g., "#f00" or "#ff0000ff") or HSLA object
*/
setColor: (color) => {
if ( typeof color === 'string' ) {
// Remove # if present for matching
const hexValue = color.startsWith('#') ? color.substring(1) : color;
// Check if it's a hex8 string (8 hex digits)
if ( /^[0-9a-fA-F]{8}$/.test(hexValue) ) {
// It's a hex8 string, set both hex and alpha
const hex6 = `#${ hexValue.substring(0, 6)}`; // Get first 6 hex digits
const alphaHex = hexValue.substring(6, 8); // Get last 2 hex digits (alpha)
colorPicker.color.hexString = hex6;
colorPicker.color.alpha = parseInt(alphaHex, 16) / 255;
} else {
// Regular hex string (with or without #)
colorPicker.color.hexString = color.startsWith('#') ? color : `#${ color}`;
}
} else if ( typeof color === 'object' && color.h !== undefined ) {
// HSLA object - set properties directly
colorPicker.color.hue = color.h;
colorPicker.color.saturation = color.s;
colorPicker.color.lightness = color.l;
colorPicker.color.alpha = color.a !== undefined ? color.a : 1;
}
},
/**
* Add an event listener
* @param {string} event - Event name (e.g., 'color:change')
* @param {Function} callback - Callback function
*/
on: (event, callback) => {
colorPicker.on(event, callback);
},
/**
* Remove an event listener
* @param {string} event - Event name
* @param {Function} callback - Callback function
*/
off: (event, callback) => {
colorPicker.off(event, callback);
},
/**
* Get the underlying iro.ColorPicker instance
* @returns {iro.ColorPicker} The iro.ColorPicker instance
*/
getPicker: () => colorPicker,
};
}
/**
* Converts HSLA values to hex8 string
* @param {number} h - Hue (0-360)
* @param {number} s - Saturation (0-100)
* @param {number} l - Lightness (0-100)
* @param {number} a - Alpha (0-1)
* @returns {string} Color in hex8 format
*/
export function hslaToHex8 (h, s, l, a) {
// Convert HSL to RGB
s /= 100;
l /= 100;
const c = (1 - Math.abs(2 * l - 1)) * s;
const x = c * (1 - Math.abs((h / 60) % 2 - 1));
const m = l - c / 2;
let r = 0, g = 0, b = 0;
if ( h >= 0 && h < 60 ) {
r = c; g = x; b = 0;
} else if ( h >= 60 && h < 120 ) {
r = x; g = c; b = 0;
} else if ( h >= 120 && h < 180 ) {
r = 0; g = c; b = x;
} else if ( h >= 180 && h < 240 ) {
r = 0; g = x; b = c;
} else if ( h >= 240 && h < 300 ) {
r = x; g = 0; b = c;
} else if ( h >= 300 && h < 360 ) {
r = c; g = 0; b = x;
}
r = Math.round((r + m) * 255);
g = Math.round((g + m) * 255);
b = Math.round((b + m) * 255);
const alpha = Math.round(a * 255);
return `#${[r, g, b, alpha].map(x => {
const hex = x.toString(16);
return hex.length === 1 ? `0${ hex}` : hex;
}).join('')}`;
}
/**
* Converts hex8 string to HSLA object
* @param {string} hex8 - Color in hex8 format (e.g., "#ff0000ff")
* @returns {Object} Object with h, s, l, a properties
*/
export function hex8ToHSLA (hex8) {
// Remove # if present
hex8 = hex8.replace('#', '');
// Parse hex values
const r = parseInt(hex8.substring(0, 2), 16) / 255;
const g = parseInt(hex8.substring(2, 4), 16) / 255;
const b = parseInt(hex8.substring(4, 6), 16) / 255;
const a = parseInt(hex8.substring(6, 8), 16) / 255;
// Convert RGB to HSL
const max = Math.max(r, g, b);
const min = Math.min(r, g, b);
let h, s, l = (max + min) / 2;
if ( max === min ) {
h = s = 0; // achromatic
} else {
const d = max - min;
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
switch ( max ) {
case r: h = ((g - b) / d + (g < b ? 6 : 0)) / 6; break;
case g: h = ((b - r) / d + 2) / 6; break;
case b: h = ((r - g) / d + 4) / 6; break;
}
}
return {
h: Math.round(h * 360),
s: Math.round(s * 100),
l: Math.round(l * 100),
a: a,
};
}
+5 -2
View File
@@ -568,9 +568,9 @@ function UIContextMenu (options) {
// Y position
// is the menu going to go out of the window from the bottom?
if ( (start_y + menu_height) > (window.innerHeight - 10) )
if ( (start_y + menu_height) > (window.innerHeight - window.taskbar_height - 10) )
{
y_pos = window.innerHeight - menu_height - 10;
y_pos = window.innerHeight - menu_height - window.taskbar_height - 10;
}
else
{
@@ -801,6 +801,9 @@ function UIContextMenu (options) {
$(options.parent_element).css('overflow', 'scroll');
$(options.parent_element).removeClass('has-open-contextmenu');
if ( $(options.parent_element).hasClass('taskbar-item') ) {
window.make_taskbar_sortable();
}
}
});
File diff suppressed because it is too large. Load diff
+84 -4
View File
@@ -18,17 +18,21 @@
*/
import UIWindowItemProperties from './UIWindowItemProperties.js';
import ensureConfirmedEmail from '../helpers/ensureConfirmedEmail.js';
import UIPopover from './UIPopover.js';
import UIContextMenu from './UIContextMenu.js';
import UIAlert from './UIAlert.js';
import UIWindowPublishWorker from './UIWindowPublishWorker.js';
import UIWindowShare from './UIWindowShare.js';
import path from '../lib/path.js';
import truncate_filename from '../helpers/truncateFilename.js';
import launch_app from '../helpers/launchApp.js';
import open_item from '../helpers/openItem.js';
import publish_as_website from '../helpers/publishAsWebsite.js';
import mime from '../lib/mime.js';
import { isWeblinkName, weblinkChangeIconMenuItem } from '../helpers/weblink.js';
import { is_owned_by_me } from '../helpers/pathOwner.js';
import { can_rename, can_restructure, invalidate_shared_roots } from '../helpers/sharedAccess.js';
import { can_rename, can_restructure, invalidate_shared_roots, shared_mode_for } from '../helpers/sharedAccess.js';
import { is_default_app } from '../helpers/defaultApp.js';
import openWithAI from '../helpers/openWithAI.js';
import refresh_item_container from '../helpers/refreshItemContainer.js';
@@ -325,6 +329,7 @@ async function UIItem (options) {
last_window_dragged_over = null;
window.an_item_is_being_dragged = true;
$('.toolbar').css('pointer-events', 'none');
},
drag: function (event, ui) {
// Constrain item within desktop bounds
@@ -414,8 +419,8 @@ async function UIItem (options) {
// the desktop itself, not a window showing the Desktop folder
if ( $(el_item).closest('.item-container').hasClass('desktop') &&
!window.is_auto_arrange_enabled && $(el_item).attr('data-path') !== window.trash_path && !ui.helper.data('dropped') &&
// .desktop clips its overflow, so the whole item has to fit above the bottom edge
window.mouseover_window === undefined && ui.position.top + $(el_item).outerHeight(true) <= window.desktop_height ) {
// Item must be dropped on the Desktop and not on the taskbar
window.mouseover_window === undefined && ui.position.top <= window.desktop_height - window.taskbar_height - 15 ) {
el_item.style.position = 'absolute';
el_item.style.left = `${ui.position.left }px`;
@@ -437,6 +442,7 @@ async function UIItem (options) {
clearTimeout(longer_hover_timeout);
last_window_dragged_over = null;
window.an_item_is_being_dragged = false;
$('.toolbar').css('pointer-events', 'auto');
},
});
@@ -1093,6 +1099,11 @@ async function UIItem (options) {
// Someone else's, however we got here — including items reached by
// opening a shared folder, which carry no share markers.
const is_not_mine = !is_owned_by_me($(el_item).attr('data-path'));
// `manage` inherits downwards, so a file inside a folder you manage
// counts too — the row itself only carries a mode at a shared root.
const can_manage_share =
$(el_item).attr('data-share_mode') === 'manage'
|| (await shared_mode_for($(el_item).attr('data-path'))) === 'manage';
// Moving and deleting go by the holding folder, not by the item.
const may_restructure = !is_not_mine
|| await can_restructure($(el_item).attr('data-path'));
@@ -1258,6 +1269,19 @@ async function UIItem (options) {
});
}
//-------------------------------------------
// Publish as Worker
// -------------------------------------------
// The backend refuses deploys from a file someone else owns.
if ( !is_trashed && !is_trash && !is_not_mine && !options.is_dir && $(el_item).attr('data-name').toLowerCase().endsWith('.js') ) {
menu_items.push({
html: i18n('publish_as_serverless_worker'),
onClick: async function () {
if ( ! await ensureConfirmedEmail(i18n('save_account_to_publish')) ) return;
UIWindowPublishWorker(options.uid, $(el_item).attr('data-name'), $(el_item).attr('data-path'));
},
});
}
// -------------------------------------------
// Deploy As App
// -------------------------------------------
@@ -1291,6 +1315,20 @@ async function UIItem (options) {
});
}
// -------------------------------------------
// Share
// -------------------------------------------
if ( !is_trash && !is_trashed && (!is_not_mine || can_manage_share) ) {
menu_items.push({
html: i18n('share_ellipsis'),
onClick: async function () {
UIWindowShare({
path: $(el_item).attr('data-path'),
name: $(el_item).attr('data-name'),
});
},
});
}
// -------------------------------------------
// Download
// -------------------------------------------
if ( !is_trash && !is_trashed && (options.associated_app_name === null || options.associated_app_name === undefined) ) {
@@ -1310,6 +1348,48 @@ async function UIItem (options) {
});
}
// -------------------------------------------
// Set as Wallpaper
// -------------------------------------------
const mime_type = mime.getType($(el_item).attr('data-name')) ??
'application/octet-stream';
if ( !is_trashed && !is_trash && !options.is_dir && mime_type.startsWith('image/') ) {
menu_items.push({
html: i18n('set_as_background'),
onClick: async function () {
const read_url = await puter.fs.sign(undefined, { uid: $(el_item).attr('data-uid'), action: 'read' });
window.set_desktop_background({
url: read_url.items.read_url,
fit: window.desktop_bg_fit,
});
try {
$.ajax({
url: `${window.api_origin }/set-desktop-bg`,
type: 'POST',
data: JSON.stringify({
url: window.desktop_bg_url,
color: window.desktop_bg_color,
fit: window.desktop_bg_fit,
}),
async: true,
contentType: 'application/json',
headers: {
'Authorization': `Bearer ${window.auth_token}`,
},
statusCode: {
401: function (xhr) {
window.handle401(xhr);
},
},
});
$(el_window).close();
resolve(true);
} catch ( err ) {
// Ignore
}
},
});
}
// -------------------------------------------
// Zip
// -------------------------------------------
if ( !is_trash && !is_trashed && !$(el_item).attr('data-path').endsWith('.zip') ) {
@@ -1554,7 +1634,7 @@ async function UIItem (options) {
left = left > (window.innerWidth - window_width) ? (window.innerWidth - window_width) : left;
let top = $(el_item).position().top + $(el_item).height();
top = top > (window.innerHeight - (window_height + window.toolbar_height)) ? (window.innerHeight - (window_height + window.toolbar_height)) : top;
top = top > (window.innerHeight - (window_height + window.taskbar_height + window.toolbar_height)) ? (window.innerHeight - (window_height + window.taskbar_height + window.toolbar_height)) : top;
UIWindowItemProperties(
$(el_item).attr('data-name'),
+2 -88
View File
@@ -27,6 +27,8 @@ vi.mock('./UIPopover.js', () => ({ default: vi.fn() }));
vi.mock('./UIWindowEmailConfirmationRequired.js', () => ({ default: vi.fn() }));
vi.mock('./UIContextMenu.js', () => ({ default: vi.fn() }));
vi.mock('./UIAlert.js', () => ({ default: vi.fn() }));
vi.mock('./UIWindowPublishWorker.js', () => ({ default: vi.fn() }));
vi.mock('./UIWindowShare.js', () => ({ default: vi.fn() }));
vi.mock('../helpers/launchApp.js', () => ({ default: vi.fn() }));
vi.mock('../helpers/openItem.js', () => ({ default: vi.fn() }));
vi.mock('../helpers/publishAsWebsite.js', () => ({ default: vi.fn() }));
@@ -137,91 +139,3 @@ describe('UIItem Remove from Shared', () => {
expect(refresh_item_container.mock.calls[0][0][0]).toBe($('.item-container')[0]);
});
});
describe('UIItem Share', () => {
beforeEach(() => {
window.user = { username: 'alice' };
window.trash_path = '/alice/Trash';
});
it('is not offered, even on an item the user owns', async () => {
const labels = await menuLabels({
path: '/alice/Photos',
owner: 'alice',
shared_with_me: false,
share_mode: undefined,
shared_by: undefined,
});
expect(labels).not.toContain('share_ellipsis');
});
});
describe('UIItem Publish as Worker', () => {
beforeEach(() => {
window.user = { username: 'alice' };
window.trash_path = '/alice/Trash';
});
it('is not offered, even on a .js file the user owns', async () => {
const labels = await menuLabels({
path: '/alice/worker.js',
name: 'worker.js',
is_dir: false,
owner: 'alice',
shared_with_me: false,
share_mode: undefined,
shared_by: undefined,
});
expect(labels).not.toContain('publish_as_serverless_worker');
});
});
describe('UIItem dropped on the desktop', () => {
let stop;
beforeEach(async () => {
document.body.innerHTML = '<div class="item-container desktop"></div>';
Object.assign(window, {
user: { username: 'alice' },
trash_path: '/alice/Trash',
desktop_height: 800,
is_auto_arrange_enabled: false,
mouseover_window: undefined,
desktop_item_positions: {},
save_desktop_item_positions: vi.fn(),
});
const draggable = jQuery.fn.draggable;
jQuery.fn.draggable = function (options) {
if ( typeof options === 'object' ) stop = options.stop;
return this;
};
try {
await UIItem({
appendTo: $('.item-container'),
uid: 'u-2',
path: '/alice/Desktop/Notes',
name: 'Notes',
is_dir: true,
icon: { image: '', type: 'icon' },
});
} finally {
jQuery.fn.draggable = draggable;
}
// jsdom has no stylesheet, so give the item the size style.css does.
$('.item').css({ height: '70px', margin: '15px 5px 30px 5px' });
});
const dropAt = (top) => stop({}, { position: { top, left: 300 }, helper: $('<div>') });
it('moves there when the whole item fits on screen', () => {
dropAt(685);
expect($('.item')[0].style.top).toBe('685px');
expect(window.save_desktop_item_positions).toHaveBeenCalledTimes(1);
});
it('stays put when the item would hang off the bottom edge', () => {
dropAt(735);
expect($('.item')[0].style.top).toBe('');
expect(window.save_desktop_item_positions).not.toHaveBeenCalled();
});
});
+38 -8
View File
@@ -62,17 +62,47 @@ function UIPopover (options) {
function position_popover () {
// X position
const popover_width = options.width ?? $(el_popover).width();
if ( options.position === 'bottom' || options.position === 'top' )
{
x_pos = options.left ?? ($(options.snapToElement).offset().left - (popover_width / 2) + 10);
}
else
{
x_pos = options.left ?? ($(options.snapToElement).offset().left + 5);
if ( options.center_horizontally ) {
// Check taskbar position to determine popover positioning
const taskbar_position = window.taskbar_position || 'bottom';
if ( taskbar_position === 'left' ) {
// Position in top-left corner for left taskbar
x_pos = window.taskbar_height + 10; // Just to the right of the taskbar
} else if ( taskbar_position === 'right' ) {
// Position in top-right corner for right taskbar
x_pos = window.innerWidth - popover_width - window.taskbar_height - 40; // Just to the left of the taskbar
} else {
// Default bottom taskbar behavior - center horizontally
x_pos = window.innerWidth / 2 - popover_width / 2 - 15;
}
} else {
if ( options.position === 'bottom' || options.position === 'top' )
{
x_pos = options.left ?? ($(options.snapToElement).offset().left - (popover_width / 2) + 10);
}
else
{
x_pos = options.left ?? ($(options.snapToElement).offset().left + 5);
}
}
// Y position
y_pos = options.top ?? ($(options.snapToElement).offset().top + $(options.snapToElement).height() + 5);
const popover_height = options.height ?? $(el_popover).height();
if ( options.center_horizontally ) {
// Check taskbar position to determine popover positioning
const taskbar_position = window.taskbar_position || 'bottom';
if ( taskbar_position === 'left' || taskbar_position === 'right' ) {
// Position at top for left/right taskbars
y_pos = window.toolbar_height + 10; // Just below the toolbar
} else {
// Default bottom taskbar behavior - position above taskbar
y_pos = options.top ?? (window.innerHeight - (window.taskbar_height + popover_height + 10));
}
} else {
y_pos = options.top ?? ($(options.snapToElement).offset().top + $(options.snapToElement).height() + 5);
}
$(el_popover).css({
left: `${x_pos }px`,
+1
View File
@@ -71,6 +71,7 @@ function UIPrompt (options) {
selectable_body: false,
draggable_body: true,
allow_context_menu: false,
show_in_taskbar: false,
window_class: 'window-alert',
dominant: true,
body_content: h,
+769
View File
@@ -0,0 +1,769 @@
/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
*
* Puter is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import { createUploadThumbnailGenerator } from '../services/pdfThumbnails/index.js';
import UITaskbarItem from './UITaskbarItem.js';
import UIPopover from './UIPopover.js';
import launch_app from '../helpers/launchApp.js';
import UIContextMenu from './UIContextMenu.js';
import { appIconAttrs, appIconSrc } from '../helpers/appIcon.js';
import { filterLaunchableApps } from '../helpers/launchAppsList.js';
const TASKBAR_POSITIONS = ['left', 'bottom', 'right'];
async function UITaskbar (options) {
window.global_element_id++;
options = options ?? {};
options.content = options.content ?? '';
let taskbar_position;
// if first visit ever, set taskbar position to left
if ( window.first_visit_ever ) {
puter.kv.set('taskbar_position', 'left').catch(err => console.warn('Could not save taskbar_position:', err));
taskbar_position = 'left';
} else {
taskbar_position = await puter.kv.get('taskbar_position').catch(() => null);
// if this is not first visit, set taskbar position to bottom since it's from a user that
// used puter before customizing taskbar position was added and the taskbar position was set to bottom
// Unknown values are discarded too: this ends up in markup and stored values may be poisoned.
if ( ! TASKBAR_POSITIONS.includes(taskbar_position) ) {
taskbar_position = 'bottom'; // default position
puter.kv.set('taskbar_position', taskbar_position).catch(err => console.warn('Could not save taskbar_position:', err));
}
}
// Force bottom position on mobile devices
if ( isMobile.phone || isMobile.tablet ) {
taskbar_position = 'bottom';
}
// Set global taskbar position
window.taskbar_position = taskbar_position;
let launchAppsRequest = 0;
let pendingLaunchApps;
const fetchLaunchApps = () => {
pendingLaunchApps?.abort();
pendingLaunchApps = $.ajax({
url: `${window.api_origin}/get-launch-apps?icon_size=64`,
type: 'GET',
contentType: 'application/json',
timeout: 30000,
headers: { 'Authorization': `Bearer ${window.auth_token}` },
});
return pendingLaunchApps;
};
const logRefreshFailure = (xhr, status) => {
if ( status !== 'abort' ) console.error('Failed to refresh launch apps:', status);
};
fetchLaunchApps().done(apps => {
if ( launchAppsRequest === 0 ) window.launch_apps = apps;
}).fail(logRefreshFailure);
let h = '';
h += `<div id="ui-taskbar_${window.global_element_id}" class="taskbar taskbar-position-${taskbar_position}" style="height:${window.taskbar_height}px;">`;
h += '<div class="taskbar-sortable" style="display: flex; justify-content: center; z-index: 99999;"></div>';
h += '</div>';
if ( taskbar_position === 'left' || taskbar_position === 'right' ) {
$('.desktop').addClass(`desktop-taskbar-position-${taskbar_position}`);
}
$('.desktop').append(h);
//---------------------------------------------
// add `Start` to taskbar
//---------------------------------------------
UITaskbarItem({
icon: window.icons['start.svg'],
name: i18n('start'),
sortable: false,
keep_in_taskbar: true,
disable_context_menu: true,
onClick: async function (item) {
// skip if popover already open
if ( $(item).hasClass('has-open-popover') )
{
$('.popover-launcher').remove();
return;
}
// show popover
let popover = UIPopover({
content: '<div class="launch-popover hide-scrollbar"></div>',
snapToElement: item,
parent_element: item,
width: 500,
height: 500,
class: 'popover-launcher',
center_horizontally: true,
});
$(popover).on('remove', () => pendingLaunchApps?.abort());
const request = ++launchAppsRequest;
if ( ! window.launch_apps?.recent ) {
window.launch_apps = { recent: [], recommended: [] };
}
$(popover).find('.launch-popover').append(`
<div class="launch-search-wrapper">
<input style="background-image:url('${window.icons['magnifier-outline.svg']}');" class="launch-search">
<img class="launch-search-clear" src="${window.icons['close.svg']}">
</div>
`);
const renderApps = () => {
const recentApps = filterLaunchableApps(window.launch_apps.recent);
const recommendedApps = filterLaunchableApps(window.launch_apps.recommended);
let apps_str = '';
// -------------------------------------------
// Recent apps
// -------------------------------------------
if ( recentApps.length > 0 ) {
// heading
apps_str += `<h1 class="start-section-heading start-section-heading-recent">${i18n('recent')}</h1>`;
// apps
apps_str += '<div class="launch-apps-recent">';
for ( let index = 0; index < window.launch_recent_apps_count && index < recentApps.length; index++ ) {
const app_info = recentApps[index];
apps_str += `<div title="${html_encode(app_info.title)}" data-name="${html_encode(app_info.name)}" class="start-app-card">`;
const icon = appIconSrc(app_info);
apps_str += `<div class="start-app" data-app-name="${html_encode(app_info.name)}" data-app-uuid="${html_encode(app_info.uuid)}" data-app-icon="${html_encode(icon.src)}" data-app-icon-fallback="${html_encode(icon.fallback)}" data-app-title="${html_encode(app_info.title)}">`;
apps_str += `<img class="start-app-icon" ${appIconAttrs(app_info, window.icons['app.svg'])}>`;
apps_str += `<span class="start-app-title">${html_encode(app_info.title)}</span>`;
apps_str += '</div>';
apps_str += '</div>';
}
apps_str += '</div>';
}
// -------------------------------------------
// Recommended apps
// -------------------------------------------
if ( recommendedApps.length > 0 ) {
// heading
apps_str += `<h1 class="start-section-heading start-section-heading-recommended" style="${recentApps.length > 0 ? 'padding-top: 30px;' : ''}">${i18n('recommended')}</h1>`;
// apps
apps_str += '<div class="launch-apps-recommended">';
for ( let index = 0; index < recommendedApps.length; index++ ) {
const app_info = recommendedApps[index];
apps_str += `<div title="${html_encode(app_info.title)}" data-name="${html_encode(app_info.name)}" class="start-app-card">`;
const icon = appIconSrc(app_info);
apps_str += `<div class="start-app" data-app-name="${html_encode(app_info.name)}" data-app-uuid="${html_encode(app_info.uuid)}" data-app-icon="${html_encode(icon.src)}" data-app-icon-fallback="${html_encode(icon.fallback)}" data-app-title="${html_encode(app_info.title)}">`;
apps_str += `<img class="start-app-icon" ${appIconAttrs(app_info, window.icons['app.svg'])}>`;
apps_str += `<span class="start-app-title">${html_encode(app_info.title)}</span>`;
apps_str += '</div>';
apps_str += '</div>';
}
apps_str += '</div>';
}
// Replace tiles only, so the search input keeps its text and focus.
$(popover).find('.start-section-heading, .launch-apps-recent, .launch-apps-recommended').remove();
$(popover).find('.launch-popover').append(apps_str);
// make apps draggable
$(popover).find('.start-app').draggable({
appendTo: 'body',
revert: 'invalid',
connectToSortable: '.taskbar-sortable',
zIndex: parseInt($(popover).css('z-index')) + 1,
scroll: false,
distance: 5,
revertDuration: 100,
helper: 'clone',
cursorAt: { left: 18, top: 20 },
start: function (event, ui) {
},
drag: function (event, ui) {
},
stop: function () {
},
});
};
renderApps();
if ( ! isMobile.phone ) $(popover).find('.launch-search').focus();
fetchLaunchApps().done(apps => {
if ( request !== launchAppsRequest || !popover.isConnected ) return;
window.launch_apps = apps;
renderApps();
$(popover).find('.launch-search').trigger('change');
}).fail(logRefreshFailure);
$(popover).on('click', function () {
// close other context menus
$('.context-menu').fadeOut(200, function () {
$(this).remove();
$('.launch-app-selected').removeClass('launch-app-selected');
});
});
$(popover).on('contextmenu taphold', function (e) {
if ( ! e.target.closest('.launch-search') ) {
e.preventDefault();
}
});
$(document).on('contextmenu taphold', '.start-app', function (e) {
if ( e.type === 'taphold' && !isMobile.phone && !isMobile.tablet )
{
return;
}
e.stopImmediatePropagation();
e.preventDefault();
// close other context menus
$('.context-menu').fadeOut(200, function () {
$(this).remove();
});
let items = [{
html: i18n('open'),
onClick: function () {
$(e.currentTarget).trigger('click');
},
}];
$('.launch-app-selected').removeClass('launch-app-selected');
$(e.currentTarget).parent().addClass('launch-app-selected');
// Determine pin state
const $existingTaskbarItem = $(`.taskbar-item[data-app="${e.currentTarget.dataset.appName}"]`);
const isPinned = $existingTaskbarItem.length > 0 && $existingTaskbarItem.attr('data-keep-in-taskbar') === 'true';
items.push({
html: i18n('add_to_desktop'),
onClick: async function () {
try {
const fileName = `${e.currentTarget.dataset.appTitle}.app`;
const content = JSON.stringify({
app: e.currentTarget.dataset.appName,
title: e.currentTarget.dataset.appTitle,
icon: e.currentTarget.dataset.appIcon,
});
await puter.fs.upload(new File([content], fileName), window.desktop_path, {
generateThumbnails: true,
thumbnailGenerator: createUploadThumbnailGenerator(),
});
} catch ( err ) {
console.error('Failed to add shortcut to desktop:', err);
// Consider showing a user-facing error notification
}
},
});
if ( ! isPinned ) {
items.push({
html: i18n('keep_in_taskbar'),
onClick: function () {
const $taskbarItem = $(`.taskbar-item[data-app="${e.currentTarget.dataset.appName}"]`);
if ( $taskbarItem.length === 0 ) {
// No taskbar item yet: create a new pinned one
UITaskbarItem({
icon: e.currentTarget.dataset.appIcon,
iconFallback: e.currentTarget.dataset.appIconFallback,
app: e.currentTarget.dataset.appName,
name: e.currentTarget.dataset.appTitle,
keep_in_taskbar: true,
});
} else if ( $taskbarItem.attr('data-keep-in-taskbar') !== 'true' ) {
// mark as pinned
$taskbarItem.attr('data-keep-in-taskbar', 'true');
}
// Persist
window.update_taskbar();
},
});
} else {
items.push({
html: i18n('remove_from_taskbar'),
onClick: function () {
const $taskbarItem = $(`.taskbar-item[data-app="${e.currentTarget.dataset.appName}"]`);
if ( $taskbarItem.length === 0 ) return; // nothing to do
// Unpin
$taskbarItem.attr('data-keep-in-taskbar', 'false');
// If no open windows for this app, remove the item
if ( $taskbarItem.attr('data-open-windows') === '0' ) {
if ( window.remove_taskbar_item ) {
window.remove_taskbar_item($taskbarItem.get(0));
} else {
$taskbarItem.remove();
}
}
window.update_taskbar();
},
});
}
UIContextMenu({
items: items,
});
return false;
});
},
});
//---------------------------------------------
// add `Explorer` to the taskbar
//---------------------------------------------
UITaskbarItem({
icon: window.icons['folders.svg'],
app: 'explorer',
name: 'Explorer',
sortable: false,
keep_in_taskbar: true,
lock_keep_in_taskbar: true,
onClick: function () {
let open_window_count = parseInt($('.taskbar-item[data-app="explorer"]').attr('data-open-windows'));
if ( open_window_count === 0 ) {
launch_app({ name: 'explorer', path: window.home_path });
} else {
return false;
}
},
});
//---------------------------------------------
// add separator before trash
//---------------------------------------------
UITaskbarItem({
icon: '', // No icon for separator
name: 'separator',
app: 'separator',
sortable: false,
keep_in_taskbar: true,
lock_keep_in_taskbar: true,
disable_context_menu: true,
style: 'pointer-events: none;', // Make it non-interactive
onClick: function () {
// Separator is non-interactive
return false;
},
});
//---------------------------------------------
// Add other useful apps to the taskbar
//---------------------------------------------
if ( window.user.taskbar_items && window.user.taskbar_items.length > 0 ) {
for ( let index = 0; index < window.user.taskbar_items.length; index++ ) {
const app_info = window.user.taskbar_items[index];
const icon = appIconSrc(app_info);
// add taskbar item for each app
UITaskbarItem({
icon: icon.src,
iconFallback: icon.fallback,
app: app_info.name,
name: app_info.title,
keep_in_taskbar: true,
onClick: function () {
let open_window_count = parseInt($(`.taskbar-item[data-app="${app_info.name}"]`).attr('data-open-windows'));
if ( open_window_count === 0 ) {
launch_app({
name: app_info.name,
});
} else {
return false;
}
},
});
}
}
//---------------------------------------------
// add `Trash` to the taskbar
//---------------------------------------------
const trash = await puter.fs.stat({ path: window.trash_path, consistency: 'eventual' });
if ( window.socket ) {
window.socket.emit('trash.is_empty', { is_empty: trash.is_empty });
}
UITaskbarItem({
icon: trash.is_empty ? window.icons['trash.svg'] : window.icons['trash-full.svg'],
app: 'trash',
name: `${i18n('trash')}`,
sortable: false,
keep_in_taskbar: true,
lock_keep_in_taskbar: true,
onClick: function () {
let open_windows = $(`.window[data-path="${html_encode(window.trash_path)}"]`);
if ( open_windows.length === 0 ) {
launch_app({ name: 'explorer', path: window.trash_path });
} else {
open_windows.focusWindow();
}
},
onItemsDrop: function (items) {
window.move_items(items, window.trash_path);
},
});
//---------------------------------------------
// add separator before trash
//---------------------------------------------
UITaskbarItem({
icon: '', // No icon for separator
name: 'separator',
app: 'separator',
sortable: false,
keep_in_taskbar: true,
lock_keep_in_taskbar: true,
disable_context_menu: true,
style: 'pointer-events: none;', // Make it non-interactive
onClick: function () {
// Separator is non-interactive
return false;
},
});
window.make_taskbar_sortable();
}
//-------------------------------------------
// Taskbar is sortable
//-------------------------------------------
window.make_taskbar_sortable = function () {
const position = window.taskbar_position || 'bottom';
const axis = position === 'bottom' ? 'x' : 'y';
$('.taskbar-sortable').sortable({
axis: axis,
items: '.taskbar-item-sortable:not(.has-open-contextmenu):not([data-app="separator"])',
cancel: '.has-open-contextmenu',
placeholder: 'taskbar-item-sortable-placeholder',
helper: 'clone',
distance: 5,
revert: 10,
receive: function (event, ui) {
if ( ! $(ui.item).hasClass('taskbar-item') ) {
// if app is already in taskbar, cancel
if ( $(`.taskbar-item[data-app="${$(ui.item).attr('data-app-name')}"]`).length !== 0 ) {
$(this).sortable('cancel');
$('.taskbar .start-app').remove();
return;
}
}
},
update: function (event, ui) {
if ( ! $(ui.item).hasClass('taskbar-item') ) {
// if app is already in taskbar, cancel
if ( $(`.taskbar-item[data-app="${$(ui.item).attr('data-app-name')}"]`).length !== 0 ) {
$(this).sortable('cancel');
$('.taskbar .start-app').remove();
return;
}
let item = UITaskbarItem({
icon: $(ui.item).attr('data-app-icon'),
iconFallback: $(ui.item).attr('data-app-icon-fallback'),
app: $(ui.item).attr('data-app-name'),
name: $(ui.item).attr('data-app-title'),
append_to_taskbar: false,
keep_in_taskbar: true,
onClick: function () {
let open_window_count = parseInt($(`.taskbar-item[data-app="${$(ui.item).attr('data-app-name')}"]`).attr('data-open-windows'));
if ( open_window_count === 0 ) {
launch_app({
name: $(ui.item).attr('data-app-name'),
});
} else {
return false;
}
},
});
let el = ($(item).detach());
$(el).insertAfter(ui.item);
$(el).show();
$(ui.item).removeItems();
window.update_taskbar();
}
// only proceed to update DB if the item sorted was a pinned item otherwise no point in updating the taskbar in DB
else if ( $(ui.item).attr('data-keep-in-taskbar') === 'true' ) {
window.update_taskbar();
}
},
});
};
// Function to update taskbar position
window.update_taskbar_position = async function (new_position) {
// Prevent position changes on mobile devices - always keep bottom
if ( isMobile.phone || isMobile.tablet ) {
return;
}
if ( ! TASKBAR_POSITIONS.includes(new_position) ) {
return;
}
// Store the new position
puter.kv.set('taskbar_position', new_position).catch(err => console.warn('Could not save taskbar_position:', err));
window.taskbar_position = new_position;
// Remove old position classes and add new one
$('.taskbar').removeClass('taskbar-position-left taskbar-position-bottom taskbar-position-right');
$('.taskbar').addClass(`taskbar-position-${new_position}`);
// update desktop class, if left or right, add `desktop-taskbar-position-left` or `desktop-taskbar-position-right`
$('.desktop').removeClass('desktop-taskbar-position-left');
$('.desktop').removeClass('desktop-taskbar-position-right');
$('.desktop').addClass(`desktop-taskbar-position-${new_position}`);
// Update desktop height/width calculations based on new position
window.update_desktop_dimensions_for_taskbar();
// Update window positions if needed (for maximized windows)
$('.window[data-is_maximized="1"]').each(function () {
const el_window = this;
window.update_maximized_window_for_taskbar(el_window);
});
// Re-initialize sortable with correct axis
$('.taskbar-sortable').sortable('destroy');
window.make_taskbar_sortable();
// Adjust taskbar item sizes for the new position
setTimeout(() => {
window.adjust_taskbar_item_sizes();
}, 10);
// Reinitialize all taskbar item tooltips with new position
$('.taskbar-item').each(function () {
const $item = $(this);
// Destroy existing tooltip
if ( $item.data('ui-tooltip') ) {
$item.tooltip('destroy');
}
// Helper function to get tooltip position based on taskbar position
function getTooltipPosition () {
const taskbarPosition = window.taskbar_position || 'bottom';
if ( taskbarPosition === 'bottom' ) {
return {
my: 'center bottom-20',
at: 'center top',
};
} else if ( taskbarPosition === 'top' ) {
return {
my: 'center top+20',
at: 'center bottom',
};
} else if ( taskbarPosition === 'left' ) {
return {
my: 'left+20 center',
at: 'right center',
};
} else if ( taskbarPosition === 'right' ) {
return {
my: 'right-20 center',
at: 'left center',
};
}
return {
my: 'center bottom-20',
at: 'center top',
}; // fallback
}
const tooltipPosition = getTooltipPosition();
// Reinitialize tooltip with new position
$item.tooltip({
items: ".taskbar:not(.children-have-open-contextmenu) .taskbar-item:not([data-app='separator'])",
position: {
my: tooltipPosition.my,
at: tooltipPosition.at,
using: function ( position, feedback ) {
$(this).css( position);
$('<div>')
.addClass( 'arrow')
.addClass( feedback.vertical)
.addClass( feedback.horizontal)
.appendTo( this);
},
},
});
});
};
// Function to update desktop dimensions based on taskbar position
window.update_desktop_dimensions_for_taskbar = function () {
const position = window.taskbar_position || 'bottom';
if ( position === 'bottom' ) {
$('.desktop').css({
'height': `calc(100vh - ${window.taskbar_height + window.toolbar_height}px)`,
'width': '100%',
'left': '0',
'top': `${window.toolbar_height}px`,
});
} else if ( position === 'left' ) {
$('.desktop').css({
'height': `calc(100vh - ${window.toolbar_height}px)`,
'width': `calc(100% - ${window.taskbar_height}px)`,
'left': `${window.taskbar_height}px`,
'top': `${window.toolbar_height}px`,
});
} else if ( position === 'right' ) {
$('.desktop').css({
'height': `calc(100vh - ${window.toolbar_height}px)`,
'width': `calc(100% - ${window.taskbar_height}px)`,
'left': '0',
'top': `${window.toolbar_height}px`,
});
}
};
//-------------------------------------------
// Dynamic taskbar item resizing for left/right positions
//-------------------------------------------
window.adjust_taskbar_item_sizes = function () {
const position = window.taskbar_position || 'bottom';
// Only apply to left and right positions
if ( position !== 'left' && position !== 'right' ) {
// Reset to default sizes for bottom position
$('.taskbar .taskbar-item').css({
'width': '40px',
'height': '40px',
'min-width': '40px',
'min-height': '40px',
});
$('.taskbar-icon').css('height', '40px');
return;
}
const taskbar = $('.taskbar')[0];
const taskbarItems = $('.taskbar .taskbar-item:visible');
if ( !taskbar || taskbarItems.length === 0 ) return;
// Get available height (minus padding)
const totalItemsNeeded = taskbarItems.length;
const taskbarHeight = taskbar.clientHeight;
const paddingTop = 20; // from CSS
const paddingBottom = 20; // from CSS
const availableHeight = taskbarHeight - paddingTop - paddingBottom - 180;
// Calculate space needed with default sizes
const defaultItemSize = 40;
const defaultMargin = 5;
const spaceNeededDefault = (totalItemsNeeded * defaultItemSize) + ((totalItemsNeeded - 1) * defaultMargin);
if ( spaceNeededDefault <= availableHeight ) {
// No overflow, use default sizes
taskbarItems.css({
'width': '40px',
'height': '40px',
'min-width': '40px',
'min-height': '40px',
'padding': '6px 5px 10px 5px', // default padding
});
$('.taskbar-icon').css('height', `${defaultItemSize }px`);
$('.taskbar-icon').css('width', '40px');
$('.taskbar-icon > img').css('width', 'auto');
$('.taskbar-icon > img').css('margin', 'auto');
$('.taskbar-icon > img').css('display', 'block');
// Reset margins to default
taskbarItems.css('margin-bottom', '5px');
taskbarItems.last().css('margin-bottom', '0px');
} else {
// Overflow detected, calculate smaller sizes
// Reserve some margin space (minimum 2px between items)
const minMargin = 2;
const marginSpace = (totalItemsNeeded - 1) * minMargin;
const availableForItems = availableHeight - marginSpace;
const newItemSize = Math.floor(availableForItems / totalItemsNeeded);
// Ensure minimum size of 20px
const finalItemSize = Math.max(20, newItemSize);
// Calculate proportional padding based on size ratio
const sizeRatio = finalItemSize / defaultItemSize;
const paddingTop = Math.max(1, Math.floor(6 * sizeRatio));
const paddingRight = Math.max(1, Math.floor(5 * sizeRatio));
const paddingBottom = Math.max(1, Math.floor(10 * sizeRatio));
const paddingLeft = Math.max(1, Math.floor(5 * sizeRatio));
// Apply new sizes and padding
taskbarItems.css({
'width': '40px',
'height': `${finalItemSize }px`,
'min-width': '40px',
'min-height': `${finalItemSize }px`,
'padding': `${paddingTop}px ${paddingRight}px ${paddingBottom}px ${paddingLeft}px`,
});
$('.taskbar-icon').css('height', `${finalItemSize }px`);
$('.taskbar-icon').css('width', '40px');
$('.taskbar-icon > img').css('width', 'auto');
$('.taskbar-icon > img').css('margin', 'auto');
$('.taskbar-icon > img').css('display', 'block');
// Adjust margins
taskbarItems.css('margin-bottom', `${minMargin }px`);
taskbarItems.last().css('margin-bottom', '0px');
}
};
// Hook into existing taskbar functionality
$(document).ready(function () {
// Watch for taskbar item changes
const observer = new MutationObserver(function (mutations) {
mutations.forEach(function (mutation) {
if ( mutation.type === 'childList' || mutation.type === 'attributes' ) {
// Delay to ensure DOM updates are complete
setTimeout(() => {
window.adjust_taskbar_item_sizes();
}, 10);
}
});
});
// Start observing when taskbar is available
const checkTaskbar = setInterval(() => {
const taskbar = document.querySelector('.taskbar-sortable');
if ( taskbar ) {
observer.observe(taskbar, {
childList: true,
attributes: true,
subtree: true,
});
clearInterval(checkTaskbar);
// Initial call
setTimeout(() => {
window.adjust_taskbar_item_sizes();
}, 100);
}
}, 100);
// Also watch for window resize events
window.addEventListener('resize', () => {
setTimeout(() => {
window.adjust_taskbar_item_sizes();
}, 10);
});
});
export default UITaskbar;
+181
View File
@@ -0,0 +1,181 @@
// @vitest-environment jsdom
/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
*
* Puter is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import { afterEach, beforeEach, expect, it, vi } from 'vitest';
import jQuery from '../lib/jquery-3.6.1/jquery-3.6.1.min.js';
vi.mock('../helpers/launchApp.js', () => ({ default: vi.fn() }));
vi.mock('./UIContextMenu.js', () => ({ default: vi.fn() }));
globalThis.$ = globalThis.jQuery = jQuery;
globalThis.i18n = (key) => (key === 'start' ? 'Start' : key);
globalThis.html_encode = (value) => String(value ?? '');
globalThis.isMobile = { phone: false, tablet: false };
await import('../lib/jquery-ui-1.13.2/jquery-ui.js');
const { default: UITaskbar } = await import('./UITaskbar.js');
const app = { name: 'test-app', uuid: 'test-uid', title: 'Test app' };
let launchApps;
let start;
let requests;
afterEach(() => {
$('.popover-launcher, .taskbar').remove();
$(document).off();
$(window).off();
document.body.innerHTML = '';
delete window.launch_apps;
vi.unstubAllGlobals();
vi.useRealTimers();
vi.restoreAllMocks();
});
beforeEach(async () => {
document.body.innerHTML = '<div class="desktop"></div>';
Object.assign(window, {
global_element_id: 0,
taskbar_height: 50,
toolbar_height: 0,
api_origin: 'http://api.test',
auth_token: 'test-token',
icons: {},
user: {},
launch_recent_apps_count: 10,
});
vi.stubGlobal('puter', {
kv: { get: async () => 'bottom' },
fs: { stat: async () => ({ is_empty: true }) },
});
launchApps = { recent: [app], recommended: [] };
requests = [];
$.ajaxTransport('+*', () => {
let complete;
const request = {
send(headers, done) {
complete = done;
},
abort: vi.fn(),
resolve(data) {
complete(
200,
'OK',
{ text: JSON.stringify(data) },
'Content-Type: application/json',
);
},
};
requests.push(request);
return request;
});
await UITaskbar();
requests[0].resolve(launchApps);
start = $('.taskbar-item[data-name="Start"]');
});
it.each([true, false])(
'keeps cached search usable after a timeout, cached=%s',
async (cached) => {
if (!cached) window.launch_apps = [];
vi.spyOn(console, 'error').mockImplementation(() => {});
vi.useFakeTimers();
start.trigger('click');
await vi.advanceTimersByTimeAsync(30000);
expect(requests.at(-1).abort).toHaveBeenCalledOnce();
expect($('.launch-search')).toHaveLength(1);
expect($('.start-app')).toHaveLength(cached ? 1 : 0);
},
);
function deferRefresh() {
return (data) => requests.at(-1).resolve(data);
}
it('refreshes reopened Start without losing cached tiles or search input', async () => {
const survivor = {
name: 'survivor',
uuid: 'survivor-uid',
title: 'Survivor',
};
launchApps.recent.push(survivor);
start.trigger('click');
requests.at(-1).resolve(launchApps);
start.trigger('click');
const resolve = deferRefresh();
start.trigger('click');
const input = $('.launch-search').get(0);
expect(input).toBeDefined();
expect($('.start-app[data-app-name="test-app"]')).toHaveLength(1);
input.value = 'notes';
const onChange = vi.fn();
$(input).on('change', onChange);
resolve({
recent: [survivor],
recommended: [{ name: 'notes', uuid: 'notes-uid', title: 'Notes' }],
});
await vi.waitFor(() =>
expect($('.start-app[data-app-name="notes"]')).toHaveLength(1),
);
expect($('.launch-search').get(0)).toBe(input);
expect(input.value).toBe('notes');
expect(document.activeElement).toBe(input);
expect(onChange).toHaveBeenCalledOnce();
expect($('.start-app[data-app-name="survivor"]')).toHaveLength(1);
expect($('.start-app[data-app-name="test-app"]')).toHaveLength(0);
});
it('cancels closed menus and ignores their late responses', () => {
start.trigger('click');
const old = requests.at(-1);
start.trigger('click');
expect(old.abort).toHaveBeenCalledOnce();
start.trigger('click');
requests.at(-1).resolve({ recent: [], recommended: [] });
old.resolve({ recent: [app], recommended: [] });
expect(window.launch_apps.recent).toHaveLength(0);
expect($('.start-app')).toHaveLength(0);
});
it('cancels the startup request when Start opens', async () => {
requests = [];
document.body.innerHTML = '<div class="desktop"></div>';
await UITaskbar();
const startup = requests[0];
$('.taskbar-item[data-name="Start"]').trigger('click');
expect(startup.abort).toHaveBeenCalledOnce();
});
it('hides apps the backend marks unlaunchable', () => {
start.trigger('click');
requests.at(-1).resolve({
recent: [
app,
{
name: 'reclaimed',
uuid: 'reclaimed-uid',
title: 'Reclaimed',
index_url: null,
privateAccess: { hasAccess: false },
},
],
recommended: [],
});
expect($('.start-app[data-app-name="test-app"]')).toHaveLength(1);
expect($('.start-app[data-app-name="reclaimed"]')).toHaveLength(0);
});
+543
View File
@@ -0,0 +1,543 @@
/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
*
* Puter is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import UIContextMenu from './UIContextMenu.js';
import path from '../lib/path.js';
import launch_app from '../helpers/launchApp.js';
import { user_facing_windows } from '../helpers/windowVisibility.js';
import { appIconFallbackAttr } from '../helpers/appIcon.js';
let tray_item_id = 1;
function UITaskbarItem (options) {
let h = '';
tray_item_id++;
options.sortable = options.sortable ?? true;
options.open_windows_count = options.open_windows_count ?? 0;
options.lock_keep_in_taskbar = options.lock_keep_in_taskbar ?? false;
options.append_to_taskbar = options.append_to_taskbar ?? true;
options.before_trash = options.before_trash ?? false;
// The windows this item stands for: the user's own. An instance another
// app launched in the background is not counted in data-open-windows and
// has no item of its own (see UIWindow's taskbar block) — it must not be
// shown, hidden, or closed through the item its app's OTHER windows own.
const item_windows = () => $(user_facing_windows($(`.window[data-app="${options.app}"]`)));
const element_id = window.global_element_id++;
h += `<div class = "taskbar-item ${options.sortable ? 'taskbar-item-sortable' : ''} disable-user-select"
id = "taskbar-item-${tray_item_id}"
data-taskbar-item-id = "${tray_item_id}"
data-element-id = "${html_encode(element_id)}"
data-name = "${html_encode(options.name)}"
data-app = "${html_encode(options.app)}"
data-keep-in-taskbar = "${html_encode(options.keep_in_taskbar ?? 'false')}"
data-open-windows="${(options.open_windows_count)}"
title = "${html_encode(options.name)}"
style= "${options.style ? html_encode(options.style) : ''}"
>`;
let icon = options.icon ? options.icon : window.icons['app.svg'];
// App icons carry a retry URL (see helpers/appIcon.js); the bundled icons
// below never need one.
let icon_fallback = options.iconFallback ?? '';
if ( options.app === 'explorer' )
{
icon = window.icons['folders.svg'];
icon_fallback = '';
}
// taskbar icon
h += '<div class="taskbar-icon">';
// Don't add img tag for separator
if ( options.app !== 'separator' ) {
h += `<img src="${html_encode(icon)}"${appIconFallbackAttr(icon_fallback)} style="${options.group === 'apps' ? 'filter:none;' : ''}">`;
}
h += '</div>';
// active indicator
if ( options.app !== 'apps' )
{
h += '<span class="active-taskbar-indicator"></span>';
}
h += '</div>';
if ( options.append_to_taskbar ) {
if ( options.before_trash ) {
$('.taskbar-sortable').append(h);
} else {
if ( options.sortable )
{
$('.taskbar-sortable').append(h);
}
else {
// if taskbar-sortable is empty then append before it
if ( $('.taskbar-sortable').children().length === 0 )
{
$('.taskbar').find('.taskbar-sortable').before(h);
}
else
{
$('.taskbar').find('.taskbar-sortable').after(h);
}
}
}
} else {
$('body').prepend(h);
}
const el_taskbar_item = document.querySelector(`#taskbar-item-${tray_item_id}`);
// fade in the taskbar item
$(el_taskbar_item).show(50);
// Adjust taskbar item sizes after adding new item
if ( window.adjust_taskbar_item_sizes ) {
setTimeout(() => {
window.adjust_taskbar_item_sizes();
}, 100);
}
$(el_taskbar_item).on('click', function (e) {
e.preventDefault();
e.stopPropagation();
// Don't handle clicks for separators
if ( options.app === 'separator' ) {
return;
}
// if this is for the launcher popover, and it's mobile, and has-open-popover, close the popover
if ( $(el_taskbar_item).attr('data-name') === 'Start'
&& (isMobile.phone || isMobile.tablet) && $(el_taskbar_item).hasClass('has-open-popover') ) {
$('.popover').remove();
return;
}
// If this item has an open context menu, don't do anything
if ( $(el_taskbar_item).hasClass('has-open-contextmenu') )
{
return;
}
if ( options.onClick === undefined || options.onClick(el_taskbar_item) === false ) {
// re-show each window in this app group
item_windows().showWindow();
}
});
$(el_taskbar_item).on('contextmenu taphold', function (e) {
// seems like the only way to stop sortable is to destroy it
if ( options.sortable ) {
$('.taskbar-sortable').sortable('destroy');
}
e.preventDefault();
e.stopPropagation();
// Don't show context menu for separators
if ( options.app === 'separator' ) {
return;
}
// If context menu is disabled on this item, return
if ( options.disable_context_menu )
{
return;
}
// don't allow context menu to open if it's already open
if ( $(el_taskbar_item).hasClass('has-open-contextmenu') )
{
return;
}
const menu_items = [];
const open_windows = parseInt($(el_taskbar_item).attr('data-open-windows'));
// -------------------------------------------
// List of open windows belonging to this app
// -------------------------------------------
item_windows().each(function () {
menu_items.push({
html: $(this).find('.window-head-title').html(),
val: $(this).attr('data-id'),
onClick: function (e) {
$(`.window[data-id="${e.value}"]`).showWindow();
},
});
});
// -------------------------------------------
// divider
// -------------------------------------------
if ( menu_items.length > 0 )
{
menu_items.push('-');
}
//------------------------------------------
// New Window
//------------------------------------------
if ( options.app && options.app !== 'trash' ) {
menu_items.push({
html: i18n('new_window'),
val: $(this).attr('data-id'),
onClick: function () {
// is trash?
launch_app({
name: options.app,
maximized: (isMobile.phone || isMobile.tablet),
});
},
});
}
//------------------------------------------
// Open Trash
//------------------------------------------
else if ( options.app && options.app === 'trash' ) {
menu_items.push({
html: i18n('open_trash'),
val: $(this).attr('data-id'),
onClick: function () {
launch_app({
name: options.app,
path: window.trash_path,
maximized: (isMobile.phone || isMobile.tablet),
});
},
});
}
//------------------------------------------
// Empty Trash
//------------------------------------------
if ( options.app && options.app === 'trash' ) {
// divider
menu_items.push('-');
// Empty Trash menu item
menu_items.push({
html: i18n('empty_trash'),
val: $(this).attr('data-id'),
onClick: async function () {
window.empty_trash();
},
});
}
//------------------------------------------
// Remove from Taskbar
//------------------------------------------
if ( options.keep_in_taskbar && !options.lock_keep_in_taskbar ) {
menu_items.push({
html: i18n('remove_from_taskbar'),
val: $(this).attr('data-id'),
onClick: function () {
$(el_taskbar_item).attr('data-keep-in-taskbar', 'false');
if ( $(el_taskbar_item).attr('data-open-windows') === '0' ) {
window.remove_taskbar_item(el_taskbar_item);
}
window.update_taskbar();
options.keep_in_taskbar = false;
},
});
}
//------------------------------------------
// Keep in Taskbar
//------------------------------------------
else if ( ! options.keep_in_taskbar ) {
menu_items.push({
html: i18n('keep_in_taskbar'),
val: $(this).attr('data-id'),
onClick: function () {
$(el_taskbar_item).attr('data-keep-in-taskbar', 'true');
window.update_taskbar();
options.keep_in_taskbar = true;
},
});
}
if ( open_windows > 0 ) {
// -------------------------------------------
// divider
// -------------------------------------------
menu_items.push('-');
// -------------------------------------------
// Show All Windows
// -------------------------------------------
menu_items.push({
html: i18n('show_all_windows'),
onClick: function () {
item_windows().showWindow();
},
});
// -------------------------------------------
// Hide All Windows
// -------------------------------------------
menu_items.push({
html: i18n('hide_all_windows'),
onClick: function () {
if ( open_windows > 0 )
{
item_windows().hideWindow();
}
},
});
// -------------------------------------------
// Close All Windows
// -------------------------------------------
menu_items.push({
html: i18n('close_all_windows'),
onClick: function () {
// "All" means the windows this item lists — a background
// helper belongs to the app running it, and goes when
// that app does (UIWindow's close path).
item_windows().close();
},
});
}
const pos = el_taskbar_item.getBoundingClientRect();
UIContextMenu({
parent_element: el_taskbar_item,
position: getContextMenuPosition(pos),
items: menu_items,
});
return false;
});
// Helper function to get tooltip position based on taskbar position
function getTooltipPosition () {
const taskbarPosition = window.taskbar_position || 'bottom';
if ( taskbarPosition === 'bottom' ) {
return {
my: 'center bottom-20',
at: 'center top',
};
} else if ( taskbarPosition === 'top' ) {
return {
my: 'center top+20',
at: 'center bottom',
};
} else if ( taskbarPosition === 'left' ) {
return {
my: 'left+20 center',
at: 'right center',
};
} else if ( taskbarPosition === 'right' ) {
return {
my: 'right-20 center',
at: 'left center',
};
}
return {
my: 'center bottom-20',
at: 'center top',
}; // fallback
}
// Helper function to get context menu position based on taskbar position
function getContextMenuPosition (pos) {
const taskbarPosition = window.taskbar_position || 'bottom';
if ( taskbarPosition === 'bottom' ) {
return {
top: pos.top - 15,
left: pos.left + 5,
};
} else if ( taskbarPosition === 'top' ) {
return {
top: pos.bottom + 15,
left: pos.left + 5,
};
} else if ( taskbarPosition === 'left' ) {
return {
top: pos.top + 5,
left: pos.right + 5,
};
} else if ( taskbarPosition === 'right' ) {
return {
top: pos.top + 5,
left: pos.left - 20,
};
}
return {
top: pos.top - 15,
left: pos.left + 5,
}; // fallback
}
const tooltipPosition = getTooltipPosition();
$(el_taskbar_item).tooltip({
// only show tooltip if desktop is not selectable active
items: ".desktop:not(.desktop-selectable-active) .taskbar:not(.children-have-open-contextmenu) .taskbar-item:not([data-app='separator'])",
position: {
my: tooltipPosition.my,
at: tooltipPosition.at,
using: function ( position, feedback ) {
$(this).css( position);
$('<div>')
.addClass( 'arrow')
.addClass( feedback.vertical)
.addClass( feedback.horizontal)
.appendTo( this);
},
},
});
// --------------------------------------------------------
// Droppable
// --------------------------------------------------------
// Don't make separators droppable
if ( options.app !== 'separator' ) {
$(el_taskbar_item).droppable({
accept: '.item',
// 'pointer' is very important because of active window tracking is based on the position of cursor.
tolerance: 'pointer',
drop: async function ( event, ui ) {
// Check if hovering over an item that is VISIBILE
if ( $(event.target).closest('.window').attr('data-id') !== $(window.mouseover_window).attr('data-id') )
{
return;
}
// If ctrl is pressed and source is Trashed, cancel whole operation
if ( event.ctrlKey && path.dirname($(ui.draggable).attr('data-path')) === window.trash_path )
{
return;
}
const items_to_move = [];
// First item
items_to_move.push(ui.draggable);
// All subsequent items
const cloned_items = document.getElementsByClassName('item-selected-clone');
for ( let i = 0; i < cloned_items.length; i++ ) {
const source_item = document.getElementById(`item-${ $(cloned_items[i]).attr('data-id')}`);
if ( source_item !== null )
{
items_to_move.push(source_item);
}
}
// --------------------------------------------------------
// If `options.onItemsDrop` is set, call it with the items to move
//--------------------------------------------------------
if ( options.onItemsDrop && typeof options.onItemsDrop === 'function' ) {
options.onItemsDrop(items_to_move);
return;
}
// --------------------------------------------------------
// If dropped on an app, open the app with the dropped item as an argument
//--------------------------------------------------------
else if ( options.app ) {
// an array that hold the items to sign
const items_to_sign = [];
// prepare items to sign
for ( let i = 0; i < items_to_move.length; i++ ) {
items_to_sign.push({
name: $(items_to_move[i]).attr('data-name'),
uid: $(items_to_move[i]).attr('data-uid'),
action: 'write',
path: $(items_to_move[i]).attr('data-path'),
});
}
// open each item
for ( let i = 0; i < items_to_sign.length; i++ ) {
const item = items_to_sign[i];
launch_app({
name: options.app,
file_path: item.path,
// app_obj: open_item_meta.suggested_apps[0],
window_title: item.name,
file_uid: item.uid,
// file_signature: item,
});
}
// deselect dragged item
for ( let i = 0; i < items_to_move.length; i++ )
{
$(items_to_move[i]).removeClass('item-selected');
}
}
// Unselect directory/app if item is dropped
if ( options.is_dir || options.app ) {
$(el_taskbar_item).removeClass('active');
$(el_taskbar_item).tooltip('close');
$('.ui-draggable-dragging .item-name, .item-selected-clone .item-name').css('opacity', 'initial');
$('.item-container').removeClass('item-container-transparent-border');
}
// Re-enable droppable on all item-container
$('.item-container').droppable('enable');
return false;
},
over: function (event, ui) {
// Check hovering over an item that is VISIBILE
const $event_parent_win = $(event.target).closest('.window');
if ( $event_parent_win.length > 0 && $event_parent_win.attr('data-id') !== $(window.mouseover_window).attr('data-id') )
{
return;
}
// Don't do anything if the dragged item is NOT a UIItem
if ( ! $(ui.draggable).hasClass('item') )
{
return;
}
// If this is a directory or an app, and an item was dragged over it, highlight it.
if ( options.is_dir || options.app ) {
$(el_taskbar_item).addClass('active');
// show tooltip of this item
$(el_taskbar_item).tooltip().mouseover();
// make item name partially transparent
$('.ui-draggable-dragging .item-name, .item-selected-clone .item-name').css('opacity', 0.1);
// remove all item-container active borders
$('.item-container').addClass('item-container-transparent-border');
}
// Disable all window bodies
$('.item-container').droppable( 'disable');
},
out: function (event, ui) {
// Don't do anything if the dragged item is NOT a UIItem
if ( ! $(ui.draggable).hasClass('item') )
{
return;
}
// Unselect directory/app if item is dragged out
if ( options.is_dir || options.app ) {
$(el_taskbar_item).removeClass('active');
$(el_taskbar_item).tooltip('close');
$('.ui-draggable-dragging .item-name, .item-selected-clone .item-name').css('opacity', 'initial');
$('.item-container').removeClass('item-container-transparent-border');
}
$('.item-container').droppable( 'enable');
},
});
}
return el_taskbar_item;
}
export default UITaskbarItem;
-123
View File
@@ -1,123 +0,0 @@
// @vitest-environment jsdom
/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
*
* Puter is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import jQuery from '../lib/jquery-3.6.1/jquery-3.6.1.min.js';
vi.mock('../helpers/launchApp.js', () => ({ default: vi.fn() }));
globalThis.$ = globalThis.jQuery = jQuery;
globalThis.i18n = (key) => key;
globalThis.html_encode = (value) => String(value ?? '');
globalThis.isMobile = { phone: false, tablet: false };
globalThis.def = globalThis.def ?? ((value) => value);
await import('../lib/jquery-ui-1.13.2/jquery-ui.js');
// The page loads this plugin from a vendored script; nothing here drops files.
$.fn.dragster = function () {
return this;
};
const { default: UIWindow } = await import('./UIWindow.js');
const openWindow = (options = {}) => UIWindow({
title: 'Notes',
app: 'notes',
body_content: '<p>hello</p>',
width: 400,
height: 300,
...options,
});
/** Opens the window head's context menu and returns its item labels. */
const headMenuLabels = (el_window) => {
$(el_window).find('.window-head').trigger('contextmenu');
return $('.context-menu .contextmenu-label').map((_, el) => $(el).text().toLowerCase()).get();
};
beforeEach(() => {
document.body.innerHTML = '<div class="desktop"></div>';
Object.assign(window, {
global_element_id: 0,
window_counter: 0,
last_window_zindex: 1,
window_stack: [],
toolbar_height: 0,
icons: {},
uuidv4: () => crypto.randomUUID(),
is_dashboard_mode: false,
is_fullpage_mode: false,
is_embedded: false,
});
});
afterEach(() => {
$(document).off();
document.body.innerHTML = '';
});
describe('minimize', () => {
it('is not offered on the desktop, where nothing could restore the window', async () => {
const el_window = await openWindow();
expect($(el_window).find('.window-minimize-btn').length).toBe(0);
const labels = headMenuLabels(el_window);
expect(labels.some((label) => label === 'maximize')).toBe(true);
expect(labels.some((label) => label === 'minimize')).toBe(false);
});
it('is offered on the dashboard, which restores the window from its tile', async () => {
window.is_dashboard_mode = true;
const el_window = await openWindow();
expect($(el_window).find('.window-minimize-btn').length).toBe(1);
expect(headMenuLabels(el_window).some((label) => label === 'minimize')).toBe(true);
});
it('hides the window in place and brings it back', async () => {
window.is_dashboard_mode = true;
const el_window = await openWindow();
const before = { top: el_window.style.top, left: el_window.style.left };
await $(el_window).hideWindow();
expect($(el_window).attr('data-is_minimized')).toBe('true');
expect($(el_window).attr('data-minimized_in_place')).toBe('1');
await $(el_window).showWindow({ no_history: true });
expect($(el_window).attr('data-is_minimized')).toBe('false');
expect({ top: el_window.style.top, left: el_window.style.left }).toEqual(before);
});
});
describe('backdrop', () => {
const backdropZ = (el_window) => Number($(el_window).closest('.window-backdrop').css('z-index'));
it('stays above ordinary windows on the desktop', async () => {
const el_window = await openWindow({ backdrop: true });
expect(backdropZ(el_window)).toBeGreaterThan(window.last_window_zindex + 1000);
});
it('stacks at the window counter on the dashboard', async () => {
window.is_dashboard_mode = true;
const el_window = await openWindow({ backdrop: true });
expect(backdropZ(el_window)).toBeLessThanOrEqual(window.last_window_zindex);
});
});
+518 -248
View File
@@ -20,6 +20,7 @@
import UIAlert from './UIAlert.js';
import UIContextMenu from './UIContextMenu.js';
import path from '../lib/path.js';
import UITaskbarItem from './UITaskbarItem.js';
import UIAuthLogin from './Auth/UIAuthLogin.js';
import UIWindowItemProperties from './UIWindowItemProperties.js';
import new_context_menu_item from '../helpers/newContextMenuItem.js';
@@ -37,8 +38,6 @@ import { is_window_hidden, is_unseen_background_window, user_facing_windows } fr
const el_body = document.getElementsByTagName('body')[0];
const SNAP_PLACEHOLDER_DELAY_MS = 600; // delay before showing placeholder in any snap zone
// Above any z-index an ordinary desktop window reaches in practice.
const DESKTOP_BACKDROP_MIN_ZINDEX = 99999;
async function UIWindow (options) {
const win_id = window.global_element_id++;
@@ -106,7 +105,7 @@ async function UIWindow (options) {
options.is_resizable = false;
}
// In the embedded/fullpage mode every window is on top since there is nothing to switch between windows
// In the embedded/fullpage mode every window is on top since there is no taskbar to switch between windows
// if user has specifically asked for this window to NOT stay on top, honor it.
if ( (window.is_embedded || window.is_fullpage_mode) && !options.parent_uuid && options.stay_on_top !== false )
{
@@ -116,11 +115,11 @@ async function UIWindow (options) {
options.stay_on_top = options.stay_on_top ?? false;
options.is_saveFileDialog = options.is_saveFileDialog ?? false;
// Only the dashboard can restore a minimized window, from the app's tile.
options.show_minimize_button = (options.show_minimize_button ?? true) && !!window.is_dashboard_mode;
options.show_minimize_button = options.show_minimize_button ?? true;
options.on_close = options.on_close ?? undefined;
options.parent_uuid = options.parent_uuid ?? null;
options.selectable_body = (options.selectable_body === undefined || options.selectable_body === true) ? true : false;
options.show_in_taskbar = options.show_in_taskbar ?? true;
options.show_maximize_button = options.show_maximize_button ?? true;
options.single_instance = options.single_instance ?? false;
options.sort_by = options.sort_by ?? 'name';
@@ -540,11 +539,24 @@ async function UIWindow (options) {
// backdrop
if ( options.backdrop ) {
// On the desktop a backdrop stays above every ordinary window, even one
// focused after it opened, so the dialog it holds stays modal.
const backdrop_zindex = (options.stay_on_top || window.is_dashboard_mode || window.is_fullpage_mode)
? zindex
: Math.max(zindex, DESKTOP_BACKDROP_MIN_ZINDEX);
let backdrop_zindex;
// backdrop should also cover over taskbar
let taskbar_zindex = $('.taskbar').css('z-index');
if ( taskbar_zindex === null || taskbar_zindex === undefined )
{
backdrop_zindex = zindex;
}
else {
taskbar_zindex = parseInt(taskbar_zindex);
backdrop_zindex = taskbar_zindex > zindex ? taskbar_zindex : zindex;
}
// dominant backdrop will cover over toolbar as well
if ( options.backdrop_covers_toolbar )
{
backdrop_zindex = 999999;
}
h = `<div class="window-backdrop" style="z-index:${backdrop_zindex};">${ h }</div>`;
}
@@ -587,6 +599,56 @@ async function UIWindow (options) {
const el_directorypicker_select_btn = document.querySelector(`#window-${win_id} .directorypicker-select-btn`);
const el_window_filedialog_upload_here = document.querySelector(`#window-${win_id} .window-filedialog-upload-here`);
// Add Taskbar Item
// data-in_taskbar records that this window is one of the item's
// data-open-windows, so the close path only decrements a count this
// window actually added to (see the close handler) — the two must stay
// in step, and a window that never took an item must not take one away.
const add_taskbar_item = () => {
$(el_window).attr('data-in_taskbar', '1');
// add icon if there is no similar app already open
if ( $(`.taskbar-item[data-app="${options.app}"]`).length === 0 ) {
UITaskbarItem({
icon: options.icon,
name: options.title,
app: options.app,
open_windows_count: 1,
before_trash: true,
onClick: function () {
let open_window_count = parseInt($(`.taskbar-item[data-app="${options.app}"]`).attr('data-open-windows'));
if ( open_window_count === 0 ) {
launch_app({
name: options.app,
});
} else {
return false;
}
},
});
if ( options.app )
{
$(`.taskbar-item[data-app="${options.app}"] .active-taskbar-indicator`).show();
}
} else {
if ( options.app ) {
$(`.taskbar-item[data-app="${options.app}"]`).attr('data-open-windows', parseInt($(`.taskbar-item[data-app="${options.app}"]`).attr('data-open-windows')) + 1);
$(`.taskbar-item[data-app="${options.app}"] .active-taskbar-indicator`).show();
}
}
};
if ( !options.is_openFileDialog && !options.is_saveFileDialog && !options.is_directoryPicker && options.show_in_taskbar ) {
// A window started hidden by a background launch gets no taskbar item
// yet: it runs for the app that launched it, and an item would both
// advertise and hand out an instance the user never asked for. The
// item is what the window earns the moment it first becomes visible
// — makeWindowVisible calls this, whether the app showed itself with
// puter.ui.showWindow() or something else revealed it. An app that is
// ALWAYS windowless never reaches here: launch_app leaves
// show_in_taskbar false for it, so it keeps having no item at all.
if ( options.launched_hidden ) el_window._add_taskbar_item = add_taskbar_item;
else add_taskbar_item();
}
if ( el_window_filedialog_upload_here ) {
el_window_filedialog_upload_here.addEventListener('click', function () {
window.init_upload_using_dialog(el_window_body, `${$(el_window).attr('data-path') }/`);
@@ -611,7 +673,8 @@ async function UIWindow (options) {
// shrink icon
$(el_window).find('.window-scale-btn>img').attr('src', window.icons['scale-down-3.svg']);
window.update_maximized_window(el_window);
// Use taskbar position-aware window positioning
window.update_maximized_window_for_taskbar(el_window);
}
// when a window is created, focus is brought to it and
@@ -1889,6 +1952,7 @@ async function UIWindow (options) {
snap_trigger_timeout = undefined;
}
hideSnapPlaceholder();
$('.toolbar').css('pointer-events', 'none');
// if window is snapped, unsnap it and reset its position to where it was before snapping
if ( options.is_resizable && window_is_snapped ) {
window_is_snapped = false;
@@ -1983,12 +2047,14 @@ async function UIWindow (options) {
$(el_window_app_iframe).css('pointer-events', 'all');
$('.window').css('pointer-events', 'initial');
$('.toolbar').css('pointer-events', 'auto');
if ( options.is_resizable && snap_placeholder_active && !window_is_snapped ) {
window_will_snap = true;
$(window_snap_placeholder).css('padding', 0);
setTimeout(function () {
// Get taskbar-aware snap dimensions for final positioning
const snapDims = getSnapDimensions();
// snap to w
@@ -2075,22 +2141,39 @@ async function UIWindow (options) {
}
// if window is dropped outside the available area, move it back in
// the '- 30' is to account for the window head
const maxTop = window.innerHeight - 30;
// Bottom boundary (account for taskbar position)
const taskbar_position = window.taskbar_position || 'bottom';
let maxTop;
if ( taskbar_position === 'bottom' ) {
maxTop = window.innerHeight - window.taskbar_height - 30;
} else {
maxTop = window.innerHeight - 30;
}
// the lst '- 30' is to account for the window head
if ( $(el_window).position().top > maxTop && !window_will_snap ) {
$(el_window).animate({
top: maxTop - 30,
}, 100);
}
// if window is dropped too far to the right, move it left
const maxLeft = window.innerWidth - 50;
let maxLeft;
if ( taskbar_position === 'right' ) {
maxLeft = window.innerWidth - window.taskbar_height - 50;
} else {
maxLeft = window.innerWidth - 50;
}
if ( $(el_window).position().left > maxLeft && !window_will_snap ) {
$(el_window).animate({
left: maxLeft,
}, 100);
}
// if window is dropped too far to the left, move it right
const minLeft = -$(el_window).width() + 150;
let minLeft;
if ( taskbar_position === 'left' ) {
minLeft = window.taskbar_height - $(el_window).width() + 150;
} else {
minLeft = -$(el_window).width() + 150;
}
if ( $(el_window).position().left < minLeft && !window_will_snap ) {
$(el_window).animate({
left: minLeft,
@@ -2309,14 +2392,12 @@ async function UIWindow (options) {
window.scale_window(el_window);
},
});
if ( window.is_dashboard_mode ) {
menu_items.push({
html: i18n('minimize'),
onClick: function () {
minimize_window(el_window);
},
});
}
menu_items.push({
html: i18n('minimize'),
onClick: function () {
minimize_window(el_window);
},
});
menu_items.push({
html: 'Advanced',
items: [
@@ -2592,7 +2673,7 @@ async function UIWindow (options) {
left = left > (window.innerWidth - window_width) ? (window.innerWidth - window_width) : left;
let top = window.mouseY;
top = top > (window.innerHeight - (window_height + window.toolbar_height)) ? (window.innerHeight - (window_height + window.toolbar_height)) : top;
top = top > (window.innerHeight - (window_height + window.taskbar_height + window.toolbar_height)) ? (window.innerHeight - (window_height + window.taskbar_height + window.toolbar_height)) : top;
UIWindowItemProperties(
options.title,
@@ -2816,6 +2897,10 @@ $(document).on('click', '.window-sidebar-item', async function (e) {
// todo
// sort_by: $(el_item).attr('data-sort_by'),
app: 'explorer',
// top: options.maximized ? 0 : undefined,
// left: options.maximized ? 0 : undefined,
// height: options.maximized ? `calc(100% - ${window.taskbar_height + 1}px)` : undefined,
// width: options.maximized ? `100%` : undefined,
});
}
// update window path only if it's a new path AND no ctrl/cmd key pressed
@@ -2876,6 +2961,10 @@ $(document).on('contextmenu taphold', '.window-sidebar-item', function (event) {
// todo
// sort_by: $(el_item).attr('data-sort_by'),
app: 'explorer',
// top: options.maximized ? 0 : undefined,
// left: options.maximized ? 0 : undefined,
// height: options.maximized ? `calc(100% - ${window.taskbar_height + 1}px)` : undefined,
// width: options.maximized ? `100%` : undefined,
});
},
},
@@ -2888,7 +2977,7 @@ $(document).on('dblclick', '.window .ui-resizable-handle', function (e) {
let el_window = $(this).closest('.window');
// bottom
if ( $(this).hasClass('ui-resizable-s') ) {
let height = window.innerHeight - $(el_window).position().top - 6;
let height = window.innerHeight - $(el_window).position().top - window.taskbar_height - 6;
$(el_window).height(height);
}
@@ -2918,7 +3007,7 @@ $(document).on('dblclick', '.window .ui-resizable-handle', function (e) {
// bottom left
else if ( $(this).hasClass('ui-resizable-sw') ) {
let width = $(el_window).width() + $(el_window).position().left;
let height = window.innerHeight - $(el_window).position().top - 6;
let height = window.innerHeight - $(el_window).position().top - window.taskbar_height - 6;
$(el_window).css({
width: width,
height: height,
@@ -2928,7 +3017,7 @@ $(document).on('dblclick', '.window .ui-resizable-handle', function (e) {
// bottom right
else if ( $(this).hasClass('ui-resizable-se') ) {
let width = window.innerWidth - $(el_window).position().left;
let height = window.innerHeight - $(el_window).position().top - 6;
let height = window.innerHeight - $(el_window).position().top - window.taskbar_height - 6;
$(el_window).css({
width: width,
height: height,
@@ -3584,7 +3673,30 @@ $.fn.close = async function (options) {
let window_uuid = $(this).attr('data-element_uuid');
// remove all instances of win_id from window.window_stack
window.window_stack = window.window_stack.filter(id => id !== win_id);
// if a fullpage window is closed, show the desktop
// taskbar update — only for a window that IS one of the item's
// open windows (data-in_taskbar, stamped when it took its place
// in the count). A window that never counted must not decrement:
// an unseen background instance closing alongside the user's own
// window would otherwise zero the count and take the item away
// while that window is still open.
if ( $(this).attr('data-in_taskbar') === '1' ) {
let open_window_count = parseInt($(`.taskbar-item[data-app="${$(this).attr('data-app')}"]`).attr('data-open-windows'));
// update open window count of corresponding taskbar item
if ( open_window_count > 0 ) {
$(`.taskbar-item[data-app="${$(this).attr('data-app')}"]`).attr('data-open-windows', open_window_count - 1);
}
// decide whether to remove taskbar item
if ( open_window_count === 1 ) {
$(`.taskbar-item[data-app="${$(this).attr('data-app')}"] .active-taskbar-indicator`).hide();
window.remove_taskbar_item($(`.taskbar-item[data-app="${$(this).attr('data-app')}"][data-keep-in-taskbar="false"]`));
}
// if no more windows of this app are open, remove taskbar item
if ( open_window_count - 1 === 0 )
{
$(`.taskbar-item[data-app="${$(this).attr('data-app')}"] .active-taskbar-indicator`).hide();
}
}
// if a fullpage window is closed, show desktop and taskbar
if ( $(this).attr('data-is_fullpage') === '1' ) {
window.exit_fullpage_mode();
}
@@ -3732,7 +3844,13 @@ window.scale_window = (el_window) => {
// shrink icon
$(el_window).find('.window-scale-btn>img').attr('src', window.icons['scale-down-3.svg']);
window.update_maximized_window(el_window);
// Use taskbar position-aware window positioning
window.update_maximized_window_for_taskbar(el_window);
// hide toolbar
if ( !isMobile.phone && !isMobile.tablet ) {
window.hide_toolbar();
}
}
//shrink
else {
@@ -3856,12 +3974,19 @@ $.fn.makeWindowVisible = function (options) {
if ( $(this).hasClass('window') ) {
// Seen by the user, so no longer a window that exists purely to
// serve whoever launched it: it outlives its launcher from here on
// (see the close path's cleanup of background children), and the
// dashboard tile shows it as running.
// (see the close path's cleanup of background children), and it
// becomes a window the user can act on — hence the taskbar item
// its launch deferred, and the dashboard tile's running dot.
// Both happen BEFORE the window shows: focusWindow() below marks
// the app's taskbar item active, which needs the item to exist.
const was_launched_hidden = $(this).attr('data-launched_hidden') === '1';
$(this).removeAttr('data-launched_hidden');
if ( was_launched_hidden && window.is_dashboard_mode && $(this).attr('data-app') ) {
document.dispatchEvent(new CustomEvent('dashboard-app-windows-changed'));
if ( was_launched_hidden ) {
this._add_taskbar_item?.();
delete this._add_taskbar_item;
if ( window.is_dashboard_mode && $(this).attr('data-app') ) {
document.dispatchEvent(new CustomEvent('dashboard-app-windows-changed'));
}
}
$(this).show();
@@ -3908,8 +4033,13 @@ $.fn.makeWindowInvisible = async function (options) {
$.fn.showWindow = async function (options) {
$(this).each(async function () {
if ( $(this).hasClass('window') ) {
// A window hidden by puter.ui.hideWindow() is not minimized and
// kept its geometry, so un-hiding it is the whole job.
// A window hidden by puter.ui.hideWindow() is not minimized: it
// kept its geometry and has no data-orig-* to restore, so every
// path below (all of which un-minimize) would leave it hidden —
// and stamp NaN geometry on it from the absent attributes. Simply
// un-hiding it is the whole job, and the inverse of what hid it.
// This is what makes the taskbar item a real handle on a window
// the user cannot currently see.
if ( is_window_hidden(this) ) {
$(this).makeWindowVisible();
return;
@@ -3927,63 +4057,92 @@ $.fn.showWindow = async function (options) {
? 99999999 + (++window.last_window_zindex)
: ++window.last_window_zindex);
// hideWindow hid the window in place, so its geometry was never
// disturbed. If the app's tile is visible on the Apps tab's current
// page, grow the window back out of it (the reverse of hideWindow's
// zoom-to-tile morph); otherwise just fade it back in.
if ( $(el_window).attr('data-minimized_in_place') !== '1' ) return;
// A window minimized with no taskbar to animate toward (dashboard
// mode) was hidden in place by hideWindow — its geometry was
// never disturbed. If the app's tile is visible on the Apps tab's
// current page, grow the window back out of it (the reverse of
// hideWindow's zoom-to-tile morph); otherwise just fade it back
// in as before. (The explicit flag is used because data-orig-*
// can't distinguish the two minimize paths: drag/maximize
// handlers set it too.)
if ( $(el_window).attr('data-minimized_in_place') === '1' ) {
$(el_window).attr({
'data-is_minimized': false,
'data-minimized_in_place': '0',
});
// On screen again (Back, tile click, Forward), so it is no
// longer minimized-because-a-child-took-over: closing that
// child must not now send the user to the dashboard.
$(el_window).removeAttr('data-minimized_for_child');
$(el_window).css('z-index', raised_zindex());
const reduce_motion = window.matchMedia
&& window.matchMedia('(prefers-reduced-motion: reduce)').matches;
// Skip the morph while another morph still owns the window's
// inline styles (reopen mid-minimize-zoom): clearing the
// flags above already makes that animation's cleanup leave
// the window visible and restored, same as before.
const tile = (reduce_motion
|| $(el_window).attr('data-window_morphing') === '1')
? null
: dashboard_tile_in_view($(el_window).attr('data-app'));
let morphed = false;
if ( tile ) {
// The morph needs the window displayed and laid out to
// measure it; no paint happens between this show() and
// the morph's start state, so nothing flashes.
const was_hidden = ! $(el_window).is(':visible');
if ( was_hidden ) $(el_window).show();
// The lighter cut of the launch morph — window half
// only, on a shorter path — so un-minimizing reads as
// the window coming back out of the tile, not the app
// launching again (no icon flourish, no launch pacing).
morphed = morph_window_from_tile(el_window, tile, {
icon_half: false,
duration: 0.3,
});
if ( ! morphed && was_hidden ) $(el_window).hide();
}
if ( ! morphed ) $(el_window).fadeIn(150);
// Restores come back with the control drawer collapsed —
// whatever state it was minimized in (headless dashboard
// windows only; no-op otherwise).
el_window._dashboard_drawer_collapse?.();
// A restore re-claims the URL for this app — except when
// the restore was DRIVEN by a history traversal (popstate
// passes no_history: the entry is already current).
if ( ! options?.no_history
&& $(el_window).attr('data-update_window_url') === 'true'
&& $(el_window).attr('data-app') !== 'explorer' ) {
push_dashboard_app_url($(el_window).attr('data-app'), $(el_window).attr('data-name'));
}
setTimeout(() => {
$(this).focusWindow();
}, 80);
return;
}
$(el_window).css({
'transition': 'top 0.2s, left 0.2s, bottom 0.2s, right 0.2s, width 0.2s, height 0.2s',
top: `${$(el_window).attr('data-orig-top') }px`,
left: `${$(el_window).attr('data-orig-left') }px`,
width: `${$(el_window).attr('data-orig-width') }px`,
height: `${$(el_window).attr('data-orig-height') }px`,
});
$(el_window).css('z-index', raised_zindex());
$(el_window).attr({
'data-is_minimized': false,
'data-minimized_in_place': '0',
});
// On screen again (Back, tile click, Forward), so it is no
// longer minimized-because-a-child-took-over: closing that
// child must not now send the user to the dashboard.
$(el_window).removeAttr('data-minimized_for_child');
$(el_window).css('z-index', raised_zindex());
const reduce_motion = window.matchMedia
&& window.matchMedia('(prefers-reduced-motion: reduce)').matches;
// Skip the morph while another morph still owns the window's
// inline styles (reopen mid-minimize-zoom): clearing the
// flags above already makes that animation's cleanup leave
// the window visible and restored, same as before.
const tile = (reduce_motion
|| $(el_window).attr('data-window_morphing') === '1')
? null
: dashboard_tile_in_view($(el_window).attr('data-app'));
let morphed = false;
if ( tile ) {
// The morph needs the window displayed and laid out to
// measure it; no paint happens between this show() and
// the morph's start state, so nothing flashes.
const was_hidden = ! $(el_window).is(':visible');
if ( was_hidden ) $(el_window).show();
// The lighter cut of the launch morph — window half
// only, on a shorter path — so un-minimizing reads as
// the window coming back out of the tile, not the app
// launching again (no icon flourish, no launch pacing).
morphed = morph_window_from_tile(el_window, tile, {
icon_half: false,
duration: 0.3,
});
if ( ! morphed && was_hidden ) $(el_window).hide();
}
if ( ! morphed ) $(el_window).fadeIn(150);
// Restores come back with the control drawer collapsed —
// whatever state it was minimized in (headless dashboard
// windows only; no-op otherwise).
el_window._dashboard_drawer_collapse?.();
// A restore re-claims the URL for this app — except when
// the restore was DRIVEN by a history traversal (popstate
// passes no_history: the entry is already current).
if ( ! options?.no_history
&& $(el_window).attr('data-update_window_url') === 'true'
&& $(el_window).attr('data-app') !== 'explorer' ) {
push_dashboard_app_url($(el_window).attr('data-app'), $(el_window).attr('data-name'));
}
setTimeout(() => {
$(this).focusWindow();
}, 80);
// remove `transitions` a good while after setting css to make sure
// it doesn't interfere with an ongoing animation
setTimeout(() => {
$(el_window).css('transition', 'none');
}, 250);
}
});
return this;
@@ -4105,6 +4264,7 @@ $.fn.focusWindow = function (event) {
document.title = $(this).attr('data-name');
}
}
$(`.taskbar .taskbar-item[data-app="${$(this).attr('data-app')}"]`).addClass('taskbar-item-active');
} else {
$('.window').find('.item-selected').addClass('item-blurred');
$('.desktop').find('.item-blurred').removeClass('item-blurred');
@@ -5086,167 +5246,230 @@ function morph_window_from_tile (el_window, tile, morph_options = {}) {
$.fn.hideWindow = async function (options) {
$(this).each(async function () {
if ( $(this).hasClass('window') ) {
// If the app's tile is visible on the dashboard's Apps tab, shrink
// the window into it so the user sees where the app went; otherwise
// simply hide the window in place. Either way the geometry is
// untouched afterwards and showWindow() un-hides via the
// data-minimized_in_place flag.
const el_window = this;
const $win = $(this);
const reduce_motion = window.matchMedia
&& window.matchMedia('(prefers-reduced-motion: reduce)').matches;
// (A morph already in flight — either direction — owns the
// window's inline transform/opacity and will restore them at
// its end, so don't start another on top; fall back to the
// plain fade below, exactly as before the morphs existed.)
const tile = (reduce_motion
|| $win.attr('data-window_morphing') === '1')
? null
: dashboard_tile_in_view($win.attr('data-app'));
// get taskbar item location
let taskbar_item_pos = $(`.taskbar .taskbar-item[data-app="${$(this).attr('data-app')}"]`).position();
if ( tile ) {
// iOS-style zoom-to-icon morph, two congruent layers on
// the same 450ms decelerating path so it reads as ONE
// object transforming:
// 1. the LIVE window scales onto the tile's icon box,
// its corner radius growing toward the squircle,
// fading OUT once it has mostly shrunk;
// 2. an enlarged clone of the icon ("ghost") starts
// covering the window and flies/shrinks with it,
// fading IN as the window fades out, landing exactly
// on the real icon's slot (the real icon is hidden
// until the ghost lands, so nothing doubles).
// Transform + opacity animate on the compositor (no
// per-frame reflow of the app's iframe); the window's
// geometry (top/left/width/height) is never touched, so
// restore is trivial.
const icon = tile.querySelector('.myapps-tile-icon') || tile;
const win_rect = el_window.getBoundingClientRect();
const icon_rect = icon.getBoundingClientRect();
if ( win_rect.width > 0 && win_rect.height > 0
&& icon_rect.width > 0 && icon_rect.height > 0 ) {
// Everything touched is restored from these exact
// inline values once the animation ends.
const orig_style = {
transform: el_window.style.transform,
transformOrigin: el_window.style.transformOrigin,
opacity: el_window.style.opacity,
borderRadius: el_window.style.borderRadius,
overflow: el_window.style.overflow,
willChange: el_window.style.willChange,
pointerEvents: el_window.style.pointerEvents,
transition: el_window.style.transition,
};
const icon_orig_visibility = icon.style.visibility;
// Map the window rect exactly onto the icon rect (and
// the ghost the exact inverse: icon rect onto window
// rect), so the two layers stay congruent throughout.
const scale_x = icon_rect.width / win_rect.width;
const scale_y = icon_rect.height / win_rect.height;
const dx = icon_rect.left - win_rect.left;
const dy = icon_rect.top - win_rect.top;
// No taskbar item to animate toward (e.g. dashboard mode, which
// has no taskbar): if the app's tile is visible on the Apps tab's
// current page, shrink the window into it so the user sees where
// the app went; otherwise simply hide the window in place. Either
// way the geometry is untouched afterwards and showWindow()
// un-hides via the data-minimized_in_place flag.
if ( ! taskbar_item_pos ) {
const el_window = this;
const $win = $(this);
const reduce_motion = window.matchMedia
&& window.matchMedia('(prefers-reduced-motion: reduce)').matches;
// (A morph already in flight — either direction — owns the
// window's inline transform/opacity and will restore them at
// its end, so don't start another on top; fall back to the
// plain fade below, exactly as before the morphs existed.)
const tile = (reduce_motion
|| $win.attr('data-window_morphing') === '1')
? null
: dashboard_tile_in_view($win.attr('data-app'));
const ghost = icon.cloneNode(true);
ghost.style.position = 'fixed';
ghost.style.left = `${icon_rect.left}px`;
ghost.style.top = `${icon_rect.top}px`;
ghost.style.width = `${icon_rect.width}px`;
ghost.style.height = `${icon_rect.height}px`;
ghost.style.margin = '0';
ghost.style.zIndex = (parseInt($win.css('z-index'), 10) || 1) + 1;
ghost.style.pointerEvents = 'none';
ghost.style.transformOrigin = 'top left';
ghost.style.willChange = 'transform, opacity';
ghost.style.opacity = '0';
// UNIFORM start scale so the icon stays square (a
// rect-onto-rect mapping stretches it), sized to fit
// INSIDE the window (contain, centered) — a covering
// square would protrude past the card's short edge
// and the protruding halo pops in mid-crossfade
// (visible jitter). Contained, the ghost's side
// tracks the card's short edge exactly for the whole
// flight (both interpolate linearly between the same
// start and end sizes), so the card's rectangular
// flanks simply melt away around a steady square.
const ghost_scale = Math.min(
win_rect.width / icon_rect.width,
win_rect.height / icon_rect.height,
);
const ghost_left = win_rect.left + (win_rect.width - icon_rect.width * ghost_scale) / 2;
const ghost_top = win_rect.top + (win_rect.height - icon_rect.height * ghost_scale) / 2;
ghost.style.transform = `translate(${ghost_left - icon_rect.left}px, ${ghost_top - icon_rect.top}px) scale(${ghost_scale})`;
document.body.appendChild(ghost);
icon.style.visibility = 'hidden';
if ( tile ) {
// iOS-style zoom-to-icon morph, two congruent layers on
// the same 450ms decelerating path so it reads as ONE
// object transforming:
// 1. the LIVE window scales onto the tile's icon box,
// its corner radius growing toward the squircle,
// fading OUT once it has mostly shrunk;
// 2. an enlarged clone of the icon ("ghost") starts
// covering the window and flies/shrinks with it,
// fading IN as the window fades out, landing exactly
// on the real icon's slot (the real icon is hidden
// until the ghost lands, so nothing doubles).
// Transform + opacity animate on the compositor (no
// per-frame reflow of the app's iframe); the window's
// geometry (top/left/width/height) is never touched, so
// restore is trivial.
const icon = tile.querySelector('.myapps-tile-icon') || tile;
const win_rect = el_window.getBoundingClientRect();
const icon_rect = icon.getBoundingClientRect();
if ( win_rect.width > 0 && win_rect.height > 0
&& icon_rect.width > 0 && icon_rect.height > 0 ) {
// Everything touched is restored from these exact
// inline values once the animation ends.
const orig_style = {
transform: el_window.style.transform,
transformOrigin: el_window.style.transformOrigin,
opacity: el_window.style.opacity,
borderRadius: el_window.style.borderRadius,
overflow: el_window.style.overflow,
willChange: el_window.style.willChange,
pointerEvents: el_window.style.pointerEvents,
transition: el_window.style.transition,
};
const icon_orig_visibility = icon.style.visibility;
// Map the window rect exactly onto the icon rect (and
// the ghost the exact inverse: icon rect onto window
// rect), so the two layers stay congruent throughout.
const scale_x = icon_rect.width / win_rect.width;
const scale_y = icon_rect.height / win_rect.height;
const dx = icon_rect.left - win_rect.left;
const dy = icon_rect.top - win_rect.top;
$win.attr({
'data-is_minimized': true,
'data-minimized_in_place': '1',
'data-window_morphing': '1',
});
el_window.style.transformOrigin = 'top left';
el_window.style.overflow = 'hidden'; // let the radius clip the content
el_window.style.willChange = 'transform, opacity';
el_window.style.pointerEvents = 'none';
// Flush the starting state (both layers) so the
// transitions animate from it rather than snapping.
void el_window.offsetWidth;
// The handoff: by ~130ms the decelerating curve has
// done ~80% of the shrink — the ghost fades in just
// before (80→240ms) and the window fades out just
// after (120→320ms). The overlap means there is never
// a hole, and since both ride the same path the swap
// is invisible: the window "becomes" the icon.
el_window.style.transition = [
'transform 0.45s cubic-bezier(0.32, 0.72, 0, 1)',
'border-radius 0.45s cubic-bezier(0.32, 0.72, 0, 1)',
'opacity 0.2s ease-out 0.12s',
].join(', ');
el_window.style.transform = `translate(${dx}px, ${dy}px) scale(${scale_x}, ${scale_y})`;
// Percentage radius stays proportional under the
// scale — ~22% is the icon-squircle look.
el_window.style.borderRadius = '22%';
el_window.style.opacity = '0';
ghost.style.transition = [
'transform 0.45s cubic-bezier(0.32, 0.72, 0, 1)',
'opacity 0.16s ease-in 0.08s',
].join(', ');
ghost.style.transform = 'none';
ghost.style.opacity = '1';
const ghost = icon.cloneNode(true);
ghost.style.position = 'fixed';
ghost.style.left = `${icon_rect.left}px`;
ghost.style.top = `${icon_rect.top}px`;
ghost.style.width = `${icon_rect.width}px`;
ghost.style.height = `${icon_rect.height}px`;
ghost.style.margin = '0';
ghost.style.zIndex = (parseInt($win.css('z-index'), 10) || 1) + 1;
ghost.style.pointerEvents = 'none';
ghost.style.transformOrigin = 'top left';
ghost.style.willChange = 'transform, opacity';
ghost.style.opacity = '0';
// UNIFORM start scale so the icon stays square (a
// rect-onto-rect mapping stretches it), sized to fit
// INSIDE the window (contain, centered) — a covering
// square would protrude past the card's short edge
// and the protruding halo pops in mid-crossfade
// (visible jitter). Contained, the ghost's side
// tracks the card's short edge exactly for the whole
// flight (both interpolate linearly between the same
// start and end sizes), so the card's rectangular
// flanks simply melt away around a steady square.
const ghost_scale = Math.min(
win_rect.width / icon_rect.width,
win_rect.height / icon_rect.height,
);
const ghost_left = win_rect.left + (win_rect.width - icon_rect.width * ghost_scale) / 2;
const ghost_top = win_rect.top + (win_rect.height - icon_rect.height * ghost_scale) / 2;
ghost.style.transform = `translate(${ghost_left - icon_rect.left}px, ${ghost_top - icon_rect.top}px) scale(${ghost_scale})`;
document.body.appendChild(ghost);
icon.style.visibility = 'hidden';
$win.attr({
'data-is_minimized': true,
'data-minimized_in_place': '1',
'data-window_morphing': '1',
});
el_window.style.transformOrigin = 'top left';
el_window.style.overflow = 'hidden'; // let the radius clip the content
el_window.style.willChange = 'transform, opacity';
el_window.style.pointerEvents = 'none';
// Flush the starting state (both layers) so the
// transitions animate from it rather than snapping.
void el_window.offsetWidth;
// The handoff: by ~130ms the decelerating curve has
// done ~80% of the shrink — the ghost fades in just
// before (80→240ms) and the window fades out just
// after (120→320ms). The overlap means there is never
// a hole, and since both ride the same path the swap
// is invisible: the window "becomes" the icon.
el_window.style.transition = [
'transform 0.45s cubic-bezier(0.32, 0.72, 0, 1)',
'border-radius 0.45s cubic-bezier(0.32, 0.72, 0, 1)',
'opacity 0.2s ease-out 0.12s',
].join(', ');
el_window.style.transform = `translate(${dx}px, ${dy}px) scale(${scale_x}, ${scale_y})`;
// Percentage radius stays proportional under the
// scale — ~22% is the icon-squircle look.
el_window.style.borderRadius = '22%';
el_window.style.opacity = '0';
ghost.style.transition = [
'transform 0.45s cubic-bezier(0.32, 0.72, 0, 1)',
'opacity 0.16s ease-in 0.08s',
].join(', ');
ghost.style.transform = 'none';
ghost.style.opacity = '1';
setTimeout(() => {
// End of the zoom: the ghost has landed on the
// real icon's slot — swap them back in the same
// frame, hide the window, and put every touched
// inline property back while nothing is visible.
// If the user re-opened the window mid-animation
// (tile click → showWindow cleared the flags),
// restore but leave it visible.
ghost.remove();
icon.style.visibility = icon_orig_visibility;
$win.attr('data-window_morphing', '0');
const minimized = $win.attr('data-is_minimized');
if ( minimized === '1' || minimized === 'true' ) $win.hide();
el_window.style.transition = 'none';
el_window.style.transform = orig_style.transform;
el_window.style.transformOrigin = orig_style.transformOrigin;
el_window.style.opacity = orig_style.opacity;
el_window.style.borderRadius = orig_style.borderRadius;
el_window.style.overflow = orig_style.overflow;
el_window.style.willChange = orig_style.willChange;
el_window.style.pointerEvents = orig_style.pointerEvents;
setTimeout(() => {
el_window.style.transition = orig_style.transition;
}, 50);
}, 480);
return;
// End of the zoom: the ghost has landed on the
// real icon's slot — swap them back in the same
// frame, hide the window, and put every touched
// inline property back while nothing is visible.
// If the user re-opened the window mid-animation
// (tile click → showWindow cleared the flags),
// restore but leave it visible.
ghost.remove();
icon.style.visibility = icon_orig_visibility;
$win.attr('data-window_morphing', '0');
const minimized = $win.attr('data-is_minimized');
if ( minimized === '1' || minimized === 'true' ) $win.hide();
el_window.style.transition = 'none';
el_window.style.transform = orig_style.transform;
el_window.style.transformOrigin = orig_style.transformOrigin;
el_window.style.opacity = orig_style.opacity;
el_window.style.borderRadius = orig_style.borderRadius;
el_window.style.overflow = orig_style.overflow;
el_window.style.willChange = orig_style.willChange;
el_window.style.pointerEvents = orig_style.pointerEvents;
setTimeout(() => {
el_window.style.transition = orig_style.transition;
}, 50);
}, 480);
return;
}
}
$win.attr({
'data-is_minimized': true,
'data-minimized_in_place': '1',
});
$win.fadeOut(150);
return;
}
$win.attr({
// Calculate animation target based on taskbar position
let animationTarget = {};
const taskbarPosition = window.taskbar_position || 'bottom';
if ( taskbarPosition === 'bottom' ) {
// taskbar position is center of window minus half of taskbar item width
taskbar_item_pos.left = taskbar_item_pos.left + ($(window).width() / 2) - ($('.taskbar').width() / 2);
animationTarget = {
top: 'calc(100% - 60px)',
left: taskbar_item_pos.left + 14.5,
};
} else if ( taskbarPosition === 'left' ) {
animationTarget = {
top: taskbar_item_pos.top + ($(window).height() / 2) - ($('.taskbar').height() / 2) + 14.5,
left: '5px',
};
} else if ( taskbarPosition === 'right' ) {
animationTarget = {
top: taskbar_item_pos.top + ($(window).height() / 2) - ($('.taskbar').height() / 2) + 14.5,
left: 'calc(100% - 60px)',
};
}
$(this).attr({
'data-orig-width': $(this).width(),
'data-orig-height': $(this).height(),
'data-orig-top': $(this).position().top,
'data-orig-left': $(this).position().left,
'data-is_minimized': true,
'data-minimized_in_place': '1',
});
$win.fadeOut(150);
$(this).css({
...(!isMobile.phone ? {
'transition': 'top 0.2s, left 0.2s, bottom 0.2s, right 0.2s, width 0.2s, height 0.2s',
} : {}),
width: '0',
height: '0',
...animationTarget,
});
// remove transitions a good while after setting css to make sure
// it doesn't interfere with an ongoing animation
setTimeout(() => {
$(this).css({
'transition': 'none',
'transform': 'none',
});
}, 250);
// reset the tab title (the URL is not touched — apps never
// rewrite it on the desktop) — only if this window owned it
const update_window_url = $(this).attr('data-update_window_url');
if ( ! window.is_dashboard_mode && (update_window_url === 'true' || update_window_url === null) ) {
document.title = i18n('window_title_puter');
}
}
});
return this;
@@ -5388,7 +5611,11 @@ async function saveSidebarOrder (order) {
}
}
window.update_maximized_window = function (el_window) {
// Function to update maximized window positioning based on taskbar position
window.update_maximized_window_for_taskbar = function (el_window) {
const position = window.taskbar_position || 'bottom';
// Handle fullpage mode differently
if ( window.is_fullpage_mode ) {
$(el_window).css({
'top': `${window.toolbar_height }px`,
@@ -5399,20 +5626,63 @@ window.update_maximized_window = function (el_window) {
return;
}
$(el_window).css({
'top': `${window.toolbar_height }px`,
'left': '0',
'width': '100%',
'height': `${window.innerHeight - window.toolbar_height - 6 }px`,
});
if ( position === 'bottom' ) {
let height = window.innerHeight - window.taskbar_height - window.toolbar_height - 6;
let width = '100%';
$(el_window).css({
'top': `${window.toolbar_height }px`,
'left': '0',
'width': width,
'height': `${height }px`,
});
} else if ( position === 'left' ) {
let width = window.innerWidth - window.taskbar_height - 1;
$(el_window).css({
'top': `${window.toolbar_height }px`,
'left': `${window.taskbar_height + 1 }px`,
'width': width,
'height': `calc(100% - ${window.toolbar_height}px)`,
});
} else if ( position === 'right' ) {
$(el_window).css({
'top': `${window.toolbar_height }px`,
'left': '0',
'width': `calc(100% - ${window.taskbar_height + 1}px)`,
'height': `calc(100% - ${window.toolbar_height}px)`,
});
}
};
// Function to get snap dimensions and positions based on taskbar position
function getSnapDimensions () {
const taskbar_position = window.taskbar_position || 'bottom';
let available_width, available_height, start_x, start_y;
if ( taskbar_position === 'left' ) {
available_width = window.innerWidth - window.taskbar_height;
available_height = window.innerHeight - window.toolbar_height;
start_x = window.taskbar_height;
start_y = window.toolbar_height;
} else if ( taskbar_position === 'right' ) {
available_width = window.innerWidth - window.taskbar_height;
available_height = window.innerHeight - window.toolbar_height;
start_x = 0;
start_y = window.toolbar_height;
} else { // bottom (default)
available_width = window.innerWidth;
available_height = window.innerHeight - window.toolbar_height - window.taskbar_height;
start_x = 0;
start_y = window.toolbar_height;
}
return {
available_width: window.innerWidth,
available_height: window.innerHeight - window.toolbar_height,
start_x: 0,
start_y: window.toolbar_height,
available_width,
available_height,
start_x,
start_y,
};
}
+1
View File
@@ -782,6 +782,7 @@ const UIWindow2FASetup = async function UIWindow2FASetup () {
width: Math.min(480, window.innerWidth - 24),
height: 'auto',
dominant: true,
show_in_taskbar: false,
is_draggable: false,
backdrop: true,
on_before_exit: async () => {
+1
View File
@@ -215,6 +215,7 @@ async function UIWindowAuthMe (options = {}) {
width: 400,
height: 'auto',
dominant: true,
show_in_taskbar: false,
window_class: 'window-authme',
body_css: {
width: 'initial',
+1
View File
@@ -87,6 +87,7 @@ async function UIWindowBlockedSenders (options) {
width: 420,
height: 'auto',
dominant: true,
show_in_taskbar: false,
onAppend: function (this_window) {
$(this_window).find('.blocked-username').get(0)?.focus({ preventScroll: true });
},
+1
View File
@@ -68,6 +68,7 @@ async function UIWindowChangeUsername (options) {
width: 350,
height: 'auto',
dominant: true,
show_in_taskbar: false,
onAppend: function (this_window) {
$(this_window).find('.new-username').get(0)?.focus({ preventScroll: true });
const oidc_only = !!(window.user && window.user.oidc_only);
+103
View File
@@ -0,0 +1,103 @@
/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
*
* Puter is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import { UIColorPickerWidget } from './UIColorPickerWidget.js';
import UIWindow from './UIWindow.js';
async function UIWindowColorPicker (options) {
// set sensible defaults
if ( arguments.length > 0 ) {
// if first argument is a string, then assume it is the default color
if ( window.isString(arguments[0]) ) {
options = {};
options.default = arguments[0];
}
}
options = options ?? {};
return new Promise(async (resolve) => {
let colorPickerWidget;
let h = '';
h += '<div>';
h += '<div style="padding: 20px; border-bottom: 1px solid #ced7e1; width: 100%; box-sizing: border-box;">';
// picker
h += '<div style="padding: 0; margin-bottom: 20px;">';
h += '<div class="picker"></div>';
h += '</div>';
// Select button
h += `<button class="select-btn button button-primary button-block button-normal">${i18n('select')}</button>`;
h += '</form>';
h += '</div>';
h += '</div>';
const el_window = await UIWindow({
title: i18n('select_color'),
app: 'color-picker',
single_instance: true,
icon: null,
uid: null,
is_dir: false,
body_content: h,
has_head: true,
selectable_body: false,
draggable_body: false,
allow_context_menu: false,
is_draggable: true,
is_droppable: false,
is_resizable: false,
stay_on_top: false,
allow_native_ctxmenu: true,
allow_user_select: true,
...options.window_options,
width: 350,
dominant: true,
on_close: async () => {
resolve(false);
},
onAppend: function (window) {
colorPickerWidget = UIColorPickerWidget($(window).find('.picker'), {
default: options.defaultValue ?? options.defaultColor ?? options.default ?? '#f00',
});
},
window_class: 'window-login',
window_css: {
height: 'initial',
},
body_css: {
width: 'initial',
padding: '0',
'background-color': 'rgba(231, 238, 245, .95)',
'backdrop-filter': 'blur(3px)',
},
});
$(el_window).find('.select-btn').on('click', function (e) {
resolve({ color: colorPickerWidget.getHex8String() });
$(el_window).close();
});
$(el_window).find('.font-selector').on('click', function (e) {
$(el_window).find('.font-selector').removeClass('font-selector-active');
$(this).addClass('font-selector-active');
});
});
}
export default UIWindowColorPicker;
+1
View File
@@ -114,6 +114,7 @@ function UIWindowCopyToken (options = {}) {
width: 450,
height: 'auto',
dominant: true,
show_in_taskbar: false,
window_class: 'window-copy-auth-token',
body_css: {
width: 'initial',
+217
View File
@@ -0,0 +1,217 @@
/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
*
* Puter is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import UIWindow from './UIWindow.js';
async function UIWindowDesktopBGSettings (options) {
options = options ?? {};
return new Promise(async (resolve) => {
let h = '';
const original_background_css = $('body').attr('style');
let bg_url = window.desktop_bg_url,
bg_color = window.desktop_bg_color,
bg_fit = window.desktop_bg_fit;
h += '<div style="padding: 10px; border-bottom: 1px solid #ced7e1;">';
// type
h += `<label>${i18n('background')}:</label>`;
h += '<select class="desktop-bg-type" style="width: 150px; margin-bottom: 20px;">';
h += `<option value="default">${i18n('default')}</option>`;
h += `<option value="picture">${i18n('picture')}</option>`;
h += `<option value="color">${i18n('color')}</option>`;
h += '</select>';
// Picture
h += '<div class="desktop-bg-settings-wrapper desktop-bg-settings-picture">';
h += `<label>${i18n('image')}:</label>`;
h += `<button class="button button-default button-small browse">${i18n('browse')}</button>`;
h += `<label style="margin-top: 20px;">${i18n('fit')}:</label>`;
h += '<select class="desktop-bg-fit" style="width: 150px;">';
h += `<option value="cover">${i18n('cover')}</option>`;
h += `<option value="center">${i18n('center')}</option>`;
h += `<option value="contain">${i18n('contain')}</option>`;
h += `<option value="repeat">${i18n('repeat')}</option>`;
h += '</select>';
h += '</div>';
// Color
h += '<div class="desktop-bg-settings-wrapper desktop-bg-settings-color">';
h += `<label>${i18n('color')}:</label>`;
h += '<div class="desktop-bg-color-blocks">';
h += '<div class="desktop-bg-color-block" data-color="#4F7BB5" style="background-color: #4F7BB5"></div>';
h += '<div class="desktop-bg-color-block" data-color="#545554" style="background-color: #545554"></div>';
h += '<div class="desktop-bg-color-block" data-color="#F5D3CE" style="background-color: #F5D3CE"></div>';
h += '<div class="desktop-bg-color-block" data-color="#52A758" style="background-color: #52A758"></div>';
h += '<div class="desktop-bg-color-block" data-color="#ad3983" style="background-color: #ad3983"></div>';
h += '<div class="desktop-bg-color-block" data-color="#ffffff" style="background-color: #ffffff"></div>';
h += '<div class="desktop-bg-color-block" data-color="#000000" style="background-color: #000000"></div>';
h += '<div class="desktop-bg-color-block" data-color="#454545" style="background-color: #454545"></div>';
h += `<div class="desktop-bg-color-block desktop-bg-color-block-palette" data-color="" style="background-image: url(${window.icons['palette.svg']});
background-repeat: no-repeat;
background-size: contain;
background-position: center;"><input type="color" style="width:25px; height: 25px; opacity:0;"></div>`;
h += '</div>';
h += '</div>';
h += '<div style="padding-top: 5px; overflow:hidden; margin-top: 25px; border-top: 1px solid #CCC;">';
h += `<button class="button button-primary apply" style="float:right;">${i18n('apply')}</button>`;
h += `<button class="button button-default cancel" style="float:right; margin-right: 10px;">${i18n('cancel')}</button>`;
h += '</div>';
h += '</div>';
const el_window = await UIWindow({
title: i18n('change_desktop_background'),
icon: null,
uid: null,
is_dir: false,
body_content: h,
has_head: true,
selectable_body: false,
draggable_body: false,
allow_context_menu: false,
is_resizable: false,
is_droppable: false,
init_center: true,
allow_native_ctxmenu: true,
allow_user_select: true,
onAppend: function (this_window) {
$(this_window).find('.access-recipient').focus();
},
window_class: 'window-give-access',
width: 350,
window_css: {
height: 'initial',
},
body_css: {
width: 'initial',
height: '100%',
'background-color': 'rgb(245 247 249)',
'backdrop-filter': 'blur(3px)',
},
...options.window_options,
});
const default_wallpaper = (window.gui_env === 'prod') ? 'https://puter-assets.b-cdn.net/wallpaper.webp' : '/images/wallpaper.webp';
$(el_window).find('.desktop-bg-settings-wrapper').hide();
if ( window.desktop_bg_url === default_wallpaper ) {
$(el_window).find('.desktop-bg-type').val('default');
} else if ( window.desktop_bg_url !== undefined && window.desktop_bg_url !== null ) {
$(el_window).find('.desktop-bg-settings-picture').show();
$(el_window).find('.desktop-bg-type').val('picture');
} else if ( window.desktop_bg_color !== undefined && window.desktop_bg_color !== null ) {
$(el_window).find('.desktop-bg-settings-color').show();
$(el_window).find('.desktop-bg-type').val('color');
} else {
// Default fallback if no specific wallpaper settings are detected
$(el_window).find('.desktop-bg-type').val('default');
}
$(el_window).find('.desktop-bg-color-block:not(.desktop-bg-color-block-palette').on('click', async function (e) {
window.set_desktop_background({ color: $(this).attr('data-color') });
});
$(el_window).find('.desktop-bg-color-block-palette input').on('change', async function (e) {
window.set_desktop_background({ color: $(this).val() });
});
$(el_window).on('file_opened', function (e) {
let selected_file = Array.isArray(e.detail) ? e.detail[0] : e.detail;
const fit = $(el_window).find('.desktop-bg-fit').val();
bg_url = selected_file.read_url;
bg_fit = fit;
bg_color = undefined;
window.set_desktop_background({ url: bg_url, fit: bg_fit });
});
$(el_window).find('.desktop-bg-fit').on('change', function (e) {
const fit = $(this).val();
bg_fit = fit;
window.set_desktop_background({ fit: fit });
});
$(el_window).find('.desktop-bg-type').on('change', function (e) {
const type = $(this).val();
$(el_window).find('.desktop-bg-settings-wrapper').hide();
if ( type === 'picture' ) {
$(el_window).find('.desktop-bg-settings-picture').show();
} else if ( type === 'color' ) {
$(el_window).find('.desktop-bg-settings-color').show();
} else if ( type === 'default' ) {
bg_color = undefined;
bg_fit = 'cover';
window.set_desktop_background({ url: default_wallpaper, fit: bg_fit });
}
});
$(el_window).find('.apply').on('click', async function (e) {
// /set-desktop-bg
try {
$.ajax({
url: `${window.api_origin }/set-desktop-bg`,
type: 'POST',
data: JSON.stringify({
url: window.desktop_bg_url,
color: window.desktop_bg_color,
fit: window.desktop_bg_fit,
}),
async: true,
contentType: 'application/json',
headers: {
'Authorization': `Bearer ${window.auth_token}`,
},
statusCode: {
401: function (xhr) {
window.handle401(xhr);
},
},
});
$(el_window).close();
resolve(true);
} catch ( err ) {
// Ignore
}
});
$(el_window).find('.browse').on('click', function () {
// open dialog
UIWindow({
path: `/${ window.user.username }/Desktop`,
// this is the uuid of the window to which this dialog will return
parent_uuid: $(el_window).attr('data-element_uuid'),
allowed_file_types: ['image/*'],
show_maximize_button: false,
show_minimize_button: false,
title: i18n('window_title_open'),
is_dir: true,
is_openFileDialog: true,
selectable_body: false,
});
});
$(el_window).find('.cancel').on('click', function () {
$('body').attr('style', original_background_css);
$(el_window).close();
resolve(true);
});
});
}
export default UIWindowDesktopBGSettings;
+233
View File
@@ -0,0 +1,233 @@
/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
*
* Puter is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import {
ATTACHMENT_ACCEPT_ATTRIBUTE,
MAX_ATTACHMENTS,
MAX_ATTACHMENT_BYTES,
MAX_TOTAL_ATTACHMENT_BYTES,
checkAttachment,
} from '../helpers/contact_attachments.js';
import UIWindow from './UIWindow.js';
const MB = 1024 * 1024;
// Numbers interpolated into each error message, taken from the enforced limits.
const ERROR_VALUES = {
contact_us_attachment_too_many: [MAX_ATTACHMENTS],
contact_us_attachment_too_large: [MAX_ATTACHMENT_BYTES / MB],
contact_us_attachment_total_too_large: [MAX_TOTAL_ATTACHMENT_BYTES / MB],
};
/**
* Puter's own Contact Us form, delivered to support (UIWindowAppFeedback is the
* one for third-party apps). Attachments are posted as multipart form data; the
* client-side checks only fail fast, the server enforces the limits.
*/
async function UIWindowFeedback (options) {
return new Promise(async (resolve) => {
options = options ?? {};
// Staged files; kept out of the DOM so re-rendering chips keeps them.
let attachments = [];
let sending = false;
let h = '';
h += '<div style="padding: 20px; margin-top: 0;">';
// success
h += '<div class="feedback-sent-success">';
h += `<img src="${html_encode(window.icons['c-check.svg'])}" style="width:50px; height:50px; display: block; margin:10px auto;">`;
h += `<p style="text-align:center; margin-bottom:10px; color: #005300; padding: 10px;">${i18n('feedback_sent_confirmation')}</p>`;
h += '</div>';
// form
h += '<div class="feedback-form">';
h += `<p style="margin-top:0; font-size: 15px; -webkit-font-smoothing: antialiased;">${i18n('feedback_c2a')}</p>`;
h += '<textarea class="feedback-message" style="width:100%; height: 200px; padding: 10px; box-sizing: border-box;"></textarea>';
// attachments
h += '<div class="feedback-attachments">';
h += `<input type="file" class="feedback-attach-input" accept="${html_encode(ATTACHMENT_ACCEPT_ATTRIBUTE)}" multiple style="display:none;">`;
h += `<button type="button" class="button button-small feedback-attach-btn">${i18n('contact_us_attach')}</button>`;
h += `<span class="feedback-attach-hint">${i18n('contact_us_attach_hint', [MAX_ATTACHMENTS, MAX_ATTACHMENT_BYTES / MB])}</span>`;
h += '<ul class="feedback-attachment-list"></ul>';
h += '</div>';
h += '<p class="feedback-error" role="alert" style="display:none;"></p>';
h += `<button class="button button-primary send-feedback-btn" style="float: right; margin-bottom: 15px; margin-top: 10px;">${i18n('send')}</button>`;
h += '</div>';
h += '</div>';
const el_window = await UIWindow({
title: i18n('contact_us'),
app: 'feedback',
single_instance: true,
icon: null,
uid: null,
is_dir: false,
body_content: h,
has_head: true,
selectable_body: false,
draggable_body: false,
allow_context_menu: false,
is_resizable: false,
is_droppable: false,
init_center: true,
allow_native_ctxmenu: false,
allow_user_select: false,
width: 380,
height: 'auto',
dominant: true,
show_in_taskbar: false,
...options.window_options,
onAppend: function (this_window) {
$(this_window).find('.feedback-message').get(0).focus({ preventScroll: true });
},
window_class: 'window-feedback',
body_css: {
width: 'initial',
height: '100%',
'background-color': 'rgb(245 247 249)',
'backdrop-filter': 'blur(3px)',
},
});
const $error = $(el_window).find('.feedback-error');
// `.html()` rather than `.text()`: i18n() html-encodes what it returns,
// so text() would render the entities literally.
const showError = (key) => $error.html(i18n(key, ERROR_VALUES[key] ?? [])).show();
const clearError = () => $error.hide().empty();
// -- Attachments -------------------------------------------------
const renderAttachments = () => {
const $list = $(el_window).find('.feedback-attachment-list').empty();
attachments.forEach((file, index) => {
const removeLabel = i18n('contact_us_attachment_remove');
const $item = $(
'<li class="feedback-attachment">' +
`<span class="feedback-attachment-name" title="${html_encode(file.name)}">${html_encode(file.name)}</span>` +
`<span class="feedback-attachment-size">${html_encode(window.byte_format(file.size))}</span>` +
`<button type="button" class="feedback-attachment-remove" aria-label="${removeLabel}" title="${removeLabel}">&times;</button>` +
'</li>',
);
$item.find('.feedback-attachment-remove').on('click', () => {
if ( sending ) return;
attachments.splice(index, 1);
clearError();
renderAttachments();
});
$list.append($item);
});
// Nothing left to add once the count cap is reached.
$(el_window).find('.feedback-attach-btn')
.prop('disabled', sending || attachments.length >= MAX_ATTACHMENTS);
};
const addFiles = (files) => {
if ( sending ) return;
let rejection = null;
for ( const file of files ) {
const verdict = checkAttachment(file, attachments);
if ( ! verdict.ok ) {
// Report the first rejection but keep the files that fit.
rejection = rejection ?? verdict.error;
continue;
}
attachments.push(file);
}
if ( rejection ) showError(rejection);
else clearError();
renderAttachments();
};
const $fileInput = $(el_window).find('.feedback-attach-input');
$(el_window).find('.feedback-attach-btn').on('click', () => $fileInput.trigger('click'));
$fileInput.on('change', function () {
addFiles(Array.from(this.files ?? []));
// Reset so re-picking the same file fires `change` again.
this.value = '';
});
// Caught here before UIWindow's body-level drop handler sees it.
const $form = $(el_window).find('.feedback-form');
$form.on('dragover dragenter', (e) => {
e.preventDefault();
e.stopPropagation();
if ( ! sending ) $form.addClass('feedback-form-dragover');
});
$form.on('dragleave dragend', () => $form.removeClass('feedback-form-dragover'));
$form.on('drop', (e) => {
e.preventDefault();
e.stopPropagation();
$form.removeClass('feedback-form-dragover');
addFiles(Array.from(e.originalEvent?.dataTransfer?.files ?? []));
});
// -- Submit --------------------------------------------------------
const setSending = (value) => {
sending = value;
$(el_window).find('.send-feedback-btn').prop('disabled', value);
$(el_window).find('.feedback-attachment-remove').prop('disabled', value);
renderAttachments();
};
$(el_window).find('.send-feedback-btn').on('click', async function () {
if ( sending ) return;
const message = $(el_window).find('.feedback-message').val();
if ( ! message || ! message.trim() ) {
showError('contact_us_message_required');
return;
}
clearError();
setSending(true);
try {
const body = new FormData();
body.append('message', message);
for ( const file of attachments ) {
body.append('attachments', file, file.name);
}
// No Content-Type: the browser sets it with the boundary.
const resp = await fetch(`${window.api_origin}/contactUs`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${window.auth_token}`,
},
body,
});
if ( ! resp.ok ) {
showError(resp.status === 429 ? 'contact_us_rate_limited' : 'contact_us_error');
return;
}
$(el_window).find('.feedback-form').hide();
$(el_window).find('.feedback-sent-success').show(100);
} catch ( e ) {
console.error('contact-us: submit failed', e);
showError('contact_us_error');
} finally {
setSending(false);
}
});
renderAttachments();
resolve(el_window);
});
}
export default UIWindowFeedback;
@@ -57,6 +57,7 @@ async function UIWindowLoginInProgress (options) {
width: 350,
height: 'auto',
dominant: true,
show_in_taskbar: false,
backdrop: true,
stay_on_top: true,
window_class: 'window-login-progress',
+192
View File
@@ -0,0 +1,192 @@
/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
*
* Puter is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import UIWindow from './UIWindow.js';
import UIContextMenu from './UIContextMenu.js';
import UIAlert from './UIAlert.js';
async function UIWindowMyWebsites (options) {
let h = '';
h += '<div>';
h += '</div>';
const el_window = await UIWindow({
title: 'My Websites',
app: 'my-websites',
single_instance: true,
icon: null,
uid: null,
is_dir: false,
body_content: h,
has_head: true,
selectable_body: false,
draggable_body: false,
allow_context_menu: false,
is_resizable: false,
is_droppable: false,
init_center: true,
allow_native_ctxmenu: true,
allow_user_select: true,
width: 400,
dominant: false,
body_css: {
padding: '10px',
width: 'initial',
'background-color': 'rgba(231, 238, 245)',
'backdrop-filter': 'blur(3px)',
'padding-bottom': 0,
'height': '351px',
'box-sizing': 'border-box',
},
});
// /sites
let init_ts = Date.now();
let loading = setTimeout(function () {
$(el_window).find('.window-body').html(`<p style="text-align: center;
margin-top: 40px;
margin-bottom: 50px;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
color: #596c7c;">${i18n('loading')}...</p>`);
}, 1000);
puter.hosting.list().then(function (sites) {
setTimeout(function () {
// clear loading
clearTimeout(loading);
// user has sites
if ( sites.length > 0 ) {
let h = '';
for ( let i = 0; i < sites.length; i++ ) {
h += `<div class="mywebsites-card" data-uuid="${sites[i].uid}">`;
h += `<a class="mywebsites-address-link" href="https://${sites[i].subdomain}.puter.site" target="_blank">${sites[i].subdomain}.puter.site</a>`;
h += `<img class="mywebsites-site-setting" data-site-uuid="${sites[i].uid}" src="${html_encode(window.icons['cog.svg'])}">`;
// there is a directory associated with this site
if ( sites[i].root_dir ) {
h += `<p class="mywebsites-dir-path" data-path="${html_encode(sites[i].root_dir.path)}" data-name="${html_encode(sites[i].root_dir.name)}" data-uuid="${sites[i].root_dir.id}">`;
h += `<img src="${html_encode(window.icons['folder.svg'])}">`;
h += `${html_encode(sites[i].root_dir.path)}`;
h += '</p>';
h += '<p style="margin-bottom:0; margin-top: 20px; font-size: 13px;">';
h += `<span class="mywebsites-dis-dir" data-dir-uuid="${html_encode(sites[i].root_dir.id)}" data-site-subdomain="${html_encode(sites[i].subdomain)}" data-site-uuid="${html_encode(sites[i].uid)}">`;
h += `<img style="width: 16px; margin-bottom: -2px; margin-right: 4px;" src="${html_encode(window.icons['plug.svg'])}">${i18n('disassociate_dir')}</span>`;
h += '</p>';
}
h += `<p class="mywebsites-no-dir-notice" data-site-uuid="${html_encode(sites[i].uid)}" style="${sites[i].root_dir ? 'display:none;' : 'display:block;'}">${i18n('no_dir_associated_with_site')}</p>`;
h += '</div>';
}
$(el_window).find('.window-body').html(h);
}
// has no sites
else {
$(el_window).find('.window-body').html(`<p style="text-align: center;
margin-top: 40px;
margin-bottom: 50px;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
color: #596c7c;">${i18n('no_websites_published')}</p>`);
}
}, Date.now() - init_ts < 1000 ? 0 : 2000);
});
}
$(document).on('click', '.mywebsites-dir-path', function (e) {
e = e.target;
UIWindow({
path: $(e).attr('data-path'),
title: $(e).attr('data-name'),
icon: window.icons['folder.svg'],
uid: $(e).attr('data-uuid'),
is_dir: true,
app: 'explorer',
});
});
$(document).on('click', '.mywebsites-site-setting', function (e) {
const pos = e.target.getBoundingClientRect();
UIContextMenu({
parent_element: e.target,
position: { top: pos.top + 25, left: pos.left - 193 },
items: [
//--------------------------------------------------
// Release Address
//--------------------------------------------------
{
html: 'Release Address',
onClick: async function () {
const alert_resp = await UIAlert({
message: i18n('release_address_confirmation'),
buttons: [
{
label: i18n('yes_release_it'),
value: 'yes',
type: 'primary',
},
{
label: i18n('cancel'),
},
],
});
if ( alert_resp !== 'yes' ) {
return;
}
$.ajax({
url: `${window.api_origin }/delete-site`,
type: 'POST',
data: JSON.stringify({
site_uuid: $(e.target).attr('data-site-uuid'),
}),
async: false,
contentType: 'application/json',
headers: {
'Authorization': `Bearer ${window.auth_token}`,
},
statusCode: {
401: function (xhr) {
window.handle401(xhr);
},
},
success: function () {
$(`.mywebsites-card[data-uuid="${$(e.target).attr('data-site-uuid')}"]`).fadeOut();
},
});
},
},
],
});
});
$(document).on('click', '.mywebsites-dis-dir', function (e) {
puter.hosting.delete(
// dir
$(e.target).attr('data-dir-uuid'),
// hostname
$(e.target).attr('data-site-subdomain'),
// success
function () {
$(`.mywebsites-no-dir-notice[data-site-uuid="${$(e.target).attr('data-site-uuid')}"]`).show();
$(`.mywebsites-dir-path[data-uuid="${$(e.target).attr('data-dir-uuid')}"]`).remove();
// remove the website badge from all instances of the dir
$(`.item[data-uid="${$(e.target).attr('data-dir-uuid')}"]`).find('.item-has-website-badge').fadeOut(300);
$(e.target).hide();
});
});
export default UIWindowMyWebsites;
+1
View File
@@ -100,6 +100,7 @@ async function UIWindowNewPassword (options) {
width: 350,
height: 'auto',
dominant: true,
show_in_taskbar: false,
onAppend: function (this_window) {
$(this_window).find('.new-password').get(0)?.focus({ preventScroll: true });
},
@@ -71,6 +71,7 @@ function UIWindowPasswordChangeRequired (options) {
width: 390,
height: 'auto',
dominant: true,
show_in_taskbar: false,
onAppend: function (this_window) {
$(this_window).find('.pcr-current').get(0)?.focus({ preventScroll: true });
},
+11 -1
View File
@@ -18,6 +18,7 @@
*/
import UIWindow from './UIWindow.js';
import UIWindowMyWebsites from './UIWindowMyWebsites.js';
import { underPath } from '../helpers/pathElements.js';
async function UIWindowPublishWebsite (target_dir_uid, target_dir_name, target_dir_path) {
@@ -121,7 +122,12 @@ async function UIWindowPublishWebsite (target_dir_uid, target_dir_name, target_d
} catch ( err ) {
const errorMessage = err.message || (err.error && err.error.message) || 'An error occurred while publishing';
$(el_window).find('.publish-website-error-msg').html(errorMessage);
$(el_window).find('.publish-website-error-msg').html(
errorMessage + (
err.error && err.error.code === 'subdomain_limit_reached' ?
` <span class="manage-your-websites-link">${ i18n('manage_your_subdomains') }</span>` : ''
),
);
$(el_window).find('.publish-website-error-msg').fadeIn();
// re-enable 'Publish' button
$(el_window).find('.publish-btn').prop('disabled', false);
@@ -133,4 +139,8 @@ async function UIWindowPublishWebsite (target_dir_uid, target_dir_name, target_d
});
}
$(document).on('click', '.manage-your-websites-link', async function (e) {
UIWindowMyWebsites();
});
export default UIWindowPublishWebsite;
+157
View File
@@ -0,0 +1,157 @@
/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
*
* Puter is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import UIWindow from './UIWindow.js';
import UIWindowMyWebsites from './UIWindowMyWebsites.js';
import { underPath } from '../helpers/pathElements.js';
async function UIWindowPublishWorker (target_dir_uid, target_dir_name, target_dir_path) {
let h = '';
h += '<div class="window-publishWorker-content" style="padding: 20px; border-bottom: 1px solid #ced7e1;">';
// success
h += '<div class="window-publishWorker-success">';
h += `<img src="${html_encode(window.icons['c-check.svg'])}" style="width:80px; height:80px; display: block; margin:10px auto;">`;
h += `<p style="text-align:center;">${i18n('dir_published_as_website', `<strong>${html_encode(target_dir_name)}</strong>`, false)}<p>`;
h += `<p style="text-align:center;"><a class="publishWorker-published-link" target="_blank"></a><img class="publishWorker-published-link-icon" src="${html_encode(window.icons['launch.svg'])}"></p>`;
h += `<button class="button button-normal button-block button-primary publish-window-ok-btn" style="margin-top:20px;">${i18n('ok')}</button>`;
h += '</div>';
// form
h += '<form class="window-publishWorker-form">';
// error msg
h += '<div class="publish-worker-error-msg"></div>';
// worker name
h += '<div style="overflow: hidden;">';
h += `<label style="margin-bottom: 10px;">${i18n('pick_name_for_worker')}</label>`;
h += `<div style="font-family: monospace;">${html_encode(window.extractProtocol(window.url))}://<input class="publish-worker-name" style="width:235px;" type="text" autocomplete="subdomain" spellcheck="false" autocorrect="off" autocapitalize="off" data-gramm_editor="false"/>${html_encode('.puter.work')}</div>`;
h += '</div>';
// uid
h += `<input class="publishWebsiteTargetDirUID" type="hidden" value="${html_encode(target_dir_uid)}"/>`;
// Advanced (collapsed by default)
h += '<details class="publish-worker-advanced" style="margin: 16px 0;">';
h += '<summary style="cursor: pointer; font-size: 13px; color: #5c6b7a; user-select: none;">Advanced</summary>';
h += '<div style="margin-top: 12px; padding-left: 2px;">';
h += '<label style="display: flex; align-items: center; gap: 8px; cursor: pointer; font-size: 13px;">';
h += '<input type="checkbox" class="publish-worker-sandboxed" checked>';
h += 'Sandboxed</label>';
h += '</div>';
h += '</details>';
// Publish
h += `<button class="publish-btn button button-action button-block button-normal">${i18n('publish')}</button>`;
h += '</form>';
h += '</div>';
const el_window = await UIWindow({
title: i18n('window_title_publish_worker'),
icon: null,
uid: null,
is_dir: false,
body_content: h,
has_head: true,
selectable_body: false,
draggable_body: false,
allow_context_menu: false,
is_resizable: false,
is_droppable: false,
init_center: true,
allow_native_ctxmenu: true,
allow_user_select: true,
width: 450,
dominant: true,
onAppend: function (this_window) {
$(this_window).find('.publish-worker-name').val(window.generate_identifier());
$(this_window).find('.publish-worker-name').get(0).focus({ preventScroll: true });
},
window_class: 'window-publishWorker',
window_css: {
height: 'initial',
},
body_css: {
width: 'initial',
height: '100%',
'background-color': 'rgb(245 247 249)',
'backdrop-filter': 'blur(3px)',
},
});
$(el_window).find('.publish-btn').on('click', function (e) {
// todo do some basic validation client-side
//Worker name
let worker_name = $(el_window).find('.publish-worker-name').val();
// Store original text and replace with spinner
const originalText = $(el_window).find('.publish-btn').text();
$(el_window).find('.publish-btn').prop('disabled', true).html(`
<div style="display: inline-block; margin-top: 10px; width: 16px; height: 16px; border: 2px solid #ffffff; border-radius: 50%; border-top: 2px solid transparent; animation: spin 1s linear infinite;"></div>
`);
const sandboxed = $(el_window).find('.publish-worker-sandboxed').is(':checked');
const createOptions = sandboxed ? { sandbox: true } : { sandbox: false };
puter.workers.create(
worker_name,
target_dir_path,
createOptions,
).then((res) => {
let url = `https://${ worker_name }.puter.work`;
$(el_window).find('.window-publishWorker-form').hide(100, function () {
$(el_window).find('.publishWorker-published-link').attr('href', url);
$(el_window).find('.publishWorker-published-link').text(url);
$(el_window).find('.window-publishWorker-success').show(100);
// $(`.item[data-uid="${target_dir_uid}"] .item-has-website-badge`).show();
});
// find all items whose path starts with target_dir_path
underPath('.item', target_dir_path).each(function () {
// show the link badge
// $(this).find('.item-has-website-url-badge').show();
// update item's website_url attribute
// $(this).attr('data-website_url', url + $(this).attr('data-path').substring(target_dir_path.length));
});
}).catch((err) => {
let errorHtml;
// Handle worker service errors (result.success === false)
if ( ! (err instanceof Error) ) {
// Handle regular API errors
const error = err.error || err;
errorHtml = error.message + (
error.code === 'subdomain_limit_reached' ?
` <span class="manage-your-websites-link">${ i18n('manage_your_subdomains') }</span>` : ''
);
} else {
errorHtml = `<pre style="white-space: pre-wrap; font-family: monospace; font-size: 12px; margin: 0; text-align: left; font-family: monospace;">${html_encode(err.message)}</pre>`;
}
$(el_window).find('.publish-worker-error-msg').html(errorHtml);
$(el_window).find('.publish-worker-error-msg').fadeIn();
// re-enable 'Publish' button and restore original text
$(el_window).find('.publish-btn').prop('disabled', false).text(originalText);
});
});
$(el_window).find('.publish-window-ok-btn').on('click', function () {
$(el_window).close();
});
}
$(document).on('click', '.manage-your-websites-link', async function (e) {
UIWindowMyWebsites();
});
export default UIWindowPublishWorker;
+88
View File
@@ -0,0 +1,88 @@
/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
*
* Puter is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import Placeholder from '../util/Placeholder.js';
import Flexer from './Components/Flexer.js';
import UIQRCode from './UIQRCode.js';
import UIWindow from './UIWindow.js';
async function UIWindowQR (options) {
options = options ?? {};
const placeholder_qr = Placeholder();
let h = '';
// close button containing the multiplication sign
h += '<div class="qr-code-window-close-btn generic-close-window-button"> &times; </div>';
h += '<div class="otp-qr-code">';
h += `<h1 style="text-align: center; font-size: 16px; padding: 10px; font-weight: 400; margin: -10px 10px 20px 10px; -webkit-font-smoothing: antialiased; color: #5f626d;">${
i18n(options.message_i18n_key || 'scan_qr_generic')
}</h1>`;
h += '</div>';
h += placeholder_qr.html;
const el_window = await UIWindow({
title: i18n('window_title_instant_login'),
app: 'instant-login',
single_instance: true,
icon: null,
uid: null,
is_dir: false,
body_content: h,
has_head: false,
selectable_body: false,
allow_context_menu: false,
is_resizable: false,
is_droppable: false,
init_center: true,
allow_native_ctxmenu: false,
allow_user_select: false,
backdrop: true,
width: 450,
height: 'auto',
dominant: true,
show_in_taskbar: false,
draggable_body: true,
window_class: 'window-qr',
body_css: {
width: 'initial',
height: '100%',
'background-color': 'rgb(245 247 249)',
'backdrop-filter': 'blur(3px)',
padding: '50px 20px',
},
});
const el_qr = UIQRCode({
value: options.text,
size: 250,
});
const component_flexer = new Flexer({
children: [
el_qr,
],
});
component_flexer.attach(placeholder_qr);
}
export default UIWindowQR;
+1
View File
@@ -91,6 +91,7 @@ async function UIWindowSaveAccount (options) {
allow_user_select: true,
width: 350,
dominant: true,
show_in_taskbar: false,
...options.window_options,
onAppend: function (this_window) {
if ( options.default_username )
+308
View File
@@ -0,0 +1,308 @@
/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
*
* Puter is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import UIWindow from './UIWindow.js';
import path from '../lib/path.js';
import UIAlert from './UIAlert.js';
import launch_app from '../helpers/launchApp.js';
import item_icon from '../helpers/itemIcon.js';
import UIContextMenu from './UIContextMenu.js';
async function UIWindowSearch (options) {
let h = '';
h += '<div class="search-input-wrapper">';
h += `<input type="text" class="search-input" placeholder="Search" style="background-image:url('${window.icons['magnifier-outline.svg']}');">`;
h += '</div>';
h += '<div class="search-results" style="overflow-y: auto; max-height: 300px;">';
const el_window = await UIWindow({
icon: null,
single_instance: true,
app: 'search',
uid: null,
is_dir: false,
body_content: h,
has_head: false,
selectable_body: false,
draggable_body: true,
allow_context_menu: false,
is_draggable: false,
is_resizable: false,
is_droppable: false,
init_center: true,
allow_native_ctxmenu: true,
allow_user_select: true,
window_class: 'window-search',
backdrop: true,
center: isMobile.phone,
width: 500,
dominant: true,
window_css: {
height: 'initial',
padding: '0',
},
body_css: {
width: 'initial',
'max-height': 'calc(100vh - 200px)',
'background-color': 'rgb(241 246 251)',
'backdrop-filter': 'blur(3px)',
'padding': '0',
'height': 'initial',
'overflow': 'hidden',
'min-height': '65px',
'padding-bottom': '10px',
},
});
$(el_window).find('.search-input').focus();
// Debounce function to limit rate of API calls
function debounce (func, wait) {
let timeout;
return function (...args) {
const context = this;
clearTimeout(timeout);
timeout = setTimeout(() => {
func.apply(context, args);
}, wait);
};
}
// State for managing loading indicator
let isSearching = false;
// Debounced search function
const performSearch = debounce(async function (searchInput, resultsContainer) {
// Don't search if input is empty
if ( searchInput.val() === '' ) {
resultsContainer.html('');
resultsContainer.hide();
return;
}
// Set loading state
if ( ! isSearching ) {
isSearching = true;
}
try {
// Perform the search
let results = await fetch(`${window.api_origin }/search`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${puter.authToken}`,
},
body: JSON.stringify({ text: searchInput.val() }),
});
results = await results.json();
// Hide results if there are none
if ( results.length === 0 )
{
resultsContainer.hide();
}
else
{
resultsContainer.show();
}
// Build results HTML
let h = '';
for ( let i = 0; i < results.length; i++ ) {
const result = results[i];
h += `<div
class="search-result"
data-path="${html_encode(result.path)}"
data-uid="${html_encode(result.uid)}"
data-is_dir="${html_encode(result.is_dir)}"
>`;
// icon
h += `<img src="${html_encode((await item_icon(result)).image)}" style="width: 20px; height: 20px; margin-right: 6px;">`;
h += html_encode(result.name);
h += '</div>';
}
resultsContainer.html(h);
} catch ( error ) {
resultsContainer.html('<div class="search-error">Search failed. Please try again.</div>');
console.error('Search error:', error);
} finally {
isSearching = false;
}
}, 300); // Wait 300ms after last keystroke before searching
// Event binding
$(el_window).find('.search-input').on('input', function (e) {
const searchInput = $(this);
const resultsContainer = $(el_window).find('.search-results');
performSearch(searchInput, resultsContainer);
});
}
$(document).on('click', '.search-result', async function (e) {
const fspath = $(this).data('path');
const fsuid = $(this).data('uid');
const is_dir = $(this).attr('data-is_dir') === 'true' || $(this).data('is_dir') === '1';
let open_item_meta;
if ( is_dir ) {
UIWindow({
path: fspath,
title: path.basename(fspath),
icon: await item_icon({ is_dir: true, path: fspath }),
uid: fsuid,
is_dir: is_dir,
app: 'explorer',
});
// close search window
$(this).closest('.window').close();
return;
}
// get all info needed to open an item
try {
open_item_meta = await $.ajax({
url: `${window.api_origin }/open_item`,
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({
uid: fsuid ?? undefined,
path: fspath ?? undefined,
}),
headers: {
'Authorization': `Bearer ${window.auth_token}`,
},
statusCode: {
401: function (xhr) {
window.handle401(xhr);
},
},
});
} catch ( err ) {
// Ignored
}
// get a list of suggested apps for this file type.
let suggested_apps = open_item_meta?.suggested_apps ?? await window.suggest_apps_for_fsentry({ uid: fsuid, path: fspath });
//---------------------------------------------
// No suitable apps, ask if user would like to
// download
//---------------------------------------------
if ( suggested_apps.length === 0 ) {
//---------------------------------------------
// If .zip file, unzip it
//---------------------------------------------
if ( path.extname(fspath) === '.zip' ) {
window.unzipItem(fspath);
return;
}
const alert_resp = await UIAlert('Found no suitable apps to open this file with. Would you like to download it instead?',
[
{
label: i18n('download_file'),
value: 'download_file',
type: 'primary',
},
{
label: i18n('cancel'),
},
]);
if ( alert_resp === 'download_file' ) {
window.trigger_download([fspath]);
}
return;
}
//---------------------------------------------
// First suggested app is default app to open this item
//---------------------------------------------
else {
launch_app({
name: suggested_apps[0].name,
token: open_item_meta.token,
file_path: fspath,
app_obj: suggested_apps[0],
window_title: path.basename(fspath),
file_uid: fsuid,
// maximized: options.maximized,
file_signature: open_item_meta.signature,
});
}
// close
$(this).closest('.window').close();
});
// Context menu for search results
$(document).on('contextmenu', '.search-result', async function (e) {
e.preventDefault();
e.stopPropagation();
const fspath = $(this).data('path');
const fsuid = $(this).data('uid');
const is_dir = $(this).attr('data-is_dir') === 'true' || $(this).data('is_dir') === '1';
// Get the parent directory path
const parent_path = path.dirname(fspath);
// Build context menu items
const menuItems = [
{
html: i18n('open'),
onClick: async function () {
// Trigger the same logic as clicking on the search result
$(e.target).trigger('click');
},
},
];
// Only add "Open enclosing folder" if we're not already at root
if ( parent_path && parent_path !== fspath && parent_path !== '/' ) {
menuItems.push('-'); // divider
menuItems.push({
html: i18n('open_containing_folder'),
onClick: async function () {
// Open the enclosing folder
UIWindow({
path: parent_path,
title: path.basename(parent_path) || window.root_dirname,
icon: window.icons['folder.svg'],
is_dir: true,
app: 'explorer',
});
// Close search window
$(e.target).closest('.window').close();
},
});
}
UIContextMenu({
items: menuItems,
});
});
export default UIWindowSearch;
+454
View File
@@ -0,0 +1,454 @@
/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
*
* Puter is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import UIWindow from './UIWindow.js';
import UIAlert from './UIAlert.js';
import path from '../lib/path.js';
import { is_owned_by_me, owner_of_path } from '../helpers/pathOwner.js';
import { invalidate_shared_roots } from '../helpers/sharedAccess.js';
import { icons } from '../helpers/actionIcons.js';
import { mode_label, options_for } from '../helpers/shareModes.js';
import { has_direct_share, mark_item_shared } from '../helpers/sharedBadge.js';
import { share_outcome } from '../helpers/shareOutcome.js';
import shareRecipientPicker from '../helpers/shareRecipientPicker.js';
import { share_key } from '../helpers/shareSuggest.js';
import {
team_for_share, team_label, teams_for_sharing,
} from '../helpers/shareTeams.js';
import { share_link_for } from '../helpers/sharePaths.js';
import { is_plan_gate_error, open_upgrade_flow } from '../helpers/planGate.js';
import { with_verification_gate } from '../helpers/verification_gates.js';
/** What each outcome of a share call is called on screen. */
const SHARE_MESSAGE = {
invited: 'share_invited',
shared: 'share_shared_with',
updated: 'share_access_updated',
unchanged: 'share_already_shared_with',
};
/**
* Sharing dialog for one file or directory.
*
* @param {object} options
* @param {string} options.path Item to share.
* @param {string} [options.name] Display name; defaults to the path's basename.
* @param {string} [options.owner] Owner's username; defaults to the first path
* segment, which is not the current user when a `manage` recipient opens this.
* @param {string} [options.uid] The item's uid, when the caller has it; saves
* the lookup the "copy link" button otherwise makes.
*/
async function UIWindowShare (options) {
options = options ?? {};
const item_path = options.path;
const item_name = options.name ?? path.basename(item_path);
const item_owner =
options.owner ?? owner_of_path(item_path) ?? window.user.username;
// A delegate passes on access, never the authority to pass it on.
const allow_manage = is_owned_by_me(item_path);
let h = '';
h += '<div class="share-dialog">';
h += '<div class="form-error-msg"></div>';
h += '<div class="form-success-msg"></div>';
h += `<label for="share-recipient">${i18n('share_with')}</label>`;
h += '<div class="share-dialog-row">';
h += `<input class="share-recipient" id="share-recipient" type="text" autocomplete="off" spellcheck="false"
placeholder="${i18n('share_add_people')}" />`;
h += `<select class="share-mode">${options_for('read', { allow_manage })}</select>`;
h += '</div>';
h += `<button class="share-btn button button-primary button-block button-normal">${i18n('share')}</button>`;
// The owner's switch between people-only and anyone with the link. A
// delegate passes access on to people; opening the item to everyone is
// the owner's call, so nobody else gets the control.
if ( allow_manage ) {
h += '<div class="share-general-access">';
h += `<div class="share-dialog-heading">${i18n('share_general_access')}</div>`;
h += '<div class="share-dialog-row share-link-row">';
h += `<select class="share-link-access" aria-label="${html_encode(i18n('share_general_access'))}">`;
h += `<option value="restricted">${i18n('share_link_restricted')}</option>`;
h += `<option value="anyone">${i18n('share_link_anyone')}</option>`;
h += '</select>';
h += `<select class="share-link-mode" aria-label="${html_encode(i18n('share_access_level'))}" hidden>${options_for('read', { allow_manage: false })}</select>`;
h += '</div>';
h += `<p class="share-link-note">${i18n('share_link_restricted_note')}</p>`;
h += `<button class="share-copy-link button button-block button-normal" hidden>${i18n('share_copy_link')}</button>`;
h += '</div>';
}
h += `<div class="share-dialog-heading">${i18n('share_who_has_access')}</div>`;
h += '<div class="share-list"></div>';
h += '</div>';
// One dialog per item — window-level single_instance would refocus a
// dialog still bound to a different file.
const $existing = $('.window[data-app="share"]').filter(
(_, el) => $(el).attr('data-share-path') === item_path,
);
if ( $existing.length ) {
$existing.focusWindow();
return;
}
const el_window = await UIWindow({
title: `${i18n('share')} — ${item_name}`,
app: 'share',
icon: window.icons['share-outline.svg'],
uid: null,
is_dir: false,
body_content: h,
has_head: true,
selectable_body: false,
draggable_body: false,
allow_context_menu: false,
is_resizable: false,
is_droppable: false,
init_center: true,
allow_native_ctxmenu: false,
allow_user_select: false,
width: 420,
height: 'auto',
dominant: true,
show_in_taskbar: false,
onAppend: function (this_window) {
$(this_window).find('.share-recipient').get(0)?.focus({ preventScroll: true });
},
// The recipient field listens on the document to know when a click
// landed outside its suggestions; that has to come off with the window.
on_close: () => picker.destroy(),
window_class: 'window-share',
window_css: { height: 'initial' },
body_css: { width: 'initial', padding: '0', 'background-color': 'rgb(245 247 249)' },
});
$(el_window).attr('data-share-path', item_path);
const $error = $(el_window).find('.form-error-msg');
const $success = $(el_window).find('.form-success-msg');
const $list = $(el_window).find('.share-list');
const show_error = (message) => {
$success.hide();
$error.html(html_encode(message)).show();
};
const show_success = (message) => {
$error.hide();
$success.html(message).show();
};
/** The access list as last drawn, which is what a share call changes. */
let shown_shares = [];
/** The caller's teams, offered as recipients. */
let teams = [];
/** The team behind each `data-team` row as last drawn. */
const row_teams = new Map();
/** The item's own "anyone with the link" share as last listed, or null. */
let link_share = null;
/** The item's uid, which its link is built on; looked up once. */
let item_uid = options.uid ?? null;
const $recipient = $(el_window).find('.share-recipient');
const $share_btn = $(el_window).find('.share-btn');
// One field for every kind of recipient: a colleague, a whole team, someone
// shared with before, or an address typed from scratch.
const picker = shareRecipientPicker({
$input: $recipient,
$row: $recipient.closest('.share-dialog-row'),
// Nobody already on the list below: offering them again would only
// re-grant what the row next to it already shows.
excluded: () => shown_shares.map(share_key).filter(Boolean),
onChange: () => { $share_btn.prop('disabled', ! picker.recipient()); },
});
$share_btn.prop('disabled', true);
// Enter shares, the way it submits the Dashboard's dialog. Bound after the
// picker, which takes the press for itself while it is choosing a row.
$recipient.on('keydown', (e) => {
if ( e.key !== 'Enter' || e.isDefaultPrevented() ) return;
if ( $share_btn.prop('disabled') ) return;
$share_btn.trigger('click');
});
const render = (shares) => {
shown_shares = Array.isArray(shares) ? shares : [];
row_teams.clear();
// The item's own link share drives the general-access control rather
// than a row; a delegate, who has no control, sees it as a row.
link_share = shown_shares.find((share) => share.anyone && ! share.inheritedFrom) ?? null;
const listed = shown_shares.filter((share) => ! (allow_manage && share.anyone && ! share.inheritedFrom));
let rows = '';
// The owner's access comes from owning the item, so it can't be revoked
rows += '<div class="share-row">';
rows += `<span class="share-row-who">${html_encode(item_owner)}${item_owner === window.user.username ? ` (${i18n('share_you')})` : ''}</span>`;
rows += `<span class="share-row-owner">${i18n('share_owner')}</span>`;
rows += '</div>';
for ( const share of listed ) {
const holder = share.anyone ? i18n('share_row_anyone') : html_encode(share.holder ?? '');
if ( share.anyone && ! share.inheritedFrom ) {
rows += '<div class="share-row share-row-inherited">';
rows += `<span class="share-row-who">${holder}</span>`;
rows += `<span class="share-row-mode">${mode_label(share.mode)}</span>`;
rows += '</div>';
continue;
}
if ( share.inheritedFrom ) {
// Granted on an ancestor, so it can only be changed there
rows += '<div class="share-row share-row-inherited">';
rows += `<span class="share-row-who">${holder}</span>`;
rows += `<span class="share-row-via">${i18n('share_inherited_via', { folder: path.basename(share.inheritedFrom) })}</span>`;
rows += `<span class="share-row-mode">${mode_label(share.mode)}</span>`;
rows += '</div>';
continue;
}
if ( share.pending ) {
// Withheld unless the invite is ours to act on: nobody to name,
// and the server would refuse the cancellation anyway.
const invited = html_encode(share.recipientEmail ?? '');
rows += '<div class="share-row share-row-pending">';
rows += `<span class="share-row-who">${invited || html_encode(i18n('share_invited_someone'))}</span>`;
rows += `<span class="share-row-via">${i18n('share_awaiting_signup')}</span>`;
rows += `<span class="share-row-mode">${mode_label(share.mode)}</span>`;
if ( invited )
rows += `<button class="share-revoke" data-holder="${invited}" title="${html_encode(i18n('share_cancel_invite'))}" aria-label="${html_encode(i18n('share_cancel_invite'))}">${icons.trash}</button>`;
rows += '</div>';
continue;
}
// A team holds the share itself, so the row has no username to
// key on; `data-team` carries the uid the handlers address it by.
const team = team_for_share(teams, share);
if ( team ) row_teams.set(team.uid, team);
const key = team
? `data-team="${html_encode(team.uid)}"`
: `data-holder="${holder}"`;
rows += `<div class="share-row${team ? ' share-row-team' : ''}">`;
rows += `<span class="share-row-who">${team ? html_encode(team_label(team)) : holder}</span>`;
if ( team ) rows += `<span class="share-row-via">${i18n('share_row_team')}</span>`;
rows += `<select class="share-row-mode-select" ${key}>${options_for(share.mode, { allow_manage })}</select>`;
rows += `<button class="share-revoke" ${key} title="${html_encode(i18n('share_remove_access'))}" aria-label="${html_encode(i18n('share_remove_access'))}">${icons.trash}</button>`;
rows += '</div>';
}
if ( !listed.length ) {
rows += `<p class="share-dialog-empty">${i18n('share_no_one')}</p>`;
}
$list.html(rows);
render_link_access();
// Every share, mode change and revoke lands here.
mark_item_shared(item_path, has_direct_share(shares));
};
const refresh = async () => {
try {
render(await puter.fs.getShares(item_path));
} catch (e) {
show_error(e?.message ?? i18n('share_failed'));
}
};
// -- General access --
const $link_access = $(el_window).find('.share-link-access');
const $link_mode = $(el_window).find('.share-link-mode');
const $link_note = $(el_window).find('.share-link-note');
const $copy_link = $(el_window).find('.share-copy-link');
/** Put the control where the listing says the item stands. */
const render_link_access = () => {
if ( ! allow_manage ) return;
const on = link_share !== null;
$link_access.val(on ? 'anyone' : 'restricted');
$link_mode.prop('hidden', ! on);
if ( on ) $link_mode.val(link_share.mode);
$link_note.html(on
? i18n(link_share.mode === 'write' ? 'share_link_anyone_note_write' : 'share_link_anyone_note_read')
: i18n('share_link_restricted_note'));
$copy_link.prop('hidden', ! (on && item_uid));
};
/** Open the item to anyone with the link at `mode`, or close it with null. */
const set_link_access = async (mode) => {
$link_access.prop('disabled', true);
$link_mode.prop('disabled', true);
try {
if ( mode ) {
const created = await with_verification_gate(() => puter.fs.share({
path: item_path,
recipient: { anyone: true },
mode,
}));
item_uid ??= created?.[0]?.entryUid ?? null;
show_success(i18n(mode === 'write' ? 'share_link_on_write' : 'share_link_on_read'));
} else {
await puter.fs.unshare(item_path, { anyone: true });
show_success(i18n('share_link_off'));
}
} catch (e) {
// A plan gate gets the flow that clears it, where the deployment
// has one; a refusal is otherwise reported like any other.
if ( is_plan_gate_error(e) ) {
if ( ! open_upgrade_flow() ) show_error(i18n('share_link_requires_plan'));
} else {
show_error(e?.message ?? i18n('share_failed'));
}
} finally {
$link_access.prop('disabled', false);
$link_mode.prop('disabled', false);
}
// The listing is the truth either way, and it puts the control back.
await refresh();
};
$link_access.on('change', function () {
set_link_access($(this).val() === 'anyone' ? ($link_mode.val() || 'read') : null);
});
$link_mode.on('change', function () {
set_link_access($(this).val());
});
$copy_link.on('click', async function () {
if ( ! item_uid ) return;
try {
await window.copy_to_clipboard(share_link_for(
{ owner: item_owner, uid: item_uid, name: item_name },
window.gui_origin,
));
show_success(i18n('share_link_copied'));
} catch (e) {
show_error(e?.message ?? i18n('share_failed'));
}
});
$(el_window).on('click', '.share-btn', async function () {
// A team is named by uid; anything typed goes as-is, since a bare
// string is what the backend reads as an email or a username.
const chosen = picker.recipient();
if ( ! chosen ) return;
$(this).prop('disabled', true);
try {
const created = await with_verification_gate(() => puter.fs.share({
path: item_path,
recipient: chosen.value,
mode: $(el_window).find('.share-mode').val(),
}));
picker.clear();
$error.hide();
// `i18n()` encodes its replacements; encoding first would show the
// entities to anyone whose address or username contains one.
show_success(
i18n(SHARE_MESSAGE[share_outcome(created, shown_shares)], {
recipient: chosen.label,
}),
);
picker.remember(chosen, created);
invalidate_shared_roots();
await refresh();
} catch (e) {
show_error(e?.message ?? i18n('share_failed'));
} finally {
$(this).prop('disabled', ! picker.recipient());
}
});
$(el_window).on('change', '.share-row-mode-select', async function () {
const team = row_teams.get($(this).attr('data-team'));
const holder = $(this).attr('data-holder');
const recipient = team ? { team: team.uid } : holder;
const name = team ? team_label(team) : holder;
const mode = $(this).val();
$(this).prop('disabled', true);
try {
await with_verification_gate(() => puter.fs.share({ path: item_path, recipient, mode }));
show_success(i18n('share_access_updated', { recipient: name }));
invalidate_shared_roots();
await refresh();
} catch (e) {
show_error(e?.message ?? i18n('share_failed'));
invalidate_shared_roots();
await refresh();
}
});
$(el_window).on('click', '.share-revoke', async function () {
const holder = $(this).attr('data-holder');
const is_pending = $(this).closest('.share-row').hasClass('share-row-pending');
const team = row_teams.get($(this).attr('data-team'));
// Losing a team's access is losing everyone in it at once, which
// the ordinary "remove {recipient}" wording would understate.
const removed_name = team ? team_label(team) : holder;
const confirmed = await UIAlert({
message: is_pending
? i18n('share_confirm_cancel_invite', { recipient: holder })
: i18n(team ? 'share_confirm_remove_team' : 'share_confirm_remove', { recipient: removed_name }),
buttons: [
{ label: i18n('share_remove'), value: true, type: 'primary' },
{ label: i18n('cancel'), value: false },
],
// Stack the confirmation with the dialog that opened it. In
// fullpage/dashboard mode this window is promoted to the
// stay-on-top band, where an alert defaulting to `stay_on_top:
// false` renders underneath it — leaving a confirmation the user
// can't reach without closing the dialog behind it.
parent_uuid: $(el_window).attr('data-element_uuid'),
stay_on_top: $(el_window).attr('data-stay_on_top') === 'true',
});
if ( ! confirmed ) return;
$(this).prop('disabled', true);
try {
await puter.fs.unshare(item_path, team ? { team: team.uid } : holder);
// `i18n()` encodes what it returns, replacements included, so the
// raw value goes in — encoding first would show the entities to
// anyone whose address or username contains one.
show_success(
is_pending
? i18n('share_invite_cancelled', { recipient: holder })
: i18n('share_access_removed', { recipient: removed_name }),
);
invalidate_shared_roots();
await refresh();
} catch (e) {
show_error(e?.message ?? i18n('share_failed'));
$(this).prop('disabled', false);
}
});
// The uid the link is built on; the copy button waits for it.
if ( allow_manage && ! item_uid ) {
puter.fs.stat(item_path).then((stat) => {
item_uid = stat?.uid ?? null;
render_link_access();
}).catch(() => { /* the button just stays hidden */ });
}
// Teams first: the access list names its rows from them, and the recipient
// field suggests both them and the people in them.
teams = await teams_for_sharing();
picker.setTeams(teams);
// Not the encoded form: an attribute set from JS shows entities literally.
if ( teams.length ) $recipient.attr('placeholder', i18n('share_add_people_teams', [], false));
await refresh();
return el_window;
}
export default UIWindowShare;
+244
View File
@@ -0,0 +1,244 @@
/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
*
* Puter is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import { END_HARD, END_SOFT } from '../definitions.js';
import UIAlert from './UIAlert.js';
import UIContextMenu from './UIContextMenu.js';
import UIWindow from './UIWindow.js';
const end_process = async (uuid, force) => {
const svc_process = globalThis.services.get('process');
const process = svc_process.get_by_uuid(uuid);
if ( ! process ) {
console.warn(`Can't end process with uuid='${uuid}': does not exist`);
return;
}
let confirmation;
if ( process.is_init() ) {
if ( ! force ) {
confirmation = i18n('close_all_windows_confirm');
} else {
confirmation = i18n('restart_puter_confirm');
}
} else if ( force ) {
confirmation = i18n('end_process_force_confirm');
}
if ( confirmation ) {
const alert_resp = await UIAlert({
message: confirmation,
buttons: [
{
label: i18n('yes'),
value: true,
type: 'primary',
},
{
label: i18n('no'),
value: false,
},
],
});
if ( ! alert_resp ) return;
}
process.signal(force ? END_HARD : END_SOFT);
};
const calculate_indent_string = (indent_level, is_last_item_stack, is_last_item) => {
// Returns a string of '| ├└'
let result = '';
for ( let i = 0; i < indent_level; i++ ) {
const last_cell = i === indent_level - 1;
const has_trunk = (last_cell && ( !is_last_item )) ||
(!last_cell && !is_last_item_stack[i + 1]);
const has_branch = last_cell;
if ( has_trunk && has_branch ) {
result += '├';
} else if ( has_trunk ) {
result += '|';
} else if ( has_branch ) {
result += '└';
} else {
result += ' ';
}
}
return result;
};
const generate_task_rows = (items, { indent_level, is_last_item_stack }) => {
const svc_process = globalThis.services.get('process');
let rows_html = '';
for ( let i = 0; i < items.length; i++ ) {
const item = items[i];
const is_last_item = i === items.length - 1;
const indentation = calculate_indent_string(indent_level, is_last_item_stack, is_last_item);
// Generate indentation HTML
let indentation_html = '';
for ( const c of indentation ) {
indentation_html += '<div class="indentcell">';
switch (c) {
case ' ':
break;
case '|':
indentation_html += '<div class="indentcell-trunk"></div>';
break;
case '└':
indentation_html += '<div class="indentcell-branch"></div>';
break;
case '├':
indentation_html += '<div class="indentcell-trunk"></div>';
indentation_html += '<div class="indentcell-branch"></div>';
break;
}
indentation_html += '</div>';
}
rows_html += `
<tr class="task-row" data-uuid="${item.uuid}">
<td>
<div class="task">
<div class="task-indentation">${indentation_html}</div>
<div class="task-name">${item.name}</div>
</div>
</td>
<td><span class="process-type">${i18n(`process_type_${ item.type}`)}</span></td>
<td><span class="process-status">${i18n(`process_status_${ item.status.i18n_key}`)}</span></td>
</tr>
`;
const children = svc_process.get_children_of(item.uuid);
if ( children ) {
rows_html += generate_task_rows(children, {
indent_level: indent_level + 1,
is_last_item_stack: [ ...is_last_item_stack, is_last_item ],
});
}
}
return rows_html;
};
const UIWindowTaskManager = async function UIWindowTaskManager () {
const svc_process = globalThis.services.get('process');
let h = '';
h += '<div class="task-manager-container">';
h += '<table>';
h += '<thead>';
h += '<tr>';
h += `<th>${i18n('taskmgr_header_name')}</th>`;
h += `<th>${i18n('taskmgr_header_type')}</th>`;
h += `<th>${i18n('taskmgr_header_status')}</th>`;
h += '</tr>';
h += '</thead>';
h += '<tbody class="taskmgr-taskarea">';
h += '</tbody>';
h += '</table>';
h += '</div>';
const el_window = await UIWindow({
title: i18n('task_manager'),
icon: globalThis.icons['cog.svg'],
uid: null,
is_dir: false,
single_instance: true,
app: 'taskmgr',
is_resizable: true,
is_droppable: false,
has_head: true,
selectable_body: true,
draggable_body: false,
allow_context_menu: false,
show_in_taskbar: true,
dominant: true,
body_content: h,
width: 350,
window_class: 'window-task-manager',
window_css: {
height: 'initial',
},
body_css: {
width: 'initial',
padding: '20px',
'background-color': `hsla(
var(--primary-hue),
var(--primary-saturation),
var(--primary-lightness),
var(--primary-alpha))`,
'backdrop-filter': 'blur(3px)',
'box-sizing': 'border-box',
height: 'calc(100% - 30px)',
display: 'flex',
'flex-direction': 'column',
'--scale': '2pt',
'--line-color': '#6e6e6ebd',
padding: '0',
},
});
const update_tasks = () => {
const processes = [svc_process.get_init()];
const rows_html = generate_task_rows(processes, { indent_level: 0, is_last_item_stack: [] });
$(el_window).find('.taskmgr-taskarea').html(rows_html);
};
// Set up context menu for task rows
$(el_window).on('contextmenu', '.task-row', function (e) {
e.preventDefault();
const uuid = $(this).data('uuid');
UIContextMenu({
items: [
{
html: i18n('close'),
onClick: () => {
end_process(uuid);
},
},
{
html: i18n('force_quit'),
onClick: () => {
end_process(uuid, true);
},
},
],
});
});
// Initial task update
update_tasks();
// Set up interval to refresh tasks
const interval = setInterval(update_tasks, 500);
// Clean up interval when window is closed
$(el_window).on('close', () => {
clearInterval(interval);
});
return el_window;
};
export default UIWindowTaskManager;
+114
View File
@@ -0,0 +1,114 @@
/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
*
* Puter is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import { UIColorPickerWidget, hslaToHex8 } from './UIColorPickerWidget.js';
import UIWindow from './UIWindow.js';
const UIWindowThemeDialog = async function UIWindowThemeDialog (options) {
options = options ?? {};
const services = globalThis.services;
const svc_theme = services.get('theme');
// Get current theme values and convert to hex8 for the color picker
const currentHue = svc_theme.get('hue');
const currentSat = svc_theme.get('sat');
const currentLig = svc_theme.get('lig');
const currentAlpha = svc_theme.get('alpha');
const initialColor = hslaToHex8(currentHue, currentSat, currentLig, currentAlpha);
let h = '';
h += '<div class="theme-dialog-content" style="display: flex; flex-direction: column; gap: 10pt;">';
h += `<button class="button button-secondary reset-colors-btn">${i18n('reset_colors')}</button>`;
h += '<div class="color-picker-container" style="padding: 0; margin-bottom: 10px;">';
h += '<div class="picker"></div>';
h += '</div>';
h += '</div>';
const el_window = await UIWindow({
title: i18n('ui_colors'),
icon: null,
uid: null,
is_dir: false,
body_content: h,
is_resizable: false,
is_droppable: false,
has_head: true,
stay_on_top: true,
selectable_body: false,
draggable_body: false,
allow_context_menu: false,
show_in_taskbar: false,
window_class: 'window-alert',
dominant: true,
width: 350,
window_css: {
height: 'initial',
},
body_css: {
width: 'initial',
padding: '20px',
'background-color': `hsla(
var(--primary-hue),
var(--primary-saturation),
var(--primary-lightness),
var(--primary-alpha))`,
'backdrop-filter': 'blur(3px)',
},
...options.window_options,
onAppend: function (window) {
// Initialize the color picker widget
const colorPickerWidget = UIColorPickerWidget($(window).find('.picker'), {
default: initialColor,
onColorChange: (color) => {
// Convert color to HSLA format for theme service
const hsla = colorPickerWidget.getHSLA();
const state = {
hue: hsla.h,
sat: hsla.s,
lig: hsla.l,
alpha: hsla.a,
light_text: hsla.l < 60 ? true : false,
};
svc_theme.apply(state);
},
});
// Store widget reference on window for reset functionality
$(window).data('colorPickerWidget', colorPickerWidget);
},
});
// Reset button handler
$(el_window).find('.reset-colors-btn').on('click', function () {
svc_theme.reset();
// Update color picker to reflect reset values
const colorPickerWidget = $(el_window).data('colorPickerWidget');
if ( colorPickerWidget ) {
const resetHue = svc_theme.get('hue');
const resetSat = svc_theme.get('sat');
const resetLig = svc_theme.get('lig');
const resetAlpha = svc_theme.get('alpha');
const resetColor = hslaToHex8(resetHue, resetSat, resetLig, resetAlpha);
colorPickerWidget.setColor(resetColor);
}
});
return {};
};
export default UIWindowThemeDialog;
+90
View File
@@ -0,0 +1,90 @@
/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
*
* Puter is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import UIWindow from './UIWindow.js';
async function UIWindowWelcome (options) {
options = options ?? {};
let h = '';
// close button containing the multiplication sign
h += '<div class="generic-close-window-button welcome-window-close-button"> &times; </div>';
h += '<div style="display:flex; flex-direction: colum;">';
h += '<div style="overflow: hidden; width: 200px; max-width: 200px; min-width: 200px; background: linear-gradient(45deg, #3d476b, #838eb7); min-height: 400px; padding: 20px; box-sizing: border-box;">';
h += '<img style="display: block; margin: 45px auto 0; width: 270px; opacity: 0.5;" src="data:image/svg+xml,%3C%3Fxml%20version%3D%221.0%22%3F%3E%3Csvg%20width%3D%2248%22%20height%3D%2248%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20xmlns%3Asvg%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3Cg%20class%3D%22layer%22%3E%3Ctitle%3ELayer%201%3C%2Ftitle%3E%3Cg%20id%3D%22svg_1%22%20stroke-width%3D%221%22%20transform%3D%22rotate(90%2024%2023.9997)%22%3E%3Cpolyline%20fill%3D%22none%22%20id%3D%22svg_2%22%20points%3D%2239%2024%2025%2024%2025%2028%22%20stroke%3D%22%23ffffff%22%20stroke-linecap%3D%22square%22%20stroke-miterlimit%3D%2210%22%20stroke-width%3D%221%22%2F%3E%3Cpolyline%20fill%3D%22none%22%20id%3D%22svg_3%22%20points%3D%2235.879%2010.121%2032%2014%2025%2014%2025%2018%22%20stroke%3D%22%23ffffff%22%20stroke-linecap%3D%22square%22%20stroke-miterlimit%3D%2210%22%20stroke-width%3D%221%22%2F%3E%3Cpath%20d%3D%22m13%2C26a10.29%2C10.29%200%200%201%20-7.2%2C-3%22%20fill%3D%22none%22%20id%3D%22svg_4%22%20stroke%3D%22%23ffffff%22%20stroke-linecap%3D%22square%22%20stroke-miterlimit%3D%2210%22%20stroke-width%3D%221%22%2F%3E%3Cpath%20d%3D%22m17%2C31.6a5.83%2C5.83%200%200%201%20-4%2C-5.6a5.73%2C5.73%200%200%201%202%2C-4.4%22%20fill%3D%22none%22%20id%3D%22svg_5%22%20stroke%3D%22%23ffffff%22%20stroke-linecap%3D%22square%22%20stroke-miterlimit%3D%2210%22%20stroke-width%3D%221%22%2F%3E%3Cpath%20d%3D%22m35.88%2C37.88l-3.88%2C-3.88l-7%2C0l0%2C2a9.9%2C9.9%200%200%201%20-10%2C10a9.9%2C9.9%200%200%201%20-10%2C-10a9.06%2C9.06%200%200%201%200.6%2C-3.2a5.63%2C5.63%200%200%201%20-2.6%2C-4.8a5.89%2C5.89%200%200%201%202.8%2C-5a9.99%2C9.99%200%200%201%20-2.8%2C-7a9.9%2C9.9%200%200%201%2010%2C-10l0.4%2C0a5.83%2C5.83%200%200%201%205.6%2C-4a5.89%2C5.89%200%200%201%206%2C6%22%20fill%3D%22none%22%20id%3D%22svg_6%22%20stroke%3D%22%23ffffff%22%20stroke-linecap%3D%22square%22%20stroke-miterlimit%3D%2210%22%20stroke-width%3D%221%22%2F%3E%3Ccircle%20cx%3D%2238%22%20cy%3D%228%22%20data-color%3D%22color-2%22%20fill%3D%22none%22%20id%3D%22svg_7%22%20r%3D%223%22%20stroke%3D%22%23ffffff%22%20stroke-linecap%3D%22square%22%20stroke-miterlimit%3D%2210%22%20stroke-width%3D%221%22%2F%3E%3Ccircle%20cx%3D%2242%22%20cy%3D%2224%22%20data-color%3D%22color-2%22%20fill%3D%22none%22%20id%3D%22svg_8%22%20r%3D%223%22%20stroke%3D%22%23ffffff%22%20stroke-linecap%3D%22square%22%20stroke-miterlimit%3D%2210%22%20stroke-width%3D%221%22%2F%3E%3Ccircle%20cx%3D%2238%22%20cy%3D%2240%22%20data-color%3D%22color-2%22%20fill%3D%22none%22%20id%3D%22svg_9%22%20r%3D%223%22%20stroke%3D%22%23ffffff%22%20stroke-linecap%3D%22square%22%20stroke-miterlimit%3D%2210%22%20stroke-width%3D%221%22%2F%3E%3C%2Fg%3E%3C%2Fg%3E%3C%2Fsvg%3E">';
h += '</div>';
h += '<div style="flex-grow: 1; padding-left: 50px; padding-top: 70px; padding-right: 50px;">';
h += `<h1 style="font-size: 25px; font-weight: 300; -webkit-font-smoothing: antialiased; color: #545763;">${i18n('welcome_title')}</h1>`;
h += `<p style="margin-top: 25px; font-size: 16px; font-weight: 300; -webkit-font-smoothing: antialiased; color: #3e4251;">${i18n('welcome_description')}</p>`;
h += `<button class="welcome-window-get-started" style="font-size: 15px; font-weight: 300; -webkit-font-smoothing: antialiased; cursor: pointer; padding: 8px 20px; border-radius: 5px; text-decoration: none; margin-right: 20px; border: 1px solid #656565 !important; background: none; margin-top: 10px;">${i18n('welcome_get_started')}</button>`;
h += '<div class="welcome-window-footer">';
h += `<a href="/terms" target="_blank">${i18n('welcome_terms')}</a>`;
h += `<a href="/privacy" style="margin-left: 20px;" target="_blank">${i18n('welcome_privacy')}</a>`;
h += `<a href="https://developer.puter.com" style="margin-left: 20px;" target="_blank">${i18n('welcome_developers')}</a>`;
h += `<a href="https://github.com/heyputer/puter" style="margin-left: 20px;" target="_blank">${i18n('welcome_open_source')}</a>`;
h += '</div>';
h += '</div>';
h += '</div>';
const el_window = await UIWindow({
title: i18n('welcome_instant_login_title'),
app: 'instant-login',
single_instance: true,
icon: null,
uid: null,
is_dir: false,
body_content: h,
has_head: false,
selectable_body: false,
allow_context_menu: false,
is_resizable: false,
is_droppable: false,
init_center: true,
allow_native_ctxmenu: false,
allow_user_select: false,
backdrop: true,
close_on_backdrop_click: false,
backdrop_covers_toolbar: true,
width: 650,
height: 'auto',
dominant: true,
show_in_taskbar: false,
draggable_body: true,
fadeIn: 1000,
window_class: 'window-welcome',
on_close: function () {
// save the fact that the user has seen the welcome window
puter.kv.set('has_seen_welcome_window', true).catch(err => console.warn('Could not save has_seen_welcome_window:', err));
},
body_css: {
width: 'initial',
height: '100%',
'background-color': 'rgb(245 247 249)',
'backdrop-filter': 'blur(3px)',
padding: '0',
},
});
$(document).on('click', '.welcome-window-get-started', function () {
$(el_window).close();
});
}
export default UIWindowWelcome;
+66 -3
View File
@@ -117,6 +117,11 @@
--dashboard-bento-usage-surface: #eef2ff;
--dashboard-bento-usage-header-bg: #e0e7ff;
--dashboard-bento-usage-bar-fill: #ea580c;
/* Emerald (matches the green icon accent used elsewhere) */
--dashboard-bento-desktop-icon-bg: #059669;
--dashboard-bento-desktop-icon-shadow: rgba(5, 150, 105, 0.22);
--dashboard-bento-desktop-surface: #ecfdf5;
--dashboard-bento-desktop-header-bg: #d1fae5;
--dashboard-shadow-subtle: rgba(0, 0, 0, 0.04);
--dashboard-shadow-light: rgba(0, 0, 0, 0.06);
@@ -239,6 +244,10 @@ body {
--dashboard-bento-usage-surface: #1c1d2e;
--dashboard-bento-usage-header-bg: #252a42;
--dashboard-bento-usage-bar-fill: #fb923c;
--dashboard-bento-desktop-icon-bg: #10b981;
--dashboard-bento-desktop-icon-shadow: rgba(16, 185, 129, 0.32);
--dashboard-bento-desktop-surface: #16241f;
--dashboard-bento-desktop-header-bg: #172e26;
--dashboard-shadow-subtle: rgba(0, 0, 0, 0.2);
--dashboard-shadow-light: rgba(0, 0, 0, 0.3);
@@ -3343,7 +3352,8 @@ p.myapps-add-error {
}
/* -- Share modal --
A centered card on desktop, a bottom sheet on mobile. Mirrors the item
Responsive, from-scratch replacement for UIWindowShare in the Dashboard:
a centered card on desktop, a bottom sheet on mobile. Mirrors the item
properties modal's shell so the two read as one system. */
.share-modal-overlay {
position: fixed;
@@ -3704,8 +3714,9 @@ select.share-modal-row-mode:disabled {
font-size: 16px;
}
/* Recipient suggestions. The structure lives in style.css; only the palette
is set here so the list picks up the dashboard's tokens in both themes. */
/* Recipient suggestions. The structure lives in style.css, shared with the
desktop share dialog; only the palette is restated here so the list picks
up the dashboard's tokens in both themes. */
.share-modal {
--share-suggest-bg: var(--dashboard-card-background);
--share-suggest-border: var(--dashboard-border);
@@ -7375,6 +7386,11 @@ body.myapps-reordering .myapps-tile {
color: #fff;
}
.dashboard .bento-card-fancy-icon-desktop {
background-color: var(--dashboard-bento-desktop-icon-bg);
color: #fff;
}
.dashboard .bento-card-fancy-text {
display: flex;
flex-direction: column;
@@ -7537,6 +7553,41 @@ body.myapps-reordering .myapps-tile {
color: var(--dashboard-text-tertiary);
}
/* Open Desktop bento card (full width; links to the desktop interface) */
.dashboard .bento-desktop {
grid-column: 1 / -1;
display: flex;
align-items: center;
gap: 14px;
padding: 18px 24px;
background-color: var(--dashboard-bento-desktop-header-bg);
text-decoration: none;
color: inherit;
transition: box-shadow 0.15s ease;
}
@media (hover: hover) {
.dashboard .bento-desktop:hover {
box-shadow:
0 2px 4px var(--dashboard-shadow-subtle),
0 10px 28px var(--dashboard-bento-desktop-icon-shadow);
}
.dashboard .bento-desktop:hover .bento-desktop-arrow {
transform: translateX(3px);
color: var(--dashboard-text-primary);
}
}
.dashboard .bento-desktop-arrow {
margin-left: auto;
font-size: 22px;
font-weight: 300;
line-height: 1;
color: var(--dashboard-text-hint);
transition: transform 0.15s ease, color 0.15s ease;
}
/* Usage bento card (cool indigo surfaces; orange bars stay as progress accent) */
.dashboard .bento-usage {
grid-column: 1 / -1;
@@ -7859,6 +7910,11 @@ body.myapps-reordering .myapps-tile {
gap: 12px;
}
.dashboard .bento-desktop {
padding: 16px 20px;
gap: 12px;
}
.dashboard .bento-card-fancy-icon {
width: 40px;
height: 40px;
@@ -8691,6 +8747,13 @@ body.myapps-reordering .myapps-tile {
margin-left: auto;
}
/* Dashboard mode runs fullpage (which normally hides the minimize button
because there's no taskbar to restore from), but here a minimized app can
be brought back from its Apps-tab tile — so keep the button available. */
body.dashboard-mode .window-minimize-btn {
display: inline;
}
/* Fullpage mode sizes .window-body-app to 100% because fullpage windows have
no titlebar — but dashboard-mode app windows WITH a head still lose 29px to
it, so compensate for those. Headless dashboard app windows
+1374 -27
View File
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,54 @@
/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
*
* Puter is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
console.debug('[puter] modify-user-options-menu loaded');
$(window).on('ctxmenu-will-open', (event) => {
if ( event.detail.options?.id === 'user-options-menu' ) {
// Define array of new menu items
const newMenuItems = [
// Separator
'-',
// 'Developer', opens developer site in new tab
{
id: 'go_to_developer_site',
html: 'Developer<svg style="width: 11px; height: 11px; margin-left:2px;" height="32" viewBox="0 0 32 32" width="32" xmlns="http://www.w3.org/2000/svg"><path d="m26 28h-20a2.0027 2.0027 0 0 1 -2-2v-20a2.0027 2.0027 0 0 1 2-2h10v2h-10v20h20v-10h2v10a2.0027 2.0027 0 0 1 -2 2z"/><path d="m20 2v2h6.586l-8.586 8.586 1.414 1.414 8.586-8.586v6.586h2v-10z"/><path d="m0 0h32v32h-32z" fill="none"/></svg>',
html_active: 'Developer<svg style="width: 11px; height: 11px; margin-left:2px;" height="32" viewBox="0 0 32 32" width="32" xmlns="http://www.w3.org/2000/svg"> <path d="m26 28h-20a2.0027 2.0027 0 0 1 -2-2v-20a2.0027 2.0027 0 0 1 2-2h10v2h-10v20h20v-10h2v10a2.0027 2.0027 0 0 1 -2 2z" style="fill: rgb(255, 255, 255);"/> <path d="m20 2v2h6.586l-8.586 8.586 1.414 1.414 8.586-8.586v6.586h2v-10z" style="fill: rgb(255, 255, 255);"/> <path d="m0 0h32v32h-32z" fill="none"/> </svg>',
action: function () {
window.open('https://developer.puter.com', '_blank');
},
},
];
// Find the position of 'contact_us'
const items = event.detail.options.items;
const insertBeforeIndex = items.findIndex(item => item.id === 'contact_us');
// 'contact_us' not found, append new items at the end
if ( insertBeforeIndex === -1 ) {
event.detail.options.items = [...items, ...newMenuItems];
return;
}
// 'contact_us' found, insert new items before it
const firstHalf = items.slice(0, insertBeforeIndex);
const secondHalf = items.slice(insertBeforeIndex);
event.detail.options.items = [...firstHalf, ...newMenuItems, ...secondHalf];
}
});
+13 -3
View File
@@ -22,7 +22,6 @@ import { encode } from 'html-entities';
import { loadLocale } from './i18n/embedI18n.js';
import UIWindowAppFeedback from './UI/UIWindowAppFeedback.js';
import { embedSession } from './helpers/embedSession.js';
import { overlayGone } from './helpers/overlayGone.js';
window.$ = window.jQuery = jQuery;
window.html_encode = value => encode(String(value ?? ''), { mode: 'nonAsciiPrintable' });
@@ -38,6 +37,18 @@ const localeReady = loadLocale(window.locale);
/** Answers only the page frame-ancestors pinned, which the feedback is for. */
const tellHost = (data) => window.parent.postMessage(data, config.hostOrigin);
/** Resolves once the dialog's overlay has left the page, after its success pane and exit. */
const overlayGone = () => new Promise((resolve) => {
const gone = () => !document.querySelector('.app-feedback-overlay');
if ( gone() ) return resolve();
const observer = new MutationObserver(() => {
if ( ! gone() ) return;
observer.disconnect();
resolve();
});
observer.observe(document.body, { childList: true });
});
/**
* Shows the app feedback dialog for the framing page, as the signed-in user it
* names. Without that user's session, or with an email still to confirm, the
@@ -64,8 +75,7 @@ async function run () {
let sent = false;
try {
sent = await UIWindowAppFeedback({ origin: config.hostOrigin, source: 'web' });
// After its success pane and exit.
await overlayGone(document, '.app-feedback-overlay');
await overlayGone();
} catch (e) {
console.error('feedback embed: dialog failed', e);
}
+7 -3
View File
@@ -114,6 +114,8 @@ if ( window.user_preferences === null ) {
window.window_stack = [];
window.toolbar_height = 0;
window.default_taskbar_height = 50;
window.taskbar_height = window.default_taskbar_height;
window.upload_progress_hide_delay = 500;
window.active_uploads = {};
window.copy_progress_hide_delay = 1000;
@@ -157,12 +159,14 @@ window.child_launch_callbacks = {};
// Is puter being loaded inside an iframe?
if ( window.location !== window.parent.location ) {
window.is_embedded = true;
// taskbar is not needed in embedded mode
window.taskbar_height = 0;
} else {
window.is_embedded = false;
}
// calculate desktop height and width
window.desktop_height = window.innerHeight - window.toolbar_height;
window.desktop_height = window.innerHeight - window.toolbar_height - window.taskbar_height;
window.desktop_width = window.innerWidth;
// {id: {left: 0, top: 0}}
@@ -176,7 +180,7 @@ $(window).on( 'resize', function () {
if ( window.a_window_is_resizing ) return;
if ( window.a_window_sidebar_is_resizing ) return;
const new_desktop_height = window.innerHeight - window.toolbar_height;
const new_desktop_height = window.innerHeight - window.toolbar_height - window.taskbar_height;
const new_desktop_width = window.innerWidth;
window.desktop_height = new_desktop_height;
@@ -184,7 +188,7 @@ $(window).on( 'resize', function () {
// Update all maximized windows to fit the new viewport
$('.window[data-is_maximized="1"]').each(function () {
window.update_maximized_window(this);
window.update_maximized_window_for_taskbar(this);
});
});
+41 -4
View File
@@ -615,7 +615,7 @@ window.check_fsentry_against_allowed_file_types_string = function (fsentry, allo
window.refresh_user_data = async (auth_token) => {
let whoami;
try {
whoami = await puter.os.user();
whoami = await puter.os.user({ query: 'icon_size=64' });
} catch (e) {
// Ignored
}
@@ -677,7 +677,6 @@ window.update_auth_data = async (auth_token, user) => {
const to_storable_user = user => {
const storable_user = { ...user };
// Older sessions stored taskbar_items, with app icons, in these copies.
delete storable_user.taskbar_items;
return storable_user;
};
@@ -748,6 +747,11 @@ window.update_auth_data = async (auth_token, user) => {
window.public_path = `/${ window.user.username }/Public`;
window.shared_path = 'puter://shared';
if ( window.user !== null && !window.user.is_temp ) {
$('.user-options-login-btn, .user-options-create-account-btn').hide();
$('.user-options-menu-btn').show();
}
// Search and store user templates (non-blocking)
window.available_templates();
};
@@ -1727,13 +1731,14 @@ window.trigger_download = (paths) => {
/**
* Updates every Trash icon in the UI to reflect whether the trash is empty:
* desktop items (and shortcuts to Trash), open explorer window head icons,
* and the Dashboard's Files-tab sidebar.
* the taskbar item, desktop items (and shortcuts to Trash), open explorer
* window head icons, and the Dashboard's Files-tab sidebar.
*
* @param {boolean} is_empty - Whether the trash is empty
*/
window.update_trash_icons = function (is_empty) {
const icon = is_empty ? window.icons['trash.svg'] : window.icons['trash-full.svg'];
$('[data-app="trash"]').find('.taskbar-icon > img').attr('src', icon);
$(`.item[data-path="${html_encode(window.trash_path)}" i], .item[data-shortcut_to_path="${html_encode(window.trash_path)}" i]`).find('.item-icon > img').attr('src', icon);
$(`.window[data-path="${html_encode(window.trash_path)}" i]`).find('.window-head-icon').attr('src', icon);
$('.directories [data-folder="Trash"] img').attr('src', icon);
@@ -2027,6 +2032,7 @@ window.move_items = async function (el_items, dest_path, is_undo = false) {
if ( $(el_item).attr('data-is_dir') === '1' ) {
// Its websites stay registered: the server doesn't
// serve a root in Trash, and restoring brings them back.
$(`.mywebsites-dir-path[data-uuid="${$(el_item).attr('data-uid')}"]`).remove();
// remove the website badge from all instances of the dir
$(`.item[data-uid="${$(el_item).attr('data-uid')}"]`).find('.item-has-website-badge').fadeOut(300);
}
@@ -2189,6 +2195,37 @@ window.move_items = async function (el_items, dest_path, is_undo = false) {
}
};
/**
* Refreshes the desktop background based on the user's settings.
* If the user has set a custom desktop background URL or color, it will use that.
* If not, it defaults to a specific wallpaper image.
*
* @global
* @function
* @fires set_desktop_background - Calls this global function to set the desktop background.
*
* @example
* // This will refresh the desktop background according to the user's preference or defaults.
* window.refresh_desktop_background();
*/
window.refresh_desktop_background = function () {
if ( window.user && (window.user.desktop_bg_url !== null || window.user.desktop_bg_color !== null) ) {
window.set_desktop_background({
url: window.user.desktop_bg_url,
fit: window.user.desktop_bg_fit,
color: window.user.desktop_bg_color,
});
}
// default background
else {
let wallpaper = (window.gui_env === 'prod') ? 'https://puter-assets.b-cdn.net/wallpaper.webp' : '/src/images/wallpaper.webp';
window.set_desktop_background({
url: wallpaper,
fit: 'cover',
});
}
};
window.determine_website_url = function (fsentry_path) {
// The address an item has under a site serving a folder above it. The
// site's folder and address come with its root_dir.
+2 -2
View File
@@ -29,8 +29,8 @@ const FALLBACK_ATTR = 'data-icon-fallback';
/**
* Pick the URL to load an app's icon from, plus the one URL to retry with.
*
* @param {Object} app - App record from the backend (launch app, installedApps
* row). Reads `iconCdnUrl` and `iconUrl`/`icon`.
* @param {Object} app - App record from the backend (taskbar item, launch app,
* installedApps row). Reads `iconCdnUrl` and `iconUrl`/`icon`.
* @param {string} [defaultIcon] - Used when the app carries no icon at all.
* @returns {{ src: string; fallback: string }} `fallback` is empty when there
* is nothing left to try.
+31 -12
View File
@@ -20,7 +20,10 @@
import UIAlert from '../UI/UIAlert.js';
import UIWindowItemProperties from '../UI/UIWindowItemProperties.js';
import UIWindowPublishWorker from '../UI/UIWindowPublishWorker.js';
import UIWindowShare from '../UI/UIWindowShare.js';
import publish_as_website from './publishAsWebsite.js';
import ensure_can_publish from './ensureCanPublish.js';
import open_item from './openItem.js';
import openWithAI from './openWithAI.js';
import launch_app from './launchApp.js';
@@ -43,9 +46,9 @@ import { is_default_app } from './defaultApp.js';
* @param {Function} options.onOpen - Optional custom open handler (used by Dashboard)
* @param {boolean} options.openWithInNewTab - Open the "Open With" apps in a new browser tab instead of an in-page window (used by Dashboard)
* @param {Function} options.onShowProperties - Optional custom properties handler (used by Dashboard); receives {name, path, uid, element}
* @param {Function} options.onShare - Opens sharing for the item; Share is left out of the menu without it. Receives {name, path, uid, element}
* @param {Function} options.onShare - Optional custom share handler (used by Dashboard); receives {name, path, uid, element}
* @param {Function} options.onPublishWebsite - Optional custom publish-as-website handler (used by Dashboard); receives {uid, name, path}
* @param {Function} options.onPublishWorker - Publishes the file as a worker; Publish as Worker is left out of the menu without it. Receives {uid, name, path}
* @param {Function} options.onPublishWorker - Optional custom publish-as-worker handler (used by Dashboard); receives {uid, name, path}
* @param {Function} options.onPasteInto - Optional custom paste handler (used by Dashboard); receives the folder's path
* @param {Function} options.onRemovedFromShared - Optional, called once Remove from Shared has dropped the user's own access (used by Dashboard)
* @returns {Promise<Array>} Array of context menu items
@@ -161,16 +164,22 @@ const generate_file_context_menu = async function (options) {
// Publish as Worker
// -------------------------------------------
// The backend refuses deploys from a file someone else owns.
if ( !is_trashed && !is_trash && !is_not_mine && !fsentry.is_dir && $(el_item).attr('data-name').toLowerCase().endsWith('.js') && options.onPublishWorker ) {
if ( !is_trashed && !is_trash && !is_not_mine && !fsentry.is_dir && $(el_item).attr('data-name').toLowerCase().endsWith('.js') ) {
menu_items.push({
html: i18n('publish_as_serverless_worker'),
disabled: is_worker,
onClick: function () {
options.onPublishWorker({
onClick: async function () {
const target = {
uid: fsentry.uid,
name: $(el_item).attr('data-name'),
path: $(el_item).attr('data-path'),
});
};
if ( options.onPublishWorker ) {
options.onPublishWorker(target);
return;
}
if ( ! await ensure_can_publish(true) ) return;
UIWindowPublishWorker(target.uid, target.name, target.path);
},
});
}
@@ -212,15 +221,25 @@ const generate_file_context_menu = async function (options) {
// -------------------------------------------
// Share
// -------------------------------------------
if ( !is_trash && !is_trashed && may_share && options.onShare ) {
if ( !is_trash && !is_trashed && may_share ) {
menu_items.push({
html: i18n('share_ellipsis'),
onClick: async function () {
options.onShare({
name: $(el_item).attr('data-name'),
// The Dashboard swaps in its own responsive modal via this hook;
// everywhere else falls back to the desktop share window.
if ( options.onShare ) {
options.onShare({
name: $(el_item).attr('data-name'),
path: $(el_item).attr('data-path'),
uid: $(el_item).attr('data-uid'),
element: el_item,
});
return;
}
UIWindowShare({
path: $(el_item).attr('data-path'),
uid: $(el_item).attr('data-uid'),
element: el_item,
name: $(el_item).attr('data-name'),
});
},
});
@@ -465,7 +484,7 @@ const generate_file_context_menu = async function (options) {
left = left > (window.innerWidth - window_width) ? (window.innerWidth - window_width) : left;
let top = $(el_item).position().top + $(el_item).height();
top = top > (window.innerHeight - (window_height + window.toolbar_height)) ? (window.innerHeight - (window_height + window.toolbar_height)) : top;
top = top > (window.innerHeight - (window_height + window.taskbar_height + window.toolbar_height)) ? (window.innerHeight - (window_height + window.taskbar_height + window.toolbar_height)) : top;
UIWindowItemProperties(
$(el_item).attr('data-name'),
@@ -23,15 +23,18 @@ import jQuery from '../lib/jquery-3.6.1/jquery-3.6.1.min.js';
vi.mock('../UI/UIAlert.js', () => ({ default: vi.fn() }));
vi.mock('../UI/UIWindowItemProperties.js', () => ({ default: vi.fn() }));
vi.mock('../UI/UIWindowPublishWorker.js', () => ({ default: vi.fn() }));
vi.mock('../UI/UIWindowShare.js', () => ({ default: vi.fn() }));
vi.mock('./publishAsWebsite.js', () => ({ default: vi.fn() }));
vi.mock('./ensureCanPublish.js', () => ({ default: vi.fn() }));
vi.mock('./openItem.js', () => ({ default: vi.fn() }));
vi.mock('./openWithAI.js', () => ({ default: vi.fn() }));
vi.mock('./launchApp.js', () => ({ default: vi.fn() }));
vi.mock('./pathOwner.js', () => ({ is_owned_by_me: vi.fn(() => false) }));
vi.mock('./pathOwner.js', () => ({ is_owned_by_me: () => false }));
vi.mock('./sharedAccess.js', () => ({
can_rename: async () => false,
can_restructure: async () => false,
can_share: vi.fn(async () => false),
can_share: async () => false,
invalidate_shared_roots: vi.fn(),
}));
@@ -49,8 +52,6 @@ const { default: generate_file_context_menu } =
await import('./generateFileContextMenu.js');
const { default: launch_app } = await import('./launchApp.js');
const { default: UIAlert } = await import('../UI/UIAlert.js');
const { can_share } = await import('./sharedAccess.js');
const { is_owned_by_me } = await import('./pathOwner.js');
const sharedRow = () => {
const row = document.createElement('div');
@@ -88,62 +89,6 @@ it('does not offer it on a share held through a team', async () => {
);
});
describe('Share', () => {
const shareItem = async (options) => {
can_share.mockResolvedValueOnce(true);
const items = await generate_file_context_menu({
element: sharedRow(),
fsentry: { name: 'notes.txt', path: '/ann/uid-1/notes.txt' },
associated_app_name: 'editor',
...options,
});
return items.find((item) => item !== '-' && item.html === 'share_ellipsis');
};
it('hands the item to onShare', async () => {
const onShare = vi.fn();
await (await shareItem({ onShare })).onClick();
expect(onShare).toHaveBeenCalledWith(expect.objectContaining({
name: 'notes.txt',
path: '/ann/uid-1/notes.txt',
}));
});
it('is left out without onShare', async () => {
expect(await shareItem({})).toBeUndefined();
});
});
describe('Publish as Worker', () => {
const publishItem = async (options) => {
is_owned_by_me.mockReturnValueOnce(true);
const row = document.createElement('div');
row.setAttribute('data-path', '/me/worker.js');
row.setAttribute('data-name', 'worker.js');
const items = await generate_file_context_menu({
element: row,
fsentry: { uid: 'file-1', name: 'worker.js', path: '/me/worker.js' },
associated_app_name: 'editor',
...options,
});
return items.find((item) => item !== '-' && item.html === 'publish_as_serverless_worker');
};
it('hands the file to onPublishWorker', async () => {
const onPublishWorker = vi.fn();
await (await publishItem({ onPublishWorker })).onClick();
expect(onPublishWorker).toHaveBeenCalledWith({
uid: 'file-1',
name: 'worker.js',
path: '/me/worker.js',
});
});
it('is left out without onPublishWorker', async () => {
expect(await publishItem({})).toBeUndefined();
});
});
describe('Remove from Shared', () => {
const remove = async (fsentry) => {
const row = sharedRow();
+14 -1
View File
@@ -625,7 +625,7 @@ const runLaunch = async (options) => {
window_height = parseFloat(app_info.metadata.window_size.height);
} if ( options.maximized )
{
window_height = `calc(100% - ${window.toolbar_height + 1}px)`;
window_height = `calc(100% - ${window.taskbar_height + window.toolbar_height + 1}px)`;
}
// top
@@ -678,6 +678,18 @@ const runLaunch = async (options) => {
title = options.file_path ? path.basename(options.file_path) : title;
}
// show_in_taskbar
// Deliberately keyed on the app's own `background`, not on this launch's:
// an app that always runs windowless has nothing to put in the taskbar,
// ever. A background *launch* is a normal app that happens to start
// hidden, so it keeps asking for an item — UIWindow just holds it back
// until the window is first shown (see its taskbar block).
let show_in_taskbar = app_info.background ? false : window_options?.show_in_taskbar;
if ( window_options?.show_in_taskbar !== undefined )
{
show_in_taskbar = window_options.show_in_taskbar;
}
// has_head
let has_head = app_info.metadata?.has_head !== undefined ? app_info.metadata.has_head : window_options?.has_head;
if ( app_info.metadata?.hide_titlebar !== undefined && typeof app_info.metadata.hide_titlebar === 'boolean' && app_info.metadata.hide_titlebar === true )
@@ -736,6 +748,7 @@ const runLaunch = async (options) => {
...window_options,
is_resizable: window_resizable,
has_head: has_head,
show_in_taskbar: show_in_taskbar,
update_window_url: update_window_url,
custom_path: custom_path,
});
Loaded 100 of 182 files, more files were not shown because too many files have changed in this diff. Show more