~ knotless Search/
↑↓ move↵ open⇧↵ all results

grain.social/grain

photography-focused photo sharing platform

grain.social
1 collaborator
0
2

Grain's own sign-in screen, suggesting accounts as you type

Merged chadtmiller.com asked to merge into feature/hud from grain.social/grain:next/signin

Only what this pull adds. It is built on The next grain.social and grain-ios, drawn by HUD.

ios/Grain/Assets.xcassets/login-bg.imageset/Contents.jsonnew+22−0
@@ -0,0 +1,22 @@
{
"images" : [
{
"filename" : "login-bg.jpg",
"idiom" : "universal",
"scale" : "1x"
},
{
"filename" : "login-bg@2x.jpg",
"idiom" : "universal",
"scale" : "2x"
},
{
"idiom" : "universal",
"scale" : "3x"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
ios/Grain/Assets.xcassets/login-bg.imageset/login-bg.jpgnew+0−0
A binary file, not shown.
ios/Grain/Assets.xcassets/login-bg.imageset/login-bg@2x.jpgnew+0−0
A binary file, not shown.
ios/Grain/Config.swift+5−0
@@ -56,6 +56,10 @@ struct GrainConfig: Sendable {
/// How the device registers for push, and what a tapped notification
/// opens (HUD's docs/views.md, Push); nil where the file has no `push`.
let push: PushPlan?
/// Its sign-in screen (HUD's docs/views.md, Sign-in): heading, lines,
/// whether it offers a new account, and who matches a typed handle;
/// nil where the file has no `signIn`.
let signIn: SignInPlan?
/// The one bundled with the app.
static let bundled: GrainConfig = {
@@ -83,6 +87,7 @@ struct GrainConfig: Sendable {
}
routes = Route.all(in: json)
push = PushPlan(json["push"])
signIn = SignInPlan(app: json)
}
/// A `{name, args}`.
ios/Grain/Shell.swift+6−4
@@ -308,8 +308,10 @@ final class Shell {
/// Sign in to the server as `handle` (or a DID), in the system's browser
/// sheet, the handle sent as the request's `login_hint`, as the HUD app
/// does: every tab then starts afresh as the account.
func signIn(_ handle: String, using web: WebAuthenticationSession) async {
/// does; or, with `create`, as a new account made at the server's
/// sign-up PDS (`prompt=create`, no hint): every tab then starts afresh
/// as the account.
func signIn(_ handle: String = "", create: Bool = false, using web: WebAuthenticationSession) async {
guard !signingIn else { return }
signingIn = true
signInError = nil
@@ -318,7 +320,7 @@ final class Shell {
if hint.hasPrefix("@") { hint = hint.dropFirst() }
do {
let auth = try await AuthServer.discover(serverURL)
let request = SignInRequest(server: auth, hint: String(hint))
let request = SignInRequest(server: auth, hint: String(hint), create: create)
let callback = try await web.authenticate(using: request.url, callbackURLScheme: AuthServer.callbackScheme, preferredBrowserSession: .shared)
let tokens = try await auth.exchange(request.code(from: callback), for: request)
if session != nil {
@@ -326,7 +328,7 @@ final class Shell {
// The account signed in until now stops getting this device's pushes.
await push?.signingOut()
}
let named = hint.isEmpty || hint.hasPrefix("did:") ? nil : hint.lowercased()
let named = create || hint.isEmpty || hint.hasPrefix("did:") ? nil : hint.lowercased()
session = try AccountSession.start(server: auth, tokens: tokens, handle: named, ended: ended)
askingSignIn = false
start()
ios/Grain/SignInSheet.swift+328−39
@@ -1,76 +1,365 @@
import HUDKit
import SwiftUI
/// Signing in, by handle, through the HUD server's OAuth (HUDKit's
/// `AuthServer` and `SignInRequest`), in the system's browser sheet.
/// Signing in, as grain-ios's LoginView, from what the app file's `signIn`
/// says (HUDKit's `SignInPlan`): over Grain's photo, darkened, its wordmark,
/// the plan's heading and line, the handle field with the accounts its
/// typeahead finds for what is typed (200 ms after typing stops; arrows and
/// tab move through them, return picks one, a tap picks one and signs in),
/// Sign in, Create account where the plan offers one, and its legal line,
/// whose links open in Safari over the sheet. Signing in goes through the
/// HUD server's OAuth (HUDKit's `AuthServer` and `SignInRequest`), in the
/// system's browser sheet; what went wrong shows in red. Without a plan:
/// "Sign in to Grain", and no suggestions.
struct SignInSheet: View {
let shell: Shell
@State private var handle = ""
@State private var searching = false
@State private var suggestions: [FoundActor] = []
@State private var search: Task<Void, Never>?
/// The handle a suggestion filled in, which is not looked up again.
@State private var picked: String?
@State private var highlighted: Int?
@State private var page: Page?
@Namespace private var highlight
@FocusState private var typing: Bool
@Environment(\.webAuthenticationSession) private var web
@Environment(\.dismiss) private var dismiss
private var plan: SignInPlan {
shell.config.signIn ?? SignInPlan(title: "Sign in to \(shell.config.name)", site: URL(string: "https://\(shell.config.domain)"))
}
/// The wordmark Home is titled with, else the app's name.
private var wordmark: String {
shell.config.tabs.lazy.compactMap(\.wordmark).first ?? shell.config.name
}
private var name: String { handle.trimmingCharacters(in: .whitespaces) }
private var ready: Bool { !name.isEmpty && !shell.signingIn }
var body: some View {
NavigationStack {
VStack(spacing: Space.s4) {
Text("Sign in to \(shell.config.name)")
.font(Font(Titles.display(size: 28)))
.frame(maxWidth: .infinity, alignment: .leading)
TextField("alice.bsky.social", text: $handle)
.textContentType(.username)
.textInputAutocapitalization(.never)
.autocorrectionDisabled()
.keyboardType(.URL)
.submitLabel(.go)
.focused($typing)
.onSubmit(go)
.padding(.horizontal, Space.s4)
.frame(minHeight: 50)
.background(.field, in: .capsule)
.accessibilityLabel("Your handle")
Button(action: go) {
Group {
if shell.signingIn {
ProgressView().tint(.white)
GeometryReader { geo in
ScrollViewReader { proxy in
ScrollView {
VStack(spacing: 0) {
Spacer(minLength: suggestions.isEmpty ? 40 : 20)
form
Spacer(minLength: 40)
}
.frame(minHeight: geo.size.height)
}
.scrollDismissesKeyboard(.interactively)
.scrollIndicators(.hidden)
.onChange(of: suggestions) { _, now in
if now.isEmpty {
highlighted = nil
} else {
Text("Sign in").font(.body.weight(.semibold))
if let at = highlighted, at >= now.count { highlighted = now.count - 1 }
withAnimation { proxy.scrollTo("suggestions", anchor: .bottom) }
}
}
.frame(maxWidth: .infinity, minHeight: 50)
}
.buttonStyle(.borderedProminent)
.buttonBorderShape(.capsule)
.disabled(!ready)
Group {
if let failure = shell.signInError {
Text(failure).foregroundStyle(.danger)
} else {
Text("With your Bluesky or other atproto account.").foregroundStyle(.muted)
.onChange(of: highlighted) { _, at in
guard let at, suggestions.indices.contains(at) else { return }
withAnimation(.easeInOut(duration: 0.2)) { proxy.scrollTo(suggestions[at].id, anchor: .center) }
}
}
.font(.footnote)
.multilineTextAlignment(.center)
Spacer()
}
.padding(Space.s5)
.background(.tileSurface)
.background {
Image("login-bg")
.resizable()
.scaledToFill()
.overlay(Color.black.opacity(0.4))
.ignoresSafeArea()
.accessibilityHidden(true)
}
.toolbar {
ToolbarItem(placement: .cancellationAction) {
Button("Cancel") { dismiss() }
.tint(.white)
}
}
.toolbarBackground(.hidden, for: .navigationBar)
}
.environment(\.colorScheme, .dark)
.environment(\.openURL, OpenURLAction { url in
page = Page(url: url)
return .handled
})
.sheet(item: $page) { page in
SafariView(url: page.url).ignoresSafeArea()
}
.presentationDetents([.medium])
.presentationDetents([.large])
.onChange(of: handle) { lookUp() }
.onAppear { typing = true }
.onDisappear { search?.cancel() }
}
private var form: some View {
VStack(spacing: 0) {
Text(wordmark)
.font(Font(Titles.display(size: 44)))
.foregroundStyle(.white)
.padding(.bottom, suggestions.isEmpty ? 48 : 20)
.accessibilityAddTraits(.isHeader)
if suggestions.isEmpty {
Text(plan.title)
.font(.title3.weight(.semibold))
.foregroundStyle(.white)
.multilineTextAlignment(.center)
.padding(.bottom, 6)
if let text = plan.text {
Text(plan.linked(text))
.font(.footnote)
.foregroundStyle(.white.opacity(0.7))
.tint(.white)
.multilineTextAlignment(.center)
}
}
VStack(spacing: 16) {
field
if !suggestions.isEmpty { list }
signInButton
if let create = plan.create { creating(create) }
if let legal = plan.legal {
Text(plan.linked(legal))
.font(.caption2)
.foregroundStyle(.white.opacity(0.5))
.tint(.white.opacity(0.7))
.multilineTextAlignment(.center)
}
}
.padding(24)
if let failure = shell.signInError {
Text(failure)
.font(.caption)
.foregroundStyle(.red)
.multilineTextAlignment(.center)
.padding(.horizontal, 24)
}
}
}
private var field: some View {
HStack(spacing: 10) {
Image(systemName: "at")
.font(.body.weight(.medium))
.foregroundStyle(.white.opacity(0.5))
.accessibilityHidden(true)
let placeholder = plan.placeholder ?? "alice.bsky.social"
TextField(placeholder, text: $handle, prompt: Text(placeholder).foregroundStyle(.white.opacity(0.5)))
.foregroundStyle(.white)
.textContentType(.username)
.textInputAutocapitalization(.never)
.autocorrectionDisabled()
.keyboardType(.URL)
.submitLabel(.go)
.focused($typing)
.onSubmit(submit)
.onKeyPress(.downArrow) { move(by: 1) }
.onKeyPress(.upArrow) { move(by: -1) }
.onKeyPress(.tab) { move(by: 1, wrap: true) }
.accessibilityLabel("Your handle")
if searching {
ProgressView()
.tint(.white.opacity(0.7))
.scaleEffect(0.8)
}
}
.padding(.horizontal, 16)
.padding(.vertical, 14)
.background(.white.opacity(0.15), in: .rect(cornerRadius: 12))
.overlay(RoundedRectangle(cornerRadius: 12).stroke(.white.opacity(0.25), lineWidth: 1))
}
private var list: some View {
VStack(spacing: 0) {
ForEach(Array(suggestions.enumerated()), id: \.element.id) { i, actor in
Button { pick(actor) } label: {
HStack(spacing: 10) {
SuggestionAvatar(actor: actor)
VStack(alignment: .leading, spacing: 1) {
if let name = actor.displayName {
Text(name)
.font(.subheadline.weight(.medium))
.foregroundStyle(.white)
.lineLimit(1)
}
Text("@\(actor.handle)")
.font(.caption)
.foregroundStyle(.white.opacity(0.6))
.lineLimit(1)
}
Spacer(minLength: 0)
}
.padding(.horizontal, 16)
.padding(.vertical, 8)
.background {
if highlighted == i {
RoundedRectangle(cornerRadius: 12)
.fill(shell.config.color(.primary).opacity(0.45))
.padding(.horizontal, 6)
.padding(.vertical, 2)
.matchedGeometryEffect(id: "highlight", in: highlight)
}
}
.contentShape(.rect)
}
.buttonStyle(.plain)
.id(actor.id)
.accessibilityLabel(actor.displayName.map { "\($0), @\(actor.handle)" } ?? "@\(actor.handle)")
if i < suggestions.count - 1 {
Divider()
.background(.white.opacity(0.15))
.padding(.leading, 58)
}
}
}
.padding(.vertical, 4)
.background(.white.opacity(0.1), in: .rect(cornerRadius: 12))
.overlay(RoundedRectangle(cornerRadius: 12).stroke(.white.opacity(0.2), lineWidth: 1))
.id("suggestions")
}
private var signInButton: some View {
Button(action: go) {
Group {
if shell.signingIn {
ProgressView().tint(.black)
} else {
Text("Sign in").font(.body.weight(.semibold))
}
}
.frame(maxWidth: .infinity)
.padding(.vertical, 14)
.contentShape(.rect)
}
.buttonStyle(.plain)
.background(.white, in: .rect(cornerRadius: 12))
.foregroundStyle(.black)
.disabled(!ready)
.opacity(name.isEmpty ? 0.4 : 1)
}
private func creating(_ create: SignInPlan.Create) -> some View {
VStack(spacing: 8) {
if let text = create.text {
Text(text)
.font(.footnote)
.foregroundStyle(.white.opacity(0.6))
}
Button(action: createAccount) {
Text(create.label)
.font(.body.weight(.semibold))
.frame(maxWidth: .infinity)
.padding(.vertical, 14)
.contentShape(.rect)
}
.buttonStyle(.plain)
.background(.white.opacity(0.15), in: .rect(cornerRadius: 12))
.overlay(RoundedRectangle(cornerRadius: 12).stroke(.white.opacity(0.25), lineWidth: 1))
.foregroundStyle(.white)
.disabled(shell.signingIn)
}
}
/// Asks the typeahead for what is typed, 200 ms after typing stops; a
/// lookup overtaken by more typing is let go.
private func lookUp() {
search?.cancel()
guard let typeahead = plan.typeahead, handle != picked, typeahead.request(for: handle) != nil else {
searching = false
suggestions = []
return
}
searching = true
let typed = handle
search = Task {
try? await Task.sleep(for: .milliseconds(200))
guard !Task.isCancelled else { return }
let found = await typeahead.search(typed)
guard !Task.isCancelled else { return }
suggestions = found
searching = false
}
}
/// Moves the highlight through the suggestions, as LoginView's
/// `moveSuggestionHighlight`: `wrap` (tab) goes from the last back to
/// the first; up from the first lets it go, back to the field.
private func move(by delta: Int, wrap: Bool = false) -> KeyPress.Result {
guard !suggestions.isEmpty else { return .ignored }
let last = suggestions.count - 1
withAnimation(.spring(response: 0.3, dampingFraction: 0.82)) {
if let at = highlighted {
let next = at + delta
highlighted = next < 0 ? nil : next > last ? (wrap ? 0 : last) : next
} else {
highlighted = delta >= 0 ? 0 : last
}
}
return .handled
}
/// Return: the highlighted suggestion, else what is typed.
private func submit() {
if let at = highlighted, suggestions.indices.contains(at) {
pick(suggestions[at])
} else {
go()
}
}
/// Fills it in and signs in at once, as the button would.
private func pick(_ actor: FoundActor) {
picked = actor.handle
handle = actor.handle
go()
}
private func go() {
guard ready else { return }
typing = false
search?.cancel()
searching = false
suggestions = []
let name = name
Task { await shell.signIn(name, using: web) }
}
private func createAccount() {
guard !shell.signingIn else { return }
typing = false
Task { await shell.signIn(create: true, using: web) }
}
}
/// A suggestion's face, 32 points: its avatar, else its fallback where
/// that fails to load, else a placeholder.
private struct SuggestionAvatar: View {
let actor: FoundActor
var body: some View {
AsyncImage(url: actor.avatar ?? actor.avatarFallback) { phase in
if let image = phase.image {
image.resizable().scaledToFill()
} else if case .failure = phase, actor.avatar != nil, let fallback = actor.avatarFallback {
AsyncImage(url: fallback) { phase in
if let image = phase.image { image.resizable().scaledToFill() } else { placeholder }
}
} else {
placeholder
}
}
.frame(width: 32, height: 32)
.clipShape(.circle)
.accessibilityHidden(true)
}
private var placeholder: some View {
Image(systemName: "person.crop.circle.fill")
.resizable()
.foregroundStyle(.white.opacity(0.4))
}
}
ios/GrainUITests/SignInTests.swiftnew+105−0
@@ -0,0 +1,105 @@
import XCTest
/// The sign-in sheet (next/grain.social.json's `signIn`), opened signed out
/// from Notifications' Sign in. `testSignInSuggestsAccounts`: its heading
/// and the handle field, saved as `sign-in`; then a handle typed
/// (GRAIN_HANDLE, else "chadtm"), the typeahead's accounts suggested under
/// it, saved as `sign-in-suggest`; it never signs in. With GRAIN_TEST_HANDLE
/// and GRAIN_TEST_PASSWORD (an account on a test PDS, as HUD's harness's
/// alice.test), `testSignInAsTestAccount`: a handle that is no account
/// first, refused on the sheet (`sign-in-refused`); then the test account,
/// through the system's browser sheet and its PDS's page, signed in
/// (`sign-in-done`). Never give it a real account.
final class SignInTests: XCTestCase {
private var app: XCUIApplication!
private let env = ProcessInfo.processInfo.environment
override func setUp() {
continueAfterFailure = false
app = XCUIApplication()
app.launchArguments = ["-server", env["GRAIN_SERVER"] ?? "https://next.grain.social"]
app.launch()
}
/// The sheet, opened from Notifications' Sign in: its handle field.
private func openSignIn() -> XCUIElement {
let bar = app.tabBars.firstMatch
XCTAssertTrue(bar.waitForExistence(timeout: 10))
bar.buttons["Notifications"].tap()
let signIn = app.buttons["Sign in"].firstMatch
XCTAssertTrue(signIn.waitForExistence(timeout: 10), "Signed in already: no Sign in on Notifications")
signIn.tap()
let field = app.textFields["Your handle"]
XCTAssertTrue(field.waitForExistence(timeout: 10), "No handle field")
return field
}
func testSignInSuggestsAccounts() throws {
let field = openSignIn()
XCTAssertTrue(app.staticTexts["Log in with your atmosphere account"].exists, "No heading")
sleep(1)
shot("sign-in")
let typed = env["GRAIN_HANDLE"] ?? "chadtm"
field.tap()
field.typeText(typed)
let suggested = app.buttons.matching(NSPredicate(format: "label CONTAINS %@", "@\(typed)")).firstMatch
XCTAssertTrue(suggested.waitForExistence(timeout: 15), "No account suggested for \(typed)")
// Its avatar loaded.
sleep(3)
shot("sign-in-suggest")
}
func testSignInAsTestAccount() throws {
guard let handle = env["GRAIN_TEST_HANDLE"], let password = env["GRAIN_TEST_PASSWORD"] else {
throw XCTSkip("GRAIN_TEST_HANDLE and GRAIN_TEST_PASSWORD name no test account")
}
let field = openSignIn()
let springboard = XCUIApplication(bundleIdentifier: "com.apple.springboard")
// A handle that is no account: the server sends it back, and the sheet says why.
field.tap()
field.typeText("nobody.test\n")
if springboard.buttons["Continue"].waitForExistence(timeout: 10) { springboard.buttons["Continue"].tap() }
let refused = app.staticTexts.matching(NSPredicate(format: "label CONTAINS %@", "does not resolve")).firstMatch
XCTAssertTrue(refused.waitForExistence(timeout: 20), "No refusal on the sheet")
shot("sign-in-refused")
// The test account, signed in at its PDS.
field.tap()
field.clearAndType(handle + "\n")
if springboard.buttons["Continue"].waitForExistence(timeout: 10) { springboard.buttons["Continue"].tap() }
let web = XCUIApplication(bundleIdentifier: "com.apple.SafariViewService")
let secret = web.secureTextFields.firstMatch
XCTAssertTrue(secret.waitForExistence(timeout: 20), "No password field at the PDS")
shot("sign-in-pds")
secret.tap()
secret.typeText(password + "\n")
sleep(4)
for label in ["Accept", "Authorize", "Allow"] where web.buttons[label].exists {
web.buttons[label].tap()
}
XCTAssertTrue(field.waitForNonExistence(timeout: 30), "The sheet stayed")
sleep(3)
shot("sign-in-done")
}
private func shot(_ name: String) {
let png = XCUIScreen.main.screenshot().pngRepresentation
let attachment = XCTAttachment(data: png, uniformTypeIdentifier: "public.png")
attachment.name = name
attachment.lifetime = .keepAlways
add(attachment)
guard let dir = env["GRAIN_SHOTS"] else { return }
try? FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true)
try? png.write(to: URL(fileURLWithPath: dir).appendingPathComponent("\(name).png"))
}
}
private extension XCUIElement {
/// What it holds deleted, then `text` typed.
func clearAndType(_ text: String) {
let held = (value as? String) ?? ""
typeText(String(repeating: XCUIKeyboardKey.delete.rawValue, count: held.count) + text)
}
}
ios/README.md+4−4
@@ -12,11 +12,11 @@ guest; Sign in goes through the server's OAuth.
- `Grain/Shell.swift`: the server, the account, each tab's levels, signing in and out, push, and opening a route's path. A level opened again draws its tree as last drawn at once (HUDKit's `LastTree`: the account's own, at most 10 minutes old) while its call is read afresh; signing in or out lets them all go, and a write the account's.
- `Grain/LevelScreen.swift`: one level, its view drawn by HUDKit's TreeView, and how a view's context is wired. Each time a level shows (opened, gone back to, its tab chosen again) it is read afresh, a thin line moving under the bar meanwhile, the answer drawn in place where it was scrolled, with the pages loaded past the first kept after it.
- `Grain/StoryPager.swift`: people's stories over the tabs, from the stories strip (a `pages` list), swiped between as grain-ios does.
- `Grain/Config.swift`: `grain.social.json` read, its palettes as HUDKit themes.
- `Grain/SignInSheet.swift`: signing in by handle.
- `Grain/Config.swift`: `grain.social.json` read, its palettes as HUDKit themes, its `signIn` as HUDKit's `SignInPlan`.
- `Grain/SignInSheet.swift`: signing in, as grain-ios's LoginView, from `grain.social.json`'s `signIn`: over Grain's photo, the wordmark, the heading and its line, the handle field with the accounts the typeahead (typeahead.waow.tech) finds as it is typed (arrows and tab move through them, return or a tap picks one and signs in), Sign in, Create one (a new account, `prompt=create`), the legal line, its links in Safari; errors in red.
- `Grain/Fonts/`: Syne and Plus Jakarta Sans, Google Fonts' variable TTFs (OFL), registered in `UIAppFonts`; titles are Syne at weight 800.
- `Grain/Assets.xcassets`: Grain's own AppIcon, copied from grain-ios; the home screen names it Grain (`CFBundleDisplayName`).
- `GrainUITests/`: walks the app and pages through stories, saving its screens; `LocationsTests.swift` opens Locations (Explore → Places, See all), taps into the map's gathered pins until a place's own shows and opens it, its timings in `GRAIN_SHOTS/locations.txt`; `LastTreeTests.swift` opens a gallery from Home, goes back, opens it again and leaves the tab and comes back, checking each screen is there at once and read afresh, what it saw when in `GRAIN_SHOTS/last-tree.txt`.
- `Grain/Assets.xcassets`: Grain's own AppIcon and sign-in photo (`login-bg`), copied from grain-ios; the home screen names it Grain (`CFBundleDisplayName`).
- `GrainUITests/`: walks the app and pages through stories, saving its screens; `LocationsTests.swift` opens Locations (Explore → Places, See all), taps into the map's gathered pins until a place's own shows and opens it, its timings in `GRAIN_SHOTS/locations.txt`; `LastTreeTests.swift` opens a gallery from Home, goes back, opens it again and leaves the tab and comes back, checking each screen is there at once and read afresh, what it saw when in `GRAIN_SHOTS/last-tree.txt`; `SignInTests.swift`, signed out, opens Sign in from Notifications and types a handle, saving the sheet empty (`sign-in`) and with the accounts suggested (`sign-in-suggest`); with GRAIN_TEST_HANDLE and GRAIN_TEST_PASSWORD (a test PDS's account, never a real one) it is refused for a handle that is no account, then signs in.
- `ci_scripts/ci_post_clone.sh`: Xcode Cloud's hook, generating the project as `just ios` does.
## Generate, build, launch
next/src/lib/app.ts+5−5
@@ -1,10 +1,10 @@
// Grain as @hud/shell draws it: its app file (next/grain.social.json, the
// same HUD checks as it loads it through HUD_APPS: its tabs, routes, look,
// head and frame), and where this server takes the pages' calls and
// sessions (`HOST`): /api/mcp and /api/upload carry them to HUD as the
// account in use, /auth/signin starts signing in (signed in, adding
// another account), /auth/signout ends the account in use's session, and
// /auth/use switches to another of the browser's accounts.
// head, frame and sign-in screen), and where this server takes the pages'
// calls and sessions (`HOST`): /api/mcp and /api/upload carry them to HUD
// as the account in use, /auth/signin is Grain's own sign-in screen (signed
// in, adding another account), /auth/signout ends the account in use's
// session, and /auth/use switches to another of the browser's accounts.
import type { App, Host } from '@hud/shell';
import file from '../../grain.social.json';
next/src/lib/AppPage.sveltenew+60−0
@@ -0,0 +1,60 @@
<script lang="ts">
import { Shell, type Answer, type Navigation, type Screen } from '@hud/shell';
import type { AccountsData } from '@hud/shell/server';
import { afterNavigate, beforeNavigate, goto } from '$app/navigation';
import { page, updated } from '$app/state';
import { APP, HOST } from '#lib/app.ts';
/**
* Grain as @hud/shell draws it, for any page: the screen the server read
* for its URL (a route's, or the sign-in screen), and what the layout
* read for every page.
*/
let {
screen,
under = null,
data
}: {
screen: Screen;
under?: Promise<Answer> | null;
data: { signedIn: boolean; origin: string; now: number; counts: Promise<Record<number, number>> | null; picture: string | null; accounts: AccountsData | null };
} = $props();
// The shell's history is SvelteKit's shallow routing: each entry's state
// is `page.state.here`, made with `goto(…, { shallow })`, and the page the
// server drew is entered once SvelteKit's router has it.
const navigation: Navigation = {
get here() {
return page.state.here;
},
go: (url, here, replace) => goto(url, { state: { here }, shallow: true, replace, persistState: true }),
entered: (run) =>
afterNavigate(({ type }) => {
if (type === 'enter') run();
})
};
// After a deploy (SvelteKit's version check, vite.config.ts), the next
// move loads its page anew, from the new build, rather than drawing it
// with this one.
beforeNavigate(({ to, willUnload, cancel }) => {
if (!updated.current || willUnload || !to?.url) return;
cancel();
location.href = to.url.href;
});
</script>
<Shell
app={APP}
host={HOST}
{navigation}
{screen}
{under}
signedIn={data.signedIn}
origin={data.origin}
path={page.url.pathname + page.url.search}
now={data.now}
counts={data.counts}
picture={data.picture}
accounts={data.accounts}
/>
next/src/routes/[...path]/+page.svelte+2−41
@@ -1,46 +1,7 @@
<script lang="ts">
import { Shell, type Navigation } from '@hud/shell';
import { afterNavigate, beforeNavigate, goto } from '$app/navigation';
import { page, updated } from '$app/state';
import { APP, HOST } from '#lib/app.ts';
import AppPage from '#lib/AppPage.svelte';
let { data } = $props();
// The shell's history is SvelteKit's shallow routing: each entry's state
// is `page.state.here`, made with `goto(…, { shallow })`, and the page the
// server drew is entered once SvelteKit's router has it.
const navigation: Navigation = {
get here() {
return page.state.here;
},
go: (url, here, replace) => goto(url, { state: { here }, shallow: true, replace, persistState: true }),
entered: (run) =>
afterNavigate(({ type }) => {
if (type === 'enter') run();
})
};
// After a deploy (SvelteKit's version check, vite.config.ts), the next
// move loads its page anew, from the new build, rather than drawing it
// with this one.
beforeNavigate(({ to, willUnload, cancel }) => {
if (!updated.current || willUnload || !to?.url) return;
cancel();
location.href = to.url.href;
});
</script>
<Shell
app={APP}
host={HOST}
{navigation}
screen={data.screen}
under={data.under}
signedIn={data.signedIn}
origin={data.origin}
path={page.url.pathname + page.url.search}
now={data.now}
counts={data.counts}
picture={data.picture}
accounts={data.accounts}
/>
<AppPage screen={data.screen} under={data.under} {data} />
next/src/routes/auth/signin/+page.server.tsnew+14−0
@@ -0,0 +1,14 @@
import { fail, redirect } from '@sveltejs/kit';
import { signInScreen } from '@hud/shell/server';
/** Grain's own sign-in screen (grain.social.json's `signIn`), drawn in the frame; signed in already, it adds another account (@hud/shell's `signInScreen`). */
export const load = ({ url }) => ({ screen: signInScreen(url) });
export const actions = {
/** Its form: on to the account's server, its handle the login hint, or a new account at HUD's sign-up PDS; else the screen again, saying why (@hud/shell's `Hud.signIn`). */
default: async ({ request, url, locals }) => {
const went = await locals.hud.signIn(request, url);
if ('to' in went) redirect(303, went.to, { external: true });
return fail(400, went);
}
};
next/src/routes/auth/signin/+page.sveltenew+10−0
next/src/routes/auth/signin/+server.tsdeleted+0−2
next/check-apps.mjs+22−0
next/grain.social.json+19−0
vendor/hud/ios/HUDKit/Sources/HUDKit/Data/SignIn.swift+0−47
vendor/hud/ios/HUDKit/Sources/HUDKit/Data/SignInPlan.swiftnew+215−0
vendor/hud/ios/HUDKit/Tests/HUDKitTests/SignInPlanTests.swiftnew+125−0
vendor/hud/web/shell/src/app.ts+8−2
vendor/hud/web/shell/src/back.test.ts+23−1
vendor/hud/web/shell/src/back.ts+20−1
vendor/hud/web/shell/src/index.ts+2−2
vendor/hud/web/shell/src/oauth.ts+31−8
vendor/hud/web/shell/src/screen.ts+5−0
vendor/hud/web/shell/src/server.ts+14−0
vendor/hud/web/shell/src/session.ts+37−7
vendor/hud/web/shell/src/Shell.svelte+16−5
vendor/hud/web/shell/src/SignIn.sveltenew+393−0
vendor/hud/web/shell/src/typeahead.test.tsnew+87−0
vendor/hud/web/shell/src/typeahead.tsnew+81−0
vendor/hud/COMMIT+1−1