Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions .changeset/orientation-initial.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
---
"@solid-primitives/orientation": minor
---

Add `@solid-primitives/orientation` package (Stage 0)

New primitives for tracking screen orientation via the Screen Orientation API.

- **`makeOrientation(onChange)`** — Non-reactive base primitive. Attaches a listener for `screen.orientation` `change` events (or the legacy `orientationchange` event as fallback) and returns a cleanup function. Does not fire on mount.
- **`createOrientation()`** — Reactive primitive returning `angle` and `type` signal accessors, initialized to the current orientation and updated on every change. SSR-safe: returns static defaults (`angle: 0`, `type: "portrait-primary"`) on the server.

Peer dependencies: `solid-js@^2.0.0-beta.10` and `@solidjs/web@^2.0.0-beta.10`.
21 changes: 21 additions & 0 deletions packages/orientation/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2021 Solid Primitives Working Group

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
87 changes: 87 additions & 0 deletions packages/orientation/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
<p>
<img width="100%" src="https://assets.solidjs.com/banner?type=Primitives&background=tiles&project=orientation" alt="Solid Primitives orientation">
</p>

# @solid-primitives/orientation

[![size](https://img.shields.io/bundlephobia/minzip/@solid-primitives/orientation?style=for-the-badge&label=size)](https://bundlephobia.com/package/@solid-primitives/orientation)
[![version](https://img.shields.io/npm/v/@solid-primitives/orientation?style=for-the-badge)](https://www.npmjs.com/package/@solid-primitives/orientation)
[![stage](https://img.shields.io/endpoint?style=for-the-badge&url=https%3A%2F%2Fraw.githubusercontent.com%2Fsolidjs-community%2Fsolid-primitives%2Fmain%2Fassets%2Fbadges%2Fstage-0.json)](https://github.com/solidjs-community/solid-primitives#contribution-process)

Primitives for tracking screen orientation via the [Screen Orientation API](https://developer.mozilla.org/en-US/docs/Web/API/Screen_Orientation_API).

- [`makeOrientation`](#makeorientation) — Non-reactive listener; attaches a callback for each orientation change and returns a cleanup function.
- [`createOrientation`](#createorientation) — Reactive primitive; returns `angle` and `type` as signal accessors that update on orientation change.

## Installation

```bash
npm install @solid-primitives/orientation
# or
yarn add @solid-primitives/orientation
# or
pnpm add @solid-primitives/orientation
```

## `makeOrientation`

A non-reactive base primitive. Attaches a listener for screen orientation changes and returns a cleanup function. The callback fires on every subsequent change but **not** on mount — use `createOrientation` if you need the initial value reactively.

Uses `screen.orientation` when available, falling back to the legacy `orientationchange` event on `window`.

```ts
import { makeOrientation } from "@solid-primitives/orientation";

const cleanup = makeOrientation(({ angle, type }) => {
console.log(angle); // 0 | 90 | 180 | 270
console.log(type); // "portrait-primary" | "landscape-primary" | ...
});

// remove listener when done
cleanup();
```

## `createOrientation`

A reactive primitive that tracks the screen orientation. Returns `angle` and `type` signal accessors, initialized to the current orientation and updated on every change. Automatically removes the event listener on cleanup.

On the server, returns static defaults: `angle: 0`, `type: "portrait-primary"`.

```ts
import { createOrientation } from "@solid-primitives/orientation";
import { createEffect } from "solid-js";

const { angle, type } = createOrientation();

createEffect(
() => ({ angle: angle(), type: type() }),
({ angle, type }) => {
console.log(angle); // 0 | 90 | 180 | 270
console.log(type); // "portrait-primary" | "landscape-primary" | ...
}
);
```

## Types

```ts
export type OrientationType =
| "landscape-primary"
| "landscape-secondary"
| "portrait-primary"
| "portrait-secondary"
| "unknown";

export interface OrientationState {
readonly angle: number;
readonly type: OrientationType;
}
```

## Browser Support

`screen.orientation` is supported in Chrome 38+, Firefox 43+, and Safari 16.4+. On older browsers the primitive falls back to the deprecated `window.orientationchange` event.

## Changelog

See [CHANGELOG.md](./CHANGELOG.md)
23 changes: 23 additions & 0 deletions packages/orientation/dev/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { type Component } from "solid-js";
import { createOrientation } from "../src/index.js";

const App: Component = () => {
const { angle, type } = createOrientation();

return (
<div class="box-border flex min-h-screen w-full flex-col items-center justify-center space-y-4 bg-gray-800 p-24 text-white">
<div class="wrapper-v">
<h4>Screen Orientation</h4>
<p class="caption">Rotate your device or resize to a narrow viewport to see changes.</p>
<p>
<strong>Angle:</strong> {angle()}°
</p>
<p>
<strong>Type:</strong> {type()}
</p>
</div>
</div>
);
};

export default App;
67 changes: 67 additions & 0 deletions packages/orientation/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
{
"name": "@solid-primitives/orientation",
"version": "0.0.100",
"description": "Primitives to track screen orientation using the Screen Orientation API",
"author": "David Di Biase <dave@solidjs.com>",
"contributors": [],
"license": "MIT",
"homepage": "https://primitives.solidjs.community/package/orientation",
"repository": {
"type": "git",
"url": "git+https://github.com/solidjs-community/solid-primitives.git"
},
"bugs": {
"url": "https://github.com/solidjs-community/solid-primitives/issues"
},
"primitive": {
"name": "orientation",
"stage": 0,
"list": [
"makeOrientation",
"createOrientation"
],
"category": "Sensors"
},
"keywords": [
"solid",
"orientation",
"screen",
"device",
"primitives"
],
"private": false,
"sideEffects": false,
"files": [
"dist"
],
"type": "module",
"module": "./dist/index.js",
"types": "./dist/index.d.ts",
"browser": {},
"exports": {
"import": {
"@solid-primitives/source": "./src/index.ts",
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
}
},
"typesVersions": {},
"scripts": {
"dev": "node --import=@nothing-but/node-resolve-ts --experimental-transform-types ../../scripts/dev.ts",
"build": "node --import=@nothing-but/node-resolve-ts --experimental-transform-types ../../scripts/build.ts",
"vitest": "vitest -c ../../configs/vitest.config.ts",
"test": "pnpm run vitest",
"test:ssr": "pnpm run vitest --mode ssr"
},
"peerDependencies": {
"@solidjs/web": "^2.0.0-beta.10",
"solid-js": "^2.0.0-beta.10"
},
"dependencies": {
"@solid-primitives/utils": "workspace:^"
},
"devDependencies": {
"@solidjs/web": "2.0.0-beta.10",
"solid-js": "2.0.0-beta.10"
}
}
121 changes: 121 additions & 0 deletions packages/orientation/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
import { createSignal, onCleanup, type Accessor } from "solid-js";
import { isServer } from "@solidjs/web";
import { noop } from "@solid-primitives/utils";

export type OrientationType =
| "landscape-primary"
| "landscape-secondary"
| "portrait-primary"
| "portrait-secondary"
| "unknown";

export interface OrientationState {
readonly angle: number;
readonly type: OrientationType;
}

const DEFAULT_STATE: OrientationState = { angle: 0, type: "portrait-primary" };

function angleToType(angle: number): OrientationType {
switch (angle) {
case 0:
return "portrait-primary";
case 180:
return "portrait-secondary";
case 90:
return "landscape-primary";
case -90:
case 270:
return "landscape-secondary";
default:
return "unknown";
}
}

function readOrientation(): OrientationState {
const orient = screen.orientation as ScreenOrientation | undefined;
if (orient) {
return { angle: orient.angle, type: orient.type as OrientationType };
}
const angle = ((window as any).orientation as number | undefined) ?? 0;
return { angle, type: angleToType(angle) };
}

/**
* Attaches a listener for screen orientation changes.
*
* Uses the [Screen Orientation API](https://developer.mozilla.org/en-US/docs/Web/API/Screen_Orientation_API)
* when available, falling back to the deprecated `orientationchange` event.
*
* @param onChange called with the new {@link OrientationState} on every orientation change
* @returns cleanup function to remove the listener
*
* @example
* ```ts
* const cleanup = makeOrientation(({ angle, type }) => {
* console.log(angle, type);
* });
* // remove listener
* cleanup();
* ```
*/
export function makeOrientation(onChange: (state: OrientationState) => void): VoidFunction {
if (isServer) return noop;

const handler = () => onChange(readOrientation());
const orient = screen.orientation as ScreenOrientation | undefined;

if (orient) {
orient.addEventListener("change", handler);
return () => orient.removeEventListener("change", handler);
}

window.addEventListener("orientationchange", handler);
return () => window.removeEventListener("orientationchange", handler);
}

/**
* Creates a reactive primitive tracking the screen orientation.
*
* Returns reactive signals for `angle` (degrees: 0, 90, 180, 270) and `type`
* (e.g. `"portrait-primary"`). On the server, returns static defaults
* (`angle: 0`, `type: "portrait-primary"`).
*
* @returns object with `angle` and `type` signal accessors
*
* @example
* ```ts
* const { angle, type } = createOrientation();
*
* createEffect(
* () => ({ angle: angle(), type: type() }),
* ({ angle, type }) => {
* console.log(angle, type);
* }
* );
* ```
*/
export function createOrientation(): {
angle: Accessor<number>;
type: Accessor<OrientationType>;
} {
if (isServer) {
return {
angle: () => DEFAULT_STATE.angle,
type: () => DEFAULT_STATE.type,
};
}

const initial = readOrientation();
const [angle, setAngle] = createSignal(initial.angle);
const [type, setType] = createSignal<OrientationType>(initial.type);

const cleanup = makeOrientation(state => {
setAngle(state.angle);
setType(state.type);
});

onCleanup(cleanup);

return { angle, type };
}
Loading