@hamur/adapter-angular 0.0.0-stage → 0.0.1

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.
Files changed (88) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +42 -2
  3. package/dist/chunks/browser-index-7h7x2xz2.js +131 -0
  4. package/dist/chunks/browser-index-nann848q.js +205 -0
  5. package/dist/chunks/browser-index-qn8q5fa2.js +580 -0
  6. package/dist/src/adapter.js +1073 -0
  7. package/dist/src/error-page.js +34 -0
  8. package/dist/src/index.js +1729 -0
  9. package/dist/src/keepalive.js +0 -0
  10. package/dist/src/runtime/client.js +21 -0
  11. package/dist/src/runtime/island.js +92 -0
  12. package/dist/src/runtime/server.js +175 -0
  13. package/dist/types/src/activation.d.ts +20 -0
  14. package/dist/types/src/adapter.d.ts +7 -0
  15. package/dist/types/src/app.d.ts +3 -0
  16. package/dist/types/src/async-data.d.ts +21 -0
  17. package/dist/types/src/client-parts.d.ts +32 -0
  18. package/dist/types/src/compile.d.ts +97 -0
  19. package/dist/types/src/context.d.ts +74 -0
  20. package/dist/types/src/data.d.ts +65 -0
  21. package/dist/types/src/definition.d.ts +13 -0
  22. package/dist/types/src/error-page.d.ts +5 -0
  23. package/dist/types/src/error.d.ts +4 -0
  24. package/dist/types/src/form.d.ts +65 -0
  25. package/dist/types/src/head.d.ts +12 -0
  26. package/dist/types/src/hmr.d.ts +14 -0
  27. package/dist/types/src/hydration.d.ts +16 -0
  28. package/dist/types/src/index.d.ts +24 -0
  29. package/dist/types/src/indicators.d.ts +69 -0
  30. package/dist/types/src/island.d.ts +39 -0
  31. package/dist/types/src/keepalive.d.ts +1 -0
  32. package/dist/types/src/link.d.ts +65 -0
  33. package/dist/types/src/markdown-page.d.ts +10 -0
  34. package/dist/types/src/markdown.d.ts +37 -0
  35. package/dist/types/src/mask.d.ts +12 -0
  36. package/dist/types/src/navigate.d.ts +14 -0
  37. package/dist/types/src/outlet.d.ts +71 -0
  38. package/dist/types/src/request.d.ts +31 -0
  39. package/dist/types/src/routing.d.ts +47 -0
  40. package/dist/types/src/runtime/client.d.ts +29 -0
  41. package/dist/types/src/runtime/hydration-dev.d.ts +1 -0
  42. package/dist/types/src/runtime/hydration.d.ts +8 -0
  43. package/dist/types/src/runtime/island.d.ts +8 -0
  44. package/dist/types/src/runtime/server.d.ts +15 -0
  45. package/dist/types/src/server-island.d.ts +21 -0
  46. package/dist/types/src/state.d.ts +14 -0
  47. package/dist/types/src/svg.d.ts +15 -0
  48. package/dist/types/src/time.d.ts +37 -0
  49. package/dist/types/src/wrapper.d.ts +21 -0
  50. package/package.json +56 -4
  51. package/src/activation.ts +83 -0
  52. package/src/adapter.ts +107 -0
  53. package/src/app.ts +6 -0
  54. package/src/async-data.ts +105 -0
  55. package/src/client-parts.ts +127 -0
  56. package/src/compile.ts +959 -0
  57. package/src/context.ts +189 -0
  58. package/src/data.ts +389 -0
  59. package/src/definition.ts +144 -0
  60. package/src/error-page.ts +17 -0
  61. package/src/error.ts +15 -0
  62. package/src/form.ts +253 -0
  63. package/src/head.ts +63 -0
  64. package/src/hmr.ts +61 -0
  65. package/src/hydration.ts +120 -0
  66. package/src/index.ts +98 -0
  67. package/src/indicators.ts +251 -0
  68. package/src/island.ts +95 -0
  69. package/src/keepalive.ts +1 -0
  70. package/src/link.ts +251 -0
  71. package/src/markdown-page.ts +31 -0
  72. package/src/markdown.ts +170 -0
  73. package/src/mask.ts +36 -0
  74. package/src/navigate.ts +19 -0
  75. package/src/outlet.ts +344 -0
  76. package/src/request.ts +170 -0
  77. package/src/routing.ts +218 -0
  78. package/src/runtime/client.ts +140 -0
  79. package/src/runtime/contract.d.ts +4 -0
  80. package/src/runtime/hydration-dev.ts +18 -0
  81. package/src/runtime/hydration.ts +7 -0
  82. package/src/runtime/island.ts +109 -0
  83. package/src/runtime/server.ts +228 -0
  84. package/src/server-island.ts +54 -0
  85. package/src/state.ts +70 -0
  86. package/src/svg.ts +65 -0
  87. package/src/time.ts +108 -0
  88. 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, "&amp;").replace(/"/g, "&quot;")}"` : ""
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,54 @@
1
+ import { Component, PendingTasks, effect, inject, input, type OnInit, type TemplateRef } 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
+
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
+ @Component({ selector: "hamur-server-island", template: "" })
12
+ export class ServerIsland extends HostWriter implements OnInit {
13
+ /** The name of a component under `app/server-islands/`. */
14
+ readonly name = input.required<string>()
15
+ readonly props = input<Record<string, unknown>>()
16
+ /** Rendered with the page; replaced by the island's HTML once the browser has it. */
17
+ readonly fallback = input<TemplateRef<unknown>>()
18
+ private readonly app = inject(HAMUR_APP, { optional: true })
19
+ private readonly id = injectId()
20
+ private readonly tasks = inject(PendingTasks)
21
+ private readonly fail = inject(HAMUR_FAIL, { optional: true })
22
+ private readonly server = onServer()
23
+ private readonly kept: boolean
24
+
25
+ constructor() {
26
+ super()
27
+ if (!this.app) throw new Error("ServerIsland must be rendered inside a Hamur app")
28
+ this.kept = !this.server && this.app.asyncData.hydrating
29
+ if (this.server || this.kept) return
30
+ effect(() => {
31
+ const name = this.name()
32
+ const props = this.props()
33
+ this.renderer.setAttribute(this.host, "name", name)
34
+ if (props && Object.keys(props).length)
35
+ this.renderer.setAttribute(this.host, "props", serverIslandProps(name, props))
36
+ else this.renderer.removeAttribute(this.host, "props")
37
+ })
38
+ }
39
+
40
+ ngOnInit(): void {
41
+ if (this.kept) return
42
+ const fallback = this.fallback()
43
+ if (fallback) this.append(fallback)
44
+ if (!this.server) return
45
+ const { attributes } = renderServerIsland(this.app!, this.id, this.name(), this.props())
46
+ const done = this.tasks.add()
47
+ attributes
48
+ .then((written) => {
49
+ for (const [name, value] of Object.entries(written)) this.renderer.setAttribute(this.host, name, value)
50
+ })
51
+ .catch((error: unknown) => this.fail?.(error))
52
+ .finally(done)
53
+ }
54
+ }
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
+ "&": "&amp;",
6
+ "<": "&lt;",
7
+ ">": "&gt;",
8
+ "@": "&#64;",
9
+ "{": '{{ "{" }}',
10
+ "}": '{{ "}" }}',
11
+ }
12
+ const ATTRIBUTE: Record<string, string> = { "&": "&amp;", '"': "&quot;", "<": "&lt;", ">": "&gt;" }
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,108 @@
1
+ import {
2
+ Directive,
3
+ afterRenderEffect,
4
+ booleanAttribute,
5
+ computed,
6
+ inject,
7
+ input,
8
+ numberAttribute,
9
+ signal,
10
+ } from "@angular/core"
11
+ import { timeView, watchTime } from "hamur/adapter"
12
+ import type { TimeInput } from "hamur/adapter"
13
+ import { HAMUR_APP, HAMUR_ROUTE, required } from "./context.ts"
14
+
15
+ type Format = Intl.DateTimeFormatOptions
16
+
17
+ const optionalBoolean = (value: unknown): boolean | undefined =>
18
+ value === undefined ? undefined : booleanAttribute(value)
19
+ const optionalNumber = (value: unknown): number | undefined =>
20
+ value === undefined ? undefined : numberAttribute(value)
21
+
22
+ /**
23
+ * `<time [hamurTime]="date">` writes the `datetime`, `data-locale` and `data-time-zone` attributes and the formatted text;
24
+ * `relative` refreshes the text every `relativeInterval` ms in the browser. The other inputs are the `Intl.DateTimeFormat` options.
25
+ */
26
+ @Directive({
27
+ selector: "time[hamurTime]",
28
+ host: {
29
+ "[attr.datetime]": "view().iso",
30
+ "[attr.data-locale]": "view().locale",
31
+ "[attr.data-time-zone]": "view().timeZone",
32
+ "[textContent]": "view().text",
33
+ },
34
+ })
35
+ export class Time {
36
+ readonly datetime = input.required<Date | number | string>({ alias: "hamurTime" })
37
+ readonly locale = input<string>()
38
+ readonly timeZone = input<string>()
39
+ readonly relative = input(false, { transform: booleanAttribute })
40
+ readonly relativeInterval = input<number | undefined, unknown>(undefined, { transform: optionalNumber })
41
+ readonly calendar = input<Format["calendar"]>()
42
+ readonly dayPeriod = input<Format["dayPeriod"]>()
43
+ readonly numberingSystem = input<Format["numberingSystem"]>()
44
+ readonly dateStyle = input<Format["dateStyle"]>()
45
+ readonly timeStyle = input<Format["timeStyle"]>()
46
+ readonly hourCycle = input<Format["hourCycle"]>()
47
+ readonly hour12 = input<boolean | undefined, unknown>(undefined, { transform: optionalBoolean })
48
+ readonly localeMatcher = input<Format["localeMatcher"]>()
49
+ readonly formatMatcher = input<Format["formatMatcher"]>()
50
+ readonly weekday = input<Format["weekday"]>()
51
+ readonly era = input<Format["era"]>()
52
+ readonly year = input<Format["year"]>()
53
+ readonly month = input<Format["month"]>()
54
+ readonly day = input<Format["day"]>()
55
+ readonly hour = input<Format["hour"]>()
56
+ readonly minute = input<Format["minute"]>()
57
+ readonly second = input<Format["second"]>()
58
+ readonly fractionalSecondDigits = input<Format["fractionalSecondDigits"], unknown>(undefined, {
59
+ transform: optionalNumber as (value: unknown) => Format["fractionalSecondDigits"],
60
+ })
61
+ readonly timeZoneName = input<Format["timeZoneName"]>()
62
+
63
+ private readonly app = required(HAMUR_APP, "Time")
64
+ private readonly route = inject(HAMUR_ROUTE, { optional: true })
65
+ private readonly now = signal<number | undefined>(undefined)
66
+
67
+ private readonly props = computed<TimeInput>(() => {
68
+ const given: Record<string, unknown> = {
69
+ datetime: this.datetime(),
70
+ locale: this.locale(),
71
+ timeZone: this.timeZone(),
72
+ relative: this.relative(),
73
+ relativeInterval: this.relativeInterval(),
74
+ calendar: this.calendar(),
75
+ dayPeriod: this.dayPeriod(),
76
+ numberingSystem: this.numberingSystem(),
77
+ dateStyle: this.dateStyle(),
78
+ timeStyle: this.timeStyle(),
79
+ hourCycle: this.hourCycle(),
80
+ hour12: this.hour12(),
81
+ localeMatcher: this.localeMatcher(),
82
+ formatMatcher: this.formatMatcher(),
83
+ weekday: this.weekday(),
84
+ era: this.era(),
85
+ year: this.year(),
86
+ month: this.month(),
87
+ day: this.day(),
88
+ hour: this.hour(),
89
+ minute: this.minute(),
90
+ second: this.second(),
91
+ fractionalSecondDigits: this.fractionalSecondDigits(),
92
+ timeZoneName: this.timeZoneName(),
93
+ }
94
+ return Object.fromEntries(Object.entries(given).filter(([, value]) => value !== undefined)) as unknown as TimeInput
95
+ })
96
+
97
+ protected readonly view = computed(() => timeView(this.app, this.route?.().path ?? "/", this.props(), this.now()))
98
+
99
+ private readonly interval = computed(() => this.view().interval)
100
+
101
+ constructor() {
102
+ afterRenderEffect((onCleanup) => {
103
+ const interval = this.interval()
104
+ if (interval === undefined) return
105
+ onCleanup(watchTime(interval, (next) => this.now.set(next)))
106
+ })
107
+ }
108
+ }