@hamur/adapter-angular 0.0.0-stage → 0.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +22 -0
- package/README.md +42 -2
- package/dist/chunks/browser-index-7h7x2xz2.js +131 -0
- package/dist/chunks/browser-index-nann848q.js +205 -0
- package/dist/chunks/browser-index-qn8q5fa2.js +580 -0
- package/dist/src/adapter.js +1075 -0
- package/dist/src/error-page.js +34 -0
- package/dist/src/index.js +1729 -0
- package/dist/src/keepalive.js +0 -0
- package/dist/src/runtime/client.js +21 -0
- package/dist/src/runtime/island.js +92 -0
- package/dist/src/runtime/server.js +175 -0
- package/dist/types/src/activation.d.ts +20 -0
- package/dist/types/src/adapter.d.ts +7 -0
- package/dist/types/src/app.d.ts +6 -0
- package/dist/types/src/async-data.d.ts +21 -0
- package/dist/types/src/client-parts.d.ts +35 -0
- package/dist/types/src/compile.d.ts +99 -0
- package/dist/types/src/context.d.ts +74 -0
- package/dist/types/src/data.d.ts +65 -0
- package/dist/types/src/definition.d.ts +13 -0
- package/dist/types/src/error-page.d.ts +8 -0
- package/dist/types/src/error.d.ts +4 -0
- package/dist/types/src/form.d.ts +68 -0
- package/dist/types/src/head.d.ts +12 -0
- package/dist/types/src/hmr.d.ts +14 -0
- package/dist/types/src/hydration.d.ts +16 -0
- package/dist/types/src/index.d.ts +24 -0
- package/dist/types/src/indicators.d.ts +76 -0
- package/dist/types/src/island.d.ts +42 -0
- package/dist/types/src/keepalive.d.ts +1 -0
- package/dist/types/src/link.d.ts +68 -0
- package/dist/types/src/markdown-page.d.ts +10 -0
- package/dist/types/src/markdown.d.ts +40 -0
- package/dist/types/src/mask.d.ts +12 -0
- package/dist/types/src/navigate.d.ts +17 -0
- package/dist/types/src/outlet.d.ts +76 -0
- package/dist/types/src/request.d.ts +31 -0
- package/dist/types/src/routing.d.ts +47 -0
- package/dist/types/src/runtime/client.d.ts +29 -0
- package/dist/types/src/runtime/hydration-dev.d.ts +1 -0
- package/dist/types/src/runtime/hydration.d.ts +8 -0
- package/dist/types/src/runtime/island.d.ts +8 -0
- package/dist/types/src/runtime/server.d.ts +15 -0
- package/dist/types/src/server-island.d.ts +24 -0
- package/dist/types/src/state.d.ts +14 -0
- package/dist/types/src/svg.d.ts +15 -0
- package/dist/types/src/time.d.ts +40 -0
- package/dist/types/src/wrapper.d.ts +21 -0
- package/package.json +77 -4
- package/src/activation.ts +83 -0
- package/src/adapter.ts +107 -0
- package/src/app.ts +12 -0
- package/src/async-data.ts +105 -0
- package/src/client-parts.ts +107 -0
- package/src/compile.ts +963 -0
- package/src/context.ts +189 -0
- package/src/data.ts +389 -0
- package/src/definition.ts +144 -0
- package/src/error-page.ts +30 -0
- package/src/error.ts +15 -0
- package/src/form.ts +182 -0
- package/src/head.ts +63 -0
- package/src/hmr.ts +61 -0
- package/src/hydration.ts +120 -0
- package/src/index.ts +98 -0
- package/src/indicators.ts +220 -0
- package/src/island.ts +89 -0
- package/src/keepalive.ts +1 -0
- package/src/link.ts +214 -0
- package/src/markdown-page.ts +31 -0
- package/src/markdown.ts +140 -0
- package/src/mask.ts +36 -0
- package/src/navigate.ts +22 -0
- package/src/outlet.ts +316 -0
- package/src/request.ts +170 -0
- package/src/routing.ts +218 -0
- package/src/runtime/client.ts +140 -0
- package/src/runtime/contract.d.ts +4 -0
- package/src/runtime/hydration-dev.ts +18 -0
- package/src/runtime/hydration.ts +7 -0
- package/src/runtime/island.ts +109 -0
- package/src/runtime/server.ts +228 -0
- package/src/server-island.ts +67 -0
- package/src/state.ts +70 -0
- package/src/svg.ts +65 -0
- package/src/time.ts +115 -0
- package/src/wrapper.ts +187 -0
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
import { APP_ID, CSP_NONCE, ErrorHandler, REQUEST, type Provider } from "@angular/core"
|
|
2
|
+
import {
|
|
3
|
+
bootstrapApplication,
|
|
4
|
+
provideClientHydration,
|
|
5
|
+
withEventReplay,
|
|
6
|
+
withNoHttpTransferCache,
|
|
7
|
+
} from "@angular/platform-browser"
|
|
8
|
+
import { provideServerRendering, renderApplication } from "@angular/platform-server"
|
|
9
|
+
import CONTRACT from "@angular/core/event-dispatch-contract.min.js" with { type: "text" }
|
|
10
|
+
import { cspHash, publicError, setAdapterInstance } from "hamur/adapter"
|
|
11
|
+
import type { ComponentRenderContext, RenderContext, RenderResult, RenderTree } from "hamur/adapter"
|
|
12
|
+
import { isRedirect } from "hamur/app"
|
|
13
|
+
import type { AppContext, HamurError } from "hamur/app"
|
|
14
|
+
import { HamurApp } from "../app.ts"
|
|
15
|
+
import { createState, hamurProviders, islandHref, setupOf } from "../context.ts"
|
|
16
|
+
import { boundaryKey, maskInPlace, shownError } from "../mask.ts"
|
|
17
|
+
|
|
18
|
+
const APP = "hamur"
|
|
19
|
+
const CONTRACT_ID = "ng-event-dispatch-contract"
|
|
20
|
+
const MARKER = "<!--nghm-->"
|
|
21
|
+
const SCRIPT = /<script\b([^>]*)>([\s\S]*?)<\/script>/g
|
|
22
|
+
const STYLE = /<style\b[^>]*>[\s\S]*?<\/style>/g
|
|
23
|
+
|
|
24
|
+
const nonceAttribute = (nonce: string | undefined) =>
|
|
25
|
+
nonce ? ` nonce="${nonce.replace(/&/g, "&").replace(/"/g, """)}"` : ""
|
|
26
|
+
|
|
27
|
+
/** The event-dispatch contract goes in `<body>`, where the replay script after it finds `document.body`. */
|
|
28
|
+
const shell = (nonce: string | undefined) =>
|
|
29
|
+
`<!doctype html><html><head></head><body><script id="${CONTRACT_ID}"${nonceAttribute(nonce)}>${CONTRACT}</script><hamur-app></hamur-app></body></html>`
|
|
30
|
+
|
|
31
|
+
/** A thrown value that is not an `Error` may reach Angular's handler as the `cause` of one, so a redirect is read back from it. */
|
|
32
|
+
function redirectOf(error: unknown): unknown {
|
|
33
|
+
if (isRedirect(error)) return error
|
|
34
|
+
const cause = error instanceof Error ? error.cause : undefined
|
|
35
|
+
return isRedirect(cause) ? cause : undefined
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const isFatal = (error: unknown): boolean =>
|
|
39
|
+
typeof error === "object" && error !== null && (error as { fatal?: unknown }).fatal === true
|
|
40
|
+
|
|
41
|
+
/** Angular logs what it reports and goes on; the first throw is the render's failure. */
|
|
42
|
+
class RenderErrors extends ErrorHandler {
|
|
43
|
+
failed: { error: unknown } | undefined
|
|
44
|
+
private readonly reported = new WeakSet<object>()
|
|
45
|
+
private caught = 0
|
|
46
|
+
|
|
47
|
+
constructor(private readonly app: AppContext) {
|
|
48
|
+
super()
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
readonly fail = (error: unknown): void => {
|
|
52
|
+
this.failed ??= { error }
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
override handleError(error: unknown): void {
|
|
56
|
+
this.fail(error)
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* An `@boundary` caught it and renders its `@error` block, as an `ErrorBoundary` does on the other servers: the answer stays as it is
|
|
61
|
+
* and the error is reported once to `app:error`, masked. A redirect and a `fatal` error are not caught: they fail the render.
|
|
62
|
+
*/
|
|
63
|
+
override onViewError(error: Error): void {
|
|
64
|
+
const thrown = redirectOf(error) ?? (isFatal(error) || isFatal(error.cause) ? error : undefined)
|
|
65
|
+
if (thrown) return this.fail(thrown === error ? error : thrown)
|
|
66
|
+
if (this.reported.has(error)) return
|
|
67
|
+
this.reported.add(error)
|
|
68
|
+
const masked = publicError(this.app, error) as HamurError
|
|
69
|
+
if (masked !== error) {
|
|
70
|
+
try {
|
|
71
|
+
maskInPlace(error, masked)
|
|
72
|
+
} catch {
|
|
73
|
+
return this.fail(masked)
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
this.app.state.set(boundaryKey(this.caught++), shownError(error))
|
|
77
|
+
void this.app.hooks?.callHook("app:error", masked, { source: "render" }).catch(() => {})
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
interface Parts {
|
|
82
|
+
head: string
|
|
83
|
+
body: string
|
|
84
|
+
marker: boolean
|
|
85
|
+
/** The text of each executed inline `<script>` of the body. */
|
|
86
|
+
scripts: string[]
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Angular's `<style>` elements of its head, and its body without the `<!--nghm-->` marker. */
|
|
90
|
+
function partsOf(document: string, appId: string, nonce: string | undefined): Parts {
|
|
91
|
+
const head = (/<head>([\s\S]*?)<\/head>/.exec(document)?.[1] ?? "").match(STYLE) ?? []
|
|
92
|
+
let body = /<body[^>]*>([\s\S]*)<\/body>/.exec(document)?.[1] ?? ""
|
|
93
|
+
const marker = body.includes(MARKER)
|
|
94
|
+
body = body.replace(MARKER, "")
|
|
95
|
+
if (nonce) body = body.replace(`<script id="${appId}-state"`, `<script id="${appId}-state"${nonceAttribute(nonce)}`)
|
|
96
|
+
const scripts = [...body.matchAll(SCRIPT)]
|
|
97
|
+
.filter(([, attributes]) => !/\btype="application\/json"/.test(attributes!))
|
|
98
|
+
.map(([, , text]) => text!)
|
|
99
|
+
return { head: head.join(""), body, marker, scripts }
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** Angular renders `@defer (hydrate …)` content only with hydration on, so a script-free page is rendered with it and stripped of what only a client reads. */
|
|
103
|
+
export function withoutHydration(document: string): string {
|
|
104
|
+
return document
|
|
105
|
+
.replace(/<!--ngh[\s\S]*?-->/g, "")
|
|
106
|
+
.replace(/ ngh="[^"]*"/g, "")
|
|
107
|
+
.replace(new RegExp(`<script id="(?:${CONTRACT_ID}|${APP}-state)"[^>]*>[\\s\\S]*?</script>`, "g"), "")
|
|
108
|
+
.replace(/<script\b[^>]*>window\.__jsaction_bootstrap\([\s\S]*?<\/script>/g, "")
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
async function renderTree(
|
|
112
|
+
app: AppContext,
|
|
113
|
+
options: {
|
|
114
|
+
url: URL
|
|
115
|
+
tree: RenderTree
|
|
116
|
+
route: RenderContext["route"]
|
|
117
|
+
payload: RenderContext["payload"]
|
|
118
|
+
baseURL: string
|
|
119
|
+
href: RenderContext["href"]
|
|
120
|
+
},
|
|
121
|
+
appId: string,
|
|
122
|
+
nonce: string | undefined,
|
|
123
|
+
scriptFree = false,
|
|
124
|
+
): Promise<Parts> {
|
|
125
|
+
const { setup, bootstrapped } = setupOf(app)
|
|
126
|
+
await setAdapterInstance(app, setup)
|
|
127
|
+
const errors = new RenderErrors(app)
|
|
128
|
+
const state = createState({ app, ...options })
|
|
129
|
+
const providers: Provider[] = [
|
|
130
|
+
{ provide: APP_ID, useValue: appId },
|
|
131
|
+
{ provide: CSP_NONCE, useValue: nonce ?? null },
|
|
132
|
+
{ provide: REQUEST, useValue: app.event?.request ?? null },
|
|
133
|
+
{ provide: ErrorHandler, useValue: errors },
|
|
134
|
+
...hamurProviders(app, state, errors.fail),
|
|
135
|
+
]
|
|
136
|
+
let document = ""
|
|
137
|
+
try {
|
|
138
|
+
document = await renderApplication(
|
|
139
|
+
async (context) => {
|
|
140
|
+
const appRef = await bootstrapApplication(
|
|
141
|
+
HamurApp,
|
|
142
|
+
{
|
|
143
|
+
providers: [
|
|
144
|
+
provideServerRendering(),
|
|
145
|
+
provideClientHydration(withEventReplay(), withNoHttpTransferCache()),
|
|
146
|
+
...providers,
|
|
147
|
+
...setup.providers,
|
|
148
|
+
],
|
|
149
|
+
},
|
|
150
|
+
context,
|
|
151
|
+
)
|
|
152
|
+
bootstrapped(appRef.injector)
|
|
153
|
+
return appRef
|
|
154
|
+
},
|
|
155
|
+
{ document: shell(nonce), url: options.url.href, allowedHosts: [options.url.hostname] },
|
|
156
|
+
)
|
|
157
|
+
} catch (error) {
|
|
158
|
+
errors.fail(error)
|
|
159
|
+
}
|
|
160
|
+
if (errors.failed) throw redirectOf(errors.failed.error) ?? errors.failed.error
|
|
161
|
+
return partsOf(scriptFree ? withoutHydration(document) : document, appId, nonce)
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** A throw no boundary caught fails the render, so the handler answers the error page with its status. */
|
|
165
|
+
export async function render(ctx: RenderContext): Promise<RenderResult> {
|
|
166
|
+
const parts = await renderTree(ctx.app, ctx, APP, ctx.nonce, ctx.route.meta.scripts === false)
|
|
167
|
+
if (ctx.scriptHashes) for (const script of parts.scripts) ctx.scriptHashes.push(await cspHash(script))
|
|
168
|
+
return {
|
|
169
|
+
body: parts.body,
|
|
170
|
+
...(parts.head ? { head: parts.head } : {}),
|
|
171
|
+
...(parts.marker ? { teleports: { body: MARKER } } : {}),
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
const ISLAND_ENTRY = "island"
|
|
176
|
+
const REPLAY_SCRIPT =
|
|
177
|
+
/<script\b[^>]*>window\.__jsaction_bootstrap\(document\.currentScript\.parentElement,[\s\S]*?<\/script>/
|
|
178
|
+
const CONTRACT_SCRIPT = new RegExp(`<script id="${CONTRACT_ID}"[^>]*>([\\s\\S]*?)</script>`)
|
|
179
|
+
/** The pages whose head already holds the contract an island returned. */
|
|
180
|
+
const contractInHead = new WeakSet<object>()
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* `Island` (A8): `component` as an application of its own with `ctx.idPrefix` as its `APP_ID`. Its replay script
|
|
184
|
+
* is scoped to the island's element. The event-dispatch contract goes to the page's head once, with the first island that keeps it,
|
|
185
|
+
* so it runs before every island's replay script whatever order the islands render in.
|
|
186
|
+
*/
|
|
187
|
+
export async function renderComponent(
|
|
188
|
+
component: unknown,
|
|
189
|
+
props: Record<string, unknown>,
|
|
190
|
+
ctx: ComponentRenderContext,
|
|
191
|
+
): Promise<{ html: string; head?: string }> {
|
|
192
|
+
const parts = await renderTree(
|
|
193
|
+
ctx.app,
|
|
194
|
+
{
|
|
195
|
+
url: ctx.url,
|
|
196
|
+
route: ctx.route,
|
|
197
|
+
payload: {},
|
|
198
|
+
tree: { components: [{ id: ISLAND_ENTRY, component, props }] },
|
|
199
|
+
baseURL: ctx.baseURL,
|
|
200
|
+
href: islandHref(ctx.baseURL),
|
|
201
|
+
},
|
|
202
|
+
ctx.idPrefix,
|
|
203
|
+
ctx.nonce,
|
|
204
|
+
)
|
|
205
|
+
let head = parts.head
|
|
206
|
+
let html = parts.body.replace(
|
|
207
|
+
/window\.__jsaction_bootstrap\(document\.body,/,
|
|
208
|
+
"window.__jsaction_bootstrap(document.currentScript.parentElement,",
|
|
209
|
+
)
|
|
210
|
+
// Angular writes the replay script before the application; the "visible" directive observes the island's first element child.
|
|
211
|
+
const replay = REPLAY_SCRIPT.exec(html)
|
|
212
|
+
if (replay) html = html.replace(replay[0], "") + replay[0]
|
|
213
|
+
const contract = CONTRACT_SCRIPT.exec(html)
|
|
214
|
+
if (contract) {
|
|
215
|
+
html = html.replace(contract[0], "")
|
|
216
|
+
if (!contractInHead.has(ctx.app)) {
|
|
217
|
+
contractInHead.add(ctx.app)
|
|
218
|
+
head = contract[0] + head
|
|
219
|
+
if (ctx.scriptHashes) ctx.scriptHashes.push(await cspHash(contract[1]!))
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
if (ctx.scriptHashes)
|
|
223
|
+
for (const [, attributes, text] of html.matchAll(SCRIPT))
|
|
224
|
+
if (!/\btype="application\/json"/.test(attributes!)) ctx.scriptHashes.push(await cspHash(text!))
|
|
225
|
+
return head ? { html, head } : { html }
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
export { clientComponentOnServer as clientComponent, serverComponentOnServer as serverComponent } from "../wrapper.ts"
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { Component, PendingTasks, effect, inject, input } from "@angular/core";
|
|
2
|
+
import { renderServerIsland, serverIslandProps } from "hamur/adapter";
|
|
3
|
+
import { injectId } from "./client-parts.ts";
|
|
4
|
+
import { HAMUR_APP, HAMUR_FAIL, onServer } from "./context.ts";
|
|
5
|
+
import { HostWriter } from "./island.ts";
|
|
6
|
+
import * as i0 from "@angular/core";
|
|
7
|
+
/**
|
|
8
|
+
* A component rendered on the server in its own request; the page holds `fallback`, the core swaps the answer in, and Angular
|
|
9
|
+
* never renders or hydrates it. While hydrating, the server's element keeps its attributes and nodes.
|
|
10
|
+
*/
|
|
11
|
+
export class ServerIsland extends HostWriter {
|
|
12
|
+
/** The name of a component under `app/server-islands/`. */
|
|
13
|
+
name = input.required(/* @ts-ignore */
|
|
14
|
+
...(ngDevMode ? [{ debugName: "name" }] : /* istanbul ignore next */ []));
|
|
15
|
+
props = input(/* @ts-ignore */
|
|
16
|
+
...(ngDevMode ? [undefined, { debugName: "props" }] : /* istanbul ignore next */ []));
|
|
17
|
+
/** Rendered with the page; replaced by the island's HTML once the browser has it. */
|
|
18
|
+
fallback = input(/* @ts-ignore */
|
|
19
|
+
...(ngDevMode ? [undefined, { debugName: "fallback" }] : /* istanbul ignore next */ []));
|
|
20
|
+
app = inject(HAMUR_APP, { optional: true });
|
|
21
|
+
id = injectId();
|
|
22
|
+
tasks = inject(PendingTasks);
|
|
23
|
+
fail = inject(HAMUR_FAIL, { optional: true });
|
|
24
|
+
server = onServer();
|
|
25
|
+
kept;
|
|
26
|
+
constructor() {
|
|
27
|
+
super();
|
|
28
|
+
if (!this.app)
|
|
29
|
+
throw new Error("ServerIsland must be rendered inside a Hamur app");
|
|
30
|
+
this.kept = !this.server && this.app.asyncData.hydrating;
|
|
31
|
+
if (this.server || this.kept)
|
|
32
|
+
return;
|
|
33
|
+
effect(() => {
|
|
34
|
+
const name = this.name();
|
|
35
|
+
const props = this.props();
|
|
36
|
+
this.renderer.setAttribute(this.host, "name", name);
|
|
37
|
+
if (props && Object.keys(props).length)
|
|
38
|
+
this.renderer.setAttribute(this.host, "props", serverIslandProps(name, props));
|
|
39
|
+
else
|
|
40
|
+
this.renderer.removeAttribute(this.host, "props");
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
ngOnInit() {
|
|
44
|
+
if (this.kept)
|
|
45
|
+
return;
|
|
46
|
+
const fallback = this.fallback();
|
|
47
|
+
if (fallback)
|
|
48
|
+
this.append(fallback);
|
|
49
|
+
if (!this.server)
|
|
50
|
+
return;
|
|
51
|
+
const { attributes } = renderServerIsland(this.app, this.id, this.name(), this.props());
|
|
52
|
+
const done = this.tasks.add();
|
|
53
|
+
attributes
|
|
54
|
+
.then((written) => {
|
|
55
|
+
for (const [name, value] of Object.entries(written))
|
|
56
|
+
this.renderer.setAttribute(this.host, name, value);
|
|
57
|
+
})
|
|
58
|
+
.catch((error) => this.fail?.(error))
|
|
59
|
+
.finally(done);
|
|
60
|
+
}
|
|
61
|
+
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.3.2", ngImport: i0, type: ServerIsland, deps: [], target: i0.ɵɵFactoryTarget.Component });
|
|
62
|
+
static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.1.0", version: "22.3.2", type: ServerIsland, isStandalone: true, selector: "hamur-server-island", inputs: { name: { classPropertyName: "name", publicName: "name", isSignal: true, isRequired: true, transformFunction: null }, props: { classPropertyName: "props", publicName: "props", isSignal: true, isRequired: false, transformFunction: null }, fallback: { classPropertyName: "fallback", publicName: "fallback", isSignal: true, isRequired: false, transformFunction: null } }, usesInheritance: true, ngImport: i0, template: "", isInline: true });
|
|
63
|
+
}
|
|
64
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.3.2", ngImport: i0, type: ServerIsland, decorators: [{
|
|
65
|
+
type: Component,
|
|
66
|
+
args: [{ selector: "hamur-server-island", template: "" }]
|
|
67
|
+
}], ctorParameters: () => [], propDecorators: { name: [{ type: i0.Input, args: [{ isSignal: true, alias: "name", required: true }] }], props: [{ type: i0.Input, args: [{ isSignal: true, alias: "props", required: false }] }], fallback: [{ type: i0.Input, args: [{ isSignal: true, alias: "fallback", required: false }] }] } });
|
package/src/state.ts
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import {
|
|
2
|
+
DestroyRef,
|
|
3
|
+
afterNextRender,
|
|
4
|
+
assertInInjectionContext,
|
|
5
|
+
computed,
|
|
6
|
+
inject,
|
|
7
|
+
signal,
|
|
8
|
+
untracked,
|
|
9
|
+
type Signal,
|
|
10
|
+
type WritableSignal,
|
|
11
|
+
} from "@angular/core"
|
|
12
|
+
import { stateArguments } from "hamur/adapter"
|
|
13
|
+
import { syncedState, useCookie as cookieOf } from "hamur/app"
|
|
14
|
+
import type { StateKey, SyncedStateOptions, UseCookieOptions } from "hamur/app"
|
|
15
|
+
import { HAMUR_APP, required } from "./context.ts"
|
|
16
|
+
|
|
17
|
+
/** A signal that reads `source` and writes through `write`: the store is the one value, the signal only follows it. */
|
|
18
|
+
export function writableOf<T>(source: Signal<T>, write: (value: T) => void): WritableSignal<T> {
|
|
19
|
+
const read = computed(source)
|
|
20
|
+
return Object.assign(read, {
|
|
21
|
+
set: write,
|
|
22
|
+
update: (change: (value: T) => T) => write(change(untracked(source))),
|
|
23
|
+
asReadonly: () => read,
|
|
24
|
+
}) as unknown as WritableSignal<T>
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** The app's state under `key`, in the payload; `init` runs once per key. */
|
|
28
|
+
export function injectState<T>(key: StateKey<T>): WritableSignal<T>
|
|
29
|
+
export function injectState<T>(key: string, init?: T | (() => T)): WritableSignal<T>
|
|
30
|
+
export function injectState<T>(...args: unknown[]): WritableSignal<T> {
|
|
31
|
+
assertInInjectionContext(injectState)
|
|
32
|
+
const { key, init } = stateArguments(args) as { key: string; init: T | (() => T) | undefined }
|
|
33
|
+
const store = required(HAMUR_APP, "injectState").state
|
|
34
|
+
const value = signal(store.use<T>(key, init) as T)
|
|
35
|
+
inject(DestroyRef).onDestroy(store.subscribe(key, (next) => value.set(next as T)))
|
|
36
|
+
return writableOf(value, (next) => store.set(key, next))
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** A cookie of the request on the server and of `document.cookie` in the browser; a write sets it, `undefined` deletes it. */
|
|
40
|
+
export function injectCookie<T = string>(
|
|
41
|
+
name: string,
|
|
42
|
+
options: Omit<UseCookieOptions<T>, "app"> & { default: () => T },
|
|
43
|
+
): WritableSignal<T>
|
|
44
|
+
export function injectCookie<T = string>(
|
|
45
|
+
name: string,
|
|
46
|
+
options?: Omit<UseCookieOptions<T>, "app">,
|
|
47
|
+
): WritableSignal<T | undefined>
|
|
48
|
+
export function injectCookie<T = string>(
|
|
49
|
+
name: string,
|
|
50
|
+
options: Omit<UseCookieOptions<T>, "app"> = {},
|
|
51
|
+
): WritableSignal<T | undefined> {
|
|
52
|
+
assertInInjectionContext(injectCookie)
|
|
53
|
+
const cookie = cookieOf<T>(name, { ...options, app: required(HAMUR_APP, "injectCookie") })
|
|
54
|
+
const value = signal<T | undefined>(cookie.get())
|
|
55
|
+
inject(DestroyRef).onDestroy(cookie.subscribe((next) => value.set(next)))
|
|
56
|
+
return writableOf(value, (next) => cookie.set(next))
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** The value of `key` in the room, shared through the page's socket; `initial` until the first render is done. */
|
|
60
|
+
export function injectSyncedState<T>(key: string, initial: T, options: SyncedStateOptions = {}): WritableSignal<T> {
|
|
61
|
+
assertInInjectionContext(injectSyncedState)
|
|
62
|
+
const state = syncedState(key, initial, options)
|
|
63
|
+
const value = signal(initial)
|
|
64
|
+
const destroy = inject(DestroyRef)
|
|
65
|
+
afterNextRender(() => {
|
|
66
|
+
value.set(state.get())
|
|
67
|
+
destroy.onDestroy(state.subscribe((next) => value.set(next)))
|
|
68
|
+
})
|
|
69
|
+
return writableOf(value, (next) => state.set(next))
|
|
70
|
+
}
|
package/src/svg.ts
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { svgCode } from "hamur/adapter"
|
|
2
|
+
import type { SvgCode, SvgNode, SvgSource, SvgValue } from "hamur/adapter"
|
|
3
|
+
|
|
4
|
+
const TEXT: Record<string, string> = {
|
|
5
|
+
"&": "&",
|
|
6
|
+
"<": "<",
|
|
7
|
+
">": ">",
|
|
8
|
+
"@": "@",
|
|
9
|
+
"{": '{{ "{" }}',
|
|
10
|
+
"}": '{{ "}" }}',
|
|
11
|
+
}
|
|
12
|
+
const ATTRIBUTE: Record<string, string> = { "&": "&", '"': """, "<": "<", ">": ">" }
|
|
13
|
+
|
|
14
|
+
/** `{`, `}` and `@` start Angular's blocks and interpolation even as a decoded entity, so a brace is the text of a one-character interpolation. */
|
|
15
|
+
const text = (value: string) => value.replace(/[&<>@{}]/g, (char) => TEXT[char]!)
|
|
16
|
+
const escaped = (value: string) => value.replace(/[&"<>]/g, (char) => ATTRIBUTE[char]!)
|
|
17
|
+
|
|
18
|
+
/** The decorator is written through a constant so the compile step does not take this file for a component of the package. */
|
|
19
|
+
const COMPONENT = "@Component"
|
|
20
|
+
|
|
21
|
+
/** A value with no `{ id }` part and no `{` or `}` is a static attribute; the rest is a binding of the expression `svgCode` writes. */
|
|
22
|
+
function attribute(code: SvgCode, name: string, value: SvgValue): string {
|
|
23
|
+
if (typeof value === "string" && !/[{}]/.test(value)) return ` ${name}="${escaped(value)}"`
|
|
24
|
+
return ` [attr.${name}]="${escaped(code.value(value))}"`
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function node(code: SvgCode, child: SvgNode): string {
|
|
28
|
+
if (typeof child === "string") return text(child)
|
|
29
|
+
if (Array.isArray(child)) return `{{ ${escaped(code.value(child))} }}`
|
|
30
|
+
const attrs = Object.entries(code.attrs(child))
|
|
31
|
+
.map(([name, value]) => attribute(code, name, value))
|
|
32
|
+
.join("")
|
|
33
|
+
return `<${child.tag}${attrs}>${child.children.map((inner) => node(code, inner)).join("")}</${child.tag}>`
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* A standalone component with no selector, rendered with `NgComponentOutlet`; its only input is `title`. Each
|
|
38
|
+
* `{ id }` part is `uid + "-<id>"`, `uid` being `injectId()` of the instance, the same on the server and in hydration. Angular
|
|
39
|
+
* compiles the module with the app: the core writes it under `<buildDir>/svg` and the compile step finds it there.
|
|
40
|
+
*/
|
|
41
|
+
function module(svg: SvgSource): { contents: string; extension: string } {
|
|
42
|
+
const code = svgCode(svg, { title: "title()", props: "{}" })
|
|
43
|
+
const root = Object.entries(svg.attrs)
|
|
44
|
+
.map(([name, value]) => attribute(code, name, value))
|
|
45
|
+
.join("")
|
|
46
|
+
const hidden = code.hidden ? ` [attr.aria-hidden]="title() == null ? 'true' : null"` : ""
|
|
47
|
+
const children = svg.children.map((child) => node(code, child)).join("")
|
|
48
|
+
const template = `<svg${root}${hidden}>@if (title() != null) {<title>{{ title() }}</title>}${children}</svg>`
|
|
49
|
+
const contents = `import { Component, NO_ERRORS_SCHEMA, input } from "@angular/core";
|
|
50
|
+
import { injectId } from "@hamur/adapter-angular";
|
|
51
|
+
|
|
52
|
+
${COMPONENT}({
|
|
53
|
+
schemas: [NO_ERRORS_SCHEMA],
|
|
54
|
+
preserveWhitespaces: true,
|
|
55
|
+
template: ${JSON.stringify(template)},
|
|
56
|
+
})
|
|
57
|
+
export default class SvgComponent {
|
|
58
|
+
readonly title = input<string>();
|
|
59
|
+
protected readonly uid = injectId().replace(/[^\\w-]/g, "_");
|
|
60
|
+
}
|
|
61
|
+
`
|
|
62
|
+
return { contents, extension: ".ts" }
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export const svgComponent = { types: `import("@angular/core").Type<{ title?: string }>`, module }
|
package/src/time.ts
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { Directive, afterRenderEffect, booleanAttribute, computed, inject, input, numberAttribute, signal, } from "@angular/core";
|
|
2
|
+
import { timeView, watchTime } from "hamur/adapter";
|
|
3
|
+
import { HAMUR_APP, HAMUR_ROUTE, required } from "./context.ts";
|
|
4
|
+
import * as i0 from "@angular/core";
|
|
5
|
+
const optionalBoolean = (value) => value === undefined ? undefined : booleanAttribute(value);
|
|
6
|
+
const optionalNumber = (value) => value === undefined ? undefined : numberAttribute(value);
|
|
7
|
+
/**
|
|
8
|
+
* `<time [hamurTime]="date">` writes the `datetime`, `data-locale` and `data-time-zone` attributes and the formatted text;
|
|
9
|
+
* `relative` refreshes the text every `relativeInterval` ms in the browser. The other inputs are the `Intl.DateTimeFormat` options.
|
|
10
|
+
*/
|
|
11
|
+
export class Time {
|
|
12
|
+
datetime = input.required({ ...(ngDevMode ? { debugName: "datetime" } : /* istanbul ignore next */ {}), alias: "hamurTime" });
|
|
13
|
+
locale = input(/* @ts-ignore */
|
|
14
|
+
...(ngDevMode ? [undefined, { debugName: "locale" }] : /* istanbul ignore next */ []));
|
|
15
|
+
timeZone = input(/* @ts-ignore */
|
|
16
|
+
...(ngDevMode ? [undefined, { debugName: "timeZone" }] : /* istanbul ignore next */ []));
|
|
17
|
+
relative = input(false, { ...(ngDevMode ? { debugName: "relative" } : /* istanbul ignore next */ {}), transform: booleanAttribute });
|
|
18
|
+
relativeInterval = input(undefined, { ...(ngDevMode ? { debugName: "relativeInterval" } : /* istanbul ignore next */ {}), transform: optionalNumber });
|
|
19
|
+
calendar = input(/* @ts-ignore */
|
|
20
|
+
...(ngDevMode ? [undefined, { debugName: "calendar" }] : /* istanbul ignore next */ []));
|
|
21
|
+
dayPeriod = input(/* @ts-ignore */
|
|
22
|
+
...(ngDevMode ? [undefined, { debugName: "dayPeriod" }] : /* istanbul ignore next */ []));
|
|
23
|
+
numberingSystem = input(/* @ts-ignore */
|
|
24
|
+
...(ngDevMode ? [undefined, { debugName: "numberingSystem" }] : /* istanbul ignore next */ []));
|
|
25
|
+
dateStyle = input(/* @ts-ignore */
|
|
26
|
+
...(ngDevMode ? [undefined, { debugName: "dateStyle" }] : /* istanbul ignore next */ []));
|
|
27
|
+
timeStyle = input(/* @ts-ignore */
|
|
28
|
+
...(ngDevMode ? [undefined, { debugName: "timeStyle" }] : /* istanbul ignore next */ []));
|
|
29
|
+
hourCycle = input(/* @ts-ignore */
|
|
30
|
+
...(ngDevMode ? [undefined, { debugName: "hourCycle" }] : /* istanbul ignore next */ []));
|
|
31
|
+
hour12 = input(undefined, { ...(ngDevMode ? { debugName: "hour12" } : /* istanbul ignore next */ {}), transform: optionalBoolean });
|
|
32
|
+
localeMatcher = input(/* @ts-ignore */
|
|
33
|
+
...(ngDevMode ? [undefined, { debugName: "localeMatcher" }] : /* istanbul ignore next */ []));
|
|
34
|
+
formatMatcher = input(/* @ts-ignore */
|
|
35
|
+
...(ngDevMode ? [undefined, { debugName: "formatMatcher" }] : /* istanbul ignore next */ []));
|
|
36
|
+
weekday = input(/* @ts-ignore */
|
|
37
|
+
...(ngDevMode ? [undefined, { debugName: "weekday" }] : /* istanbul ignore next */ []));
|
|
38
|
+
era = input(/* @ts-ignore */
|
|
39
|
+
...(ngDevMode ? [undefined, { debugName: "era" }] : /* istanbul ignore next */ []));
|
|
40
|
+
year = input(/* @ts-ignore */
|
|
41
|
+
...(ngDevMode ? [undefined, { debugName: "year" }] : /* istanbul ignore next */ []));
|
|
42
|
+
month = input(/* @ts-ignore */
|
|
43
|
+
...(ngDevMode ? [undefined, { debugName: "month" }] : /* istanbul ignore next */ []));
|
|
44
|
+
day = input(/* @ts-ignore */
|
|
45
|
+
...(ngDevMode ? [undefined, { debugName: "day" }] : /* istanbul ignore next */ []));
|
|
46
|
+
hour = input(/* @ts-ignore */
|
|
47
|
+
...(ngDevMode ? [undefined, { debugName: "hour" }] : /* istanbul ignore next */ []));
|
|
48
|
+
minute = input(/* @ts-ignore */
|
|
49
|
+
...(ngDevMode ? [undefined, { debugName: "minute" }] : /* istanbul ignore next */ []));
|
|
50
|
+
second = input(/* @ts-ignore */
|
|
51
|
+
...(ngDevMode ? [undefined, { debugName: "second" }] : /* istanbul ignore next */ []));
|
|
52
|
+
fractionalSecondDigits = input(undefined, { ...(ngDevMode ? { debugName: "fractionalSecondDigits" } : /* istanbul ignore next */ {}), transform: optionalNumber });
|
|
53
|
+
timeZoneName = input(/* @ts-ignore */
|
|
54
|
+
...(ngDevMode ? [undefined, { debugName: "timeZoneName" }] : /* istanbul ignore next */ []));
|
|
55
|
+
app = required(HAMUR_APP, "Time");
|
|
56
|
+
route = inject(HAMUR_ROUTE, { optional: true });
|
|
57
|
+
now = signal(undefined, /* @ts-ignore */
|
|
58
|
+
...(ngDevMode ? [{ debugName: "now" }] : /* istanbul ignore next */ []));
|
|
59
|
+
props = computed(() => {
|
|
60
|
+
const given = {
|
|
61
|
+
datetime: this.datetime(),
|
|
62
|
+
locale: this.locale(),
|
|
63
|
+
timeZone: this.timeZone(),
|
|
64
|
+
relative: this.relative(),
|
|
65
|
+
relativeInterval: this.relativeInterval(),
|
|
66
|
+
calendar: this.calendar(),
|
|
67
|
+
dayPeriod: this.dayPeriod(),
|
|
68
|
+
numberingSystem: this.numberingSystem(),
|
|
69
|
+
dateStyle: this.dateStyle(),
|
|
70
|
+
timeStyle: this.timeStyle(),
|
|
71
|
+
hourCycle: this.hourCycle(),
|
|
72
|
+
hour12: this.hour12(),
|
|
73
|
+
localeMatcher: this.localeMatcher(),
|
|
74
|
+
formatMatcher: this.formatMatcher(),
|
|
75
|
+
weekday: this.weekday(),
|
|
76
|
+
era: this.era(),
|
|
77
|
+
year: this.year(),
|
|
78
|
+
month: this.month(),
|
|
79
|
+
day: this.day(),
|
|
80
|
+
hour: this.hour(),
|
|
81
|
+
minute: this.minute(),
|
|
82
|
+
second: this.second(),
|
|
83
|
+
fractionalSecondDigits: this.fractionalSecondDigits(),
|
|
84
|
+
timeZoneName: this.timeZoneName(),
|
|
85
|
+
};
|
|
86
|
+
return Object.fromEntries(Object.entries(given).filter(([, value]) => value !== undefined));
|
|
87
|
+
}, /* @ts-ignore */
|
|
88
|
+
...(ngDevMode ? [{ debugName: "props" }] : /* istanbul ignore next */ []));
|
|
89
|
+
view = computed(() => timeView(this.app, this.route?.().path ?? "/", this.props(), this.now()), /* @ts-ignore */
|
|
90
|
+
...(ngDevMode ? [{ debugName: "view" }] : /* istanbul ignore next */ []));
|
|
91
|
+
interval = computed(() => this.view().interval, /* @ts-ignore */
|
|
92
|
+
...(ngDevMode ? [{ debugName: "interval" }] : /* istanbul ignore next */ []));
|
|
93
|
+
constructor() {
|
|
94
|
+
afterRenderEffect((onCleanup) => {
|
|
95
|
+
const interval = this.interval();
|
|
96
|
+
if (interval === undefined)
|
|
97
|
+
return;
|
|
98
|
+
onCleanup(watchTime(interval, (next) => this.now.set(next)));
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.3.2", ngImport: i0, type: Time, deps: [], target: i0.ɵɵFactoryTarget.Directive });
|
|
102
|
+
static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "17.1.0", version: "22.3.2", type: Time, isStandalone: true, selector: "time[hamurTime]", inputs: { datetime: { classPropertyName: "datetime", publicName: "hamurTime", isSignal: true, isRequired: true, transformFunction: null }, locale: { classPropertyName: "locale", publicName: "locale", isSignal: true, isRequired: false, transformFunction: null }, timeZone: { classPropertyName: "timeZone", publicName: "timeZone", isSignal: true, isRequired: false, transformFunction: null }, relative: { classPropertyName: "relative", publicName: "relative", isSignal: true, isRequired: false, transformFunction: null }, relativeInterval: { classPropertyName: "relativeInterval", publicName: "relativeInterval", isSignal: true, isRequired: false, transformFunction: null }, calendar: { classPropertyName: "calendar", publicName: "calendar", isSignal: true, isRequired: false, transformFunction: null }, dayPeriod: { classPropertyName: "dayPeriod", publicName: "dayPeriod", isSignal: true, isRequired: false, transformFunction: null }, numberingSystem: { classPropertyName: "numberingSystem", publicName: "numberingSystem", isSignal: true, isRequired: false, transformFunction: null }, dateStyle: { classPropertyName: "dateStyle", publicName: "dateStyle", isSignal: true, isRequired: false, transformFunction: null }, timeStyle: { classPropertyName: "timeStyle", publicName: "timeStyle", isSignal: true, isRequired: false, transformFunction: null }, hourCycle: { classPropertyName: "hourCycle", publicName: "hourCycle", isSignal: true, isRequired: false, transformFunction: null }, hour12: { classPropertyName: "hour12", publicName: "hour12", isSignal: true, isRequired: false, transformFunction: null }, localeMatcher: { classPropertyName: "localeMatcher", publicName: "localeMatcher", isSignal: true, isRequired: false, transformFunction: null }, formatMatcher: { classPropertyName: "formatMatcher", publicName: "formatMatcher", isSignal: true, isRequired: false, transformFunction: null }, weekday: { classPropertyName: "weekday", publicName: "weekday", isSignal: true, isRequired: false, transformFunction: null }, era: { classPropertyName: "era", publicName: "era", isSignal: true, isRequired: false, transformFunction: null }, year: { classPropertyName: "year", publicName: "year", isSignal: true, isRequired: false, transformFunction: null }, month: { classPropertyName: "month", publicName: "month", isSignal: true, isRequired: false, transformFunction: null }, day: { classPropertyName: "day", publicName: "day", isSignal: true, isRequired: false, transformFunction: null }, hour: { classPropertyName: "hour", publicName: "hour", isSignal: true, isRequired: false, transformFunction: null }, minute: { classPropertyName: "minute", publicName: "minute", isSignal: true, isRequired: false, transformFunction: null }, second: { classPropertyName: "second", publicName: "second", isSignal: true, isRequired: false, transformFunction: null }, fractionalSecondDigits: { classPropertyName: "fractionalSecondDigits", publicName: "fractionalSecondDigits", isSignal: true, isRequired: false, transformFunction: null }, timeZoneName: { classPropertyName: "timeZoneName", publicName: "timeZoneName", isSignal: true, isRequired: false, transformFunction: null } }, host: { properties: { "attr.datetime": "view().iso", "attr.data-locale": "view().locale", "attr.data-time-zone": "view().timeZone", "textContent": "view().text" } }, ngImport: i0 });
|
|
103
|
+
}
|
|
104
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.3.2", ngImport: i0, type: Time, decorators: [{
|
|
105
|
+
type: Directive,
|
|
106
|
+
args: [{
|
|
107
|
+
selector: "time[hamurTime]",
|
|
108
|
+
host: {
|
|
109
|
+
"[attr.datetime]": "view().iso",
|
|
110
|
+
"[attr.data-locale]": "view().locale",
|
|
111
|
+
"[attr.data-time-zone]": "view().timeZone",
|
|
112
|
+
"[textContent]": "view().text",
|
|
113
|
+
},
|
|
114
|
+
}]
|
|
115
|
+
}], ctorParameters: () => [], propDecorators: { datetime: [{ type: i0.Input, args: [{ isSignal: true, alias: "hamurTime", required: true }] }], locale: [{ type: i0.Input, args: [{ isSignal: true, alias: "locale", required: false }] }], timeZone: [{ type: i0.Input, args: [{ isSignal: true, alias: "timeZone", required: false }] }], relative: [{ type: i0.Input, args: [{ isSignal: true, alias: "relative", required: false }] }], relativeInterval: [{ type: i0.Input, args: [{ isSignal: true, alias: "relativeInterval", required: false }] }], calendar: [{ type: i0.Input, args: [{ isSignal: true, alias: "calendar", required: false }] }], dayPeriod: [{ type: i0.Input, args: [{ isSignal: true, alias: "dayPeriod", required: false }] }], numberingSystem: [{ type: i0.Input, args: [{ isSignal: true, alias: "numberingSystem", required: false }] }], dateStyle: [{ type: i0.Input, args: [{ isSignal: true, alias: "dateStyle", required: false }] }], timeStyle: [{ type: i0.Input, args: [{ isSignal: true, alias: "timeStyle", required: false }] }], hourCycle: [{ type: i0.Input, args: [{ isSignal: true, alias: "hourCycle", required: false }] }], hour12: [{ type: i0.Input, args: [{ isSignal: true, alias: "hour12", required: false }] }], localeMatcher: [{ type: i0.Input, args: [{ isSignal: true, alias: "localeMatcher", required: false }] }], formatMatcher: [{ type: i0.Input, args: [{ isSignal: true, alias: "formatMatcher", required: false }] }], weekday: [{ type: i0.Input, args: [{ isSignal: true, alias: "weekday", required: false }] }], era: [{ type: i0.Input, args: [{ isSignal: true, alias: "era", required: false }] }], year: [{ type: i0.Input, args: [{ isSignal: true, alias: "year", required: false }] }], month: [{ type: i0.Input, args: [{ isSignal: true, alias: "month", required: false }] }], day: [{ type: i0.Input, args: [{ isSignal: true, alias: "day", required: false }] }], hour: [{ type: i0.Input, args: [{ isSignal: true, alias: "hour", required: false }] }], minute: [{ type: i0.Input, args: [{ isSignal: true, alias: "minute", required: false }] }], second: [{ type: i0.Input, args: [{ isSignal: true, alias: "second", required: false }] }], fractionalSecondDigits: [{ type: i0.Input, args: [{ isSignal: true, alias: "fractionalSecondDigits", required: false }] }], timeZoneName: [{ type: i0.Input, args: [{ isSignal: true, alias: "timeZoneName", required: false }] }] } });
|