@lincyaw/host 0.0.0-stage → 1.0.0-rc.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.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,39 @@
1
- # Temporary Holding Version
1
+ # @lincyaw/host
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Presmium's host interface for plugin components: step state, services, shared state, interface text, the site path and the design system, the same in the web form and in the slides (both are the viewer).
4
+
5
+ Part of [Presmium](https://github.com/Lincyaw/presmium), which compiles canonical lecture.json teaching documents into web pages, slides, Jupyter notebooks and narrated playback.
6
+
7
+ ## Install
8
+
9
+ Plugins declare it as a peer dependency (`"@lincyaw/host": "^1.0.0"`); a document's own components in `components/` need it in the document's `package.json`.
10
+
11
+ ## Usage
12
+
13
+ ```tsx
14
+ import { useMessages, useStepState } from '@lincyaw/host'
15
+
16
+ export default function Completion() {
17
+ const shown = useStepState({ from: 1 })
18
+ const t = useMessages({ 'zh-CN': { done: '完成' }, en: { done: 'Done' } })
19
+ return shown.reached ? <p>{t.done}</p> : null
20
+ }
21
+ ```
22
+
23
+ Components get everything through this package, so both forms render them; browser code finds the site path with `siteBase()`, not `import.meta.env.BASE_URL`. It also provides the design system: the `Pm*` components (`PmButton`, `PmDialog`, `PmIcon` and others) in React, over the `--pm-*` tokens, the classes and the fonts (IBM Plex Sans, IBM Plex Mono and Source Serif 4, SIL Open Font License 1.1) of `@lincyaw/design`, which it loads into every page.
24
+
25
+ The interactive primitives wrap Radix Primitives; positioning, dismissal, keyboard navigation and focus management come from the library. Theme observation uses host React hooks, and shared icon names map to Lucide.
26
+
27
+ Hooks return ordinary React values. `useSharedState` returns `[value, setValue]`; service observables use `Store<T>` and `useStore(store)`. Outside components, read services with `presmiumService` and server access with `serverClient()`, then release subscriptions in plugin disposal.
28
+
29
+ ## Experimental parts
30
+
31
+ `useToolbarPlacement` and `provideToolbarPlacement` are experimental and outside the 1.x semver promise; their declarations carry the TSDoc tag `@experimental`, and the interface list names them.
32
+
33
+ ## Documentation
34
+
35
+ - [Plugin guide](https://github.com/Lincyaw/presmium/blob/main/site/plugins/locales/en/lecture.json)
36
+
37
+ ## License
38
+
39
+ Apache-2.0
package/package.json CHANGED
@@ -1,6 +1,51 @@
1
1
  {
2
2
  "name": "@lincyaw/host",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "1.0.0-rc.1",
4
+ "description": "Presmium's host interface for plugin components in every form: step state, services, interface text, and the design system (tokens, components, fonts)",
5
+ "license": "Apache-2.0",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/Lincyaw/presmium.git",
9
+ "directory": "packages/host"
10
+ },
11
+ "homepage": "https://github.com/Lincyaw/presmium/tree/main/packages/host#readme",
12
+ "bugs": "https://github.com/Lincyaw/presmium/issues",
13
+ "keywords": [
14
+ "presmium",
15
+ "react",
16
+ "design-system"
17
+ ],
18
+ "type": "module",
19
+ "engines": {
20
+ "node": ">=22.19"
21
+ },
22
+ "publishConfig": {
23
+ "access": "public"
24
+ },
25
+ "exports": {
26
+ ".": "./src/index.ts",
27
+ "./design.css": "./src/design/design.css"
28
+ },
29
+ "files": [
30
+ "src"
31
+ ],
32
+ "dependencies": {
33
+ "@fontsource/ibm-plex-mono": "5.3.0",
34
+ "@fontsource/ibm-plex-sans": "5.3.0",
35
+ "@fontsource/source-serif-4": "5.3.1",
36
+ "@radix-ui/react-dialog": "^1.3.1",
37
+ "@radix-ui/react-dropdown-menu": "^2.2.1",
38
+ "@radix-ui/react-popover": "^1.1.15",
39
+ "@radix-ui/react-radio-group": "^1.5.1",
40
+ "@radix-ui/react-tabs": "^1.1.13",
41
+ "@radix-ui/react-tooltip": "^1.2.8",
42
+ "react": "18.3.1",
43
+ "react-dom": "18.3.1",
44
+ "@lincyaw/design": "1.0.0-rc.1",
45
+ "@lincyaw/kernel": "1.0.0-rc.1"
46
+ },
47
+ "devDependencies": {
48
+ "@types/react": "18.3.28",
49
+ "@types/react-dom": "18.3.7"
50
+ }
6
51
  }
package/src/actions.ts ADDED
@@ -0,0 +1,22 @@
1
+ import { useEffect, useRef } from 'react'
2
+ import type { RefObject } from 'react'
3
+ import { blockKeyOf } from './blocks.ts'
4
+ import type { Operations, ReplayHandler } from './contracts.ts'
5
+ export type ComponentAction = (seeking: boolean) => void
6
+ export interface ActionOptions { clear?(): void }
7
+ interface Registration { element(): Element | undefined, actions: Readonly<Record<string, ComponentAction>>, clear?(): void }
8
+ const registered = new Set<Registration>()
9
+ const done = new Map<string, string[]>()
10
+ let operations: Operations | undefined
11
+ const record = (block: string, action: string) => done.set(block, [...done.get(block) ?? [], action])
12
+ function keyOf(element: Element | null | undefined) { const block = element?.closest<HTMLElement>('.pm-block[data-block]'); return block ? blockKeyOf(block) : undefined }
13
+ export function useActions(element: RefObject<Element | null | undefined>, actions: Readonly<Record<string, ComponentAction>>, options: ActionOptions = {}): (name: string) => void {
14
+ const current = useRef({ actions, options }); current.current = { actions, options }
15
+ useEffect(() => { const registration: Registration = { element: () => element.current ?? undefined, get actions() { return current.current.actions }, clear: () => current.current.options.clear?.() }; registered.add(registration); const block = keyOf(element.current); for (const name of block ? done.get(block) ?? [] : []) current.current.actions[name]?.(true); return () => { registered.delete(registration) } }, [element])
16
+ return name => { const action = current.current.actions[name]; if (!action) return; action(false); const block = keyOf(element.current); if (!block) return; record(block, name); operations?.report({ type: 'click', data: { block, action: name } }) }
17
+ }
18
+ const clickReplay: ReplayHandler = {
19
+ apply(data, seeking) { if (typeof data.block !== 'string' || typeof data.action !== 'string') return; record(data.block, data.action); for (const registration of registered) { const action = registration.actions[data.action]; if (action && keyOf(registration.element()) === data.block) action(seeking) } },
20
+ clear() { done.clear(); for (const registration of registered) registration.clear?.() },
21
+ }
22
+ export function connectActions(to: Operations): void { operations = to; to.onReplay('click', clickReplay) }
@@ -0,0 +1,12 @@
1
+ import { createElement as h, useState } from 'react'
2
+ import { PmButton, PmNotice, PmPopover } from './design/components.ts'
3
+ import { useMessages } from './locale.ts'
4
+ import { HOST_MESSAGES } from './messages.ts'
5
+ import { approvals } from './control.ts'
6
+ import { useStore } from './store.ts'
7
+ export function PmApprovals({ placement = 'below' }: { placement?: 'below' | 'above' }) {
8
+ const t = useMessages(HOST_MESSAGES); const [open, setOpen] = useState(false); const [failed, setFailed] = useState<string>(); const pending = useStore(approvals.pending)
9
+ if (!pending.length) return null
10
+ const answer = (id: string, allow: boolean) => { setFailed(undefined); void approvals.answer(id, allow).catch(() => setFailed(t.answerFailed)) }
11
+ return h(PmPopover, { open, label: t.approvalsTitle, name: 'pm-approvals', placement: placement === 'above' ? 'above-end' : 'below-end', onOpenChange: setOpen, trigger: h(PmButton, { variant: 'accent', small: true }, t.approvals(pending.length)) }, pending.map(({ id, request }) => h('div', { key: id, 'data-approval': id }, h('p', {}, request.title), h('p', {}, t.from(t.origins[request.from] ?? t.otherOrigin)), ...(request.detail ?? '').split('\n').filter(Boolean).map((line, key) => h('p', { key }, line)), h(PmButton, { small: true, variant: 'primary', onClick: () => answer(id, true) }, t.allow), h(PmButton, { small: true, onClick: () => answer(id, false) }, t.deny))), failed ? h(PmNotice, { tone: 'danger' }, failed) : null)
12
+ }
package/src/blocks.ts ADDED
@@ -0,0 +1,81 @@
1
+ const UNSEEN = '[inert], .pm-hidden'
2
+
3
+ export function blockKey(section: string, block: string): string {
4
+ return `${section}/${block}`
5
+ }
6
+
7
+ export function splitBlockKey(key: string): [section: string, block: string] | undefined {
8
+ const cut = key.lastIndexOf('/')
9
+ return cut > 0 && cut < key.length - 1 ? [key.slice(0, cut), key.slice(cut + 1)] : undefined
10
+ }
11
+
12
+ function seen(element: Element): boolean {
13
+ return !element.closest(UNSEEN) && element.getClientRects().length > 0
14
+ }
15
+
16
+ export function blockElement(key: string): HTMLElement | undefined {
17
+ const parts = splitBlockKey(key)
18
+ if (!parts || typeof document === 'undefined') return undefined
19
+ const found = document.querySelectorAll<HTMLElement>(`[data-section="${CSS.escape(parts[0])}"] .pm-block[data-block="${CSS.escape(parts[1])}"]`)
20
+ for (const element of found) if (seen(element)) return element
21
+ return undefined
22
+ }
23
+
24
+ export interface BlockPoint {
25
+ key: string
26
+ element: HTMLElement
27
+ x: number
28
+ y: number
29
+ line?: number
30
+ }
31
+
32
+ export function codeLines(block: Element): HTMLElement[] {
33
+ return [...block.querySelectorAll<HTMLElement>('.pm-code .line')]
34
+ }
35
+
36
+ /** The `<section>/<block>` key of a block's element (`.pm-block[data-block]`). */
37
+ export function blockKeyOf(block: HTMLElement): string | undefined {
38
+ const section = block.closest<HTMLElement>('[data-section]')?.dataset.section
39
+ return section ? blockKey(section, block.dataset.block!) : undefined
40
+ }
41
+
42
+ export function blockAt(x: number, y: number, options: { skip?: Element, within?: string } = {}): BlockPoint | undefined {
43
+ if (typeof document === 'undefined') return undefined
44
+ const { skip, within } = options
45
+ const hit = document.elementsFromPoint(x, y).find(el => el !== skip && !skip?.contains(el))
46
+ const element = hit?.closest<HTMLElement>(`${within ? `${within} ` : ''}.pm-block[data-block]`)
47
+ const key = element && blockKeyOf(element)
48
+ if (!element || !key || !seen(element)) return undefined
49
+ const box = element.getBoundingClientRect()
50
+ if (!box.width || !box.height) return undefined
51
+ const index = codeLines(element).findIndex((line) => {
52
+ const r = line.getBoundingClientRect()
53
+ return y >= r.top && y < r.bottom
54
+ })
55
+ return {
56
+ key,
57
+ element,
58
+ x: (x - box.left) / box.width,
59
+ y: (y - box.top) / box.height,
60
+ ...index >= 0 ? { line: index + 1 } : {},
61
+ }
62
+ }
63
+
64
+ export function lineNumbers(lines: string): number[] {
65
+ return lines.split(/[\s,]+/).flatMap((part) => {
66
+ const [from, to = from] = part.split('-').map(Number)
67
+ return Number.isInteger(from) && Number.isInteger(to) && from! > 0 ? Array.from({ length: Math.max(0, to! - from! + 1) }, (_, k) => from! + k) : []
68
+ })
69
+ }
70
+
71
+ export function linesText(numbers: number[]): string {
72
+ const sorted = [...new Set(numbers)].sort((a, b) => a - b)
73
+ const runs: string[] = []
74
+ for (let i = 0; i < sorted.length;) {
75
+ let j = i
76
+ while (j + 1 < sorted.length && sorted[j + 1] === sorted[j]! + 1) j++
77
+ runs.push(i === j ? String(sorted[i]) : `${sorted[i]}-${sorted[j]}`)
78
+ i = j + 1
79
+ }
80
+ return runs.join(',')
81
+ }
@@ -0,0 +1,13 @@
1
+ import { createStore } from './store.ts'
2
+ import type { Store } from './store.ts'
3
+ const groups = new Map<string, Store<symbol[]>>()
4
+ export function claimFirst(group: string): { owns: Store<boolean>, release(): void } {
5
+ let owners = groups.get(group)
6
+ if (!owners) { owners = createStore<symbol[]>([]); groups.set(group, owners) }
7
+ const list = owners
8
+ const claim = Symbol(group)
9
+ list.set([...list.getSnapshot(), claim])
10
+ const owns = createStore(list.getSnapshot()[0] === claim)
11
+ const stop = list.subscribe(() => owns.set(list.getSnapshot()[0] === claim))
12
+ return { owns, release() { stop(); list.set(list.getSnapshot().filter(other => other !== claim)) } }
13
+ }
@@ -0,0 +1,11 @@
1
+ import { codeLines, lineNumbers } from './blocks.ts'
2
+
3
+ export function codeLinesBox(block: HTMLElement, lines: string): DOMRect | undefined {
4
+ const rows = codeLines(block)
5
+ const named = lineNumbers(lines).map(n => rows[n - 1]).filter((row): row is HTMLElement => Boolean(row))
6
+ if (named.length === 0) return undefined
7
+ const code = block.querySelector('.pm-code')?.getBoundingClientRect() ?? block.getBoundingClientRect()
8
+ const top = Math.min(...named.map(row => row.getBoundingClientRect().top))
9
+ const bottom = Math.max(...named.map(row => row.getBoundingClientRect().bottom))
10
+ return new DOMRect(code.left, top, code.width, bottom - top)
11
+ }
@@ -0,0 +1,157 @@
1
+ import type { Dispatch, SetStateAction } from 'react'
2
+ import type { Store } from './store.ts'
3
+ import { defineService } from '@lincyaw/kernel/contracts'
4
+ import type { Cursor, Member, Operation, PresentationMode, ServiceToken, StartReport, Unsubscribe } from '@lincyaw/kernel/contracts'
5
+ import type { IRDocument, ProductionPlaybackCommand, ProductionPlaybackState } from '@lincyaw/kernel'
6
+ import type { IconName } from '@lincyaw/design'
7
+
8
+ export type ViewRole = 'audience' | 'presenter' | 'reader'
9
+
10
+ export type SharedStateScope = 'view' | 'local' | 'remote'
11
+
12
+ export interface HostAdapter {
13
+ readonly mode: PresentationMode
14
+ readonly lang?: string
15
+ useDoc?(): IRDocument
16
+ useCursor(): Cursor
17
+ useStep(): number
18
+ useViewRole(): ViewRole
19
+ useStaticRender(): boolean
20
+ useSectionConfig(pluginId: string): Record<string, unknown>
21
+ useSharedState<T>(key: string, initial: T, scope: SharedStateScope): [T, Dispatch<SetStateAction<T>>]
22
+ sharedStateStore?<T>(key: string, initial: T, scope: SharedStateScope): Store<T>
23
+ getService<T>(token: ServiceToken<T>): T | undefined
24
+ startReport(): StartReport | undefined
25
+ useDarkMode?(): [boolean, Dispatch<SetStateAction<boolean>>]
26
+ }
27
+
28
+ export type SyncPublish = (state: Readonly<Record<string, unknown>>, fromRemote: boolean) => void
29
+
30
+ export interface SyncTransport {
31
+ connect(
32
+ channel: string,
33
+ receive: (patch: Record<string, unknown>) => void,
34
+ state: Readonly<Record<string, unknown>>,
35
+ persist: boolean,
36
+ ): SyncPublish | undefined
37
+ }
38
+
39
+ export interface SyncTransports {
40
+ add(transport: SyncTransport): Unsubscribe
41
+ }
42
+
43
+ export const SYNC_TRANSPORTS = defineService<SyncTransports>('presmium.syncTransports')
44
+
45
+ export interface NavigationPosition extends Cursor {
46
+ /** Transient seek intent; authoring steps and Production retain no duplicate timing. */
47
+ boundary?: 'start' | 'end'
48
+ view?: string
49
+ section?: string
50
+ }
51
+
52
+ export interface Navigation {
53
+ readonly position: Store<NavigationPosition>
54
+ go(position: NavigationPosition): void
55
+ }
56
+
57
+ export const NAVIGATION = defineService<Navigation>('presmium.navigation')
58
+
59
+ export type ToolbarSlot = 'tools' | 'settings' | 'status'
60
+
61
+ export type ToolbarPlacement = 'bar' | 'status'
62
+
63
+ export interface ToolbarItem {
64
+ id: string
65
+ title: string
66
+ component: unknown
67
+ order?: number
68
+ slot?: ToolbarSlot
69
+ icon?: IconName
70
+ }
71
+
72
+ export interface Toolbar {
73
+ register(item: ToolbarItem): Unsubscribe
74
+ list(): ToolbarItem[]
75
+ subscribe(listener: () => void): Unsubscribe
76
+ }
77
+
78
+ export const TOOLBAR = defineService<Toolbar>('presmium.toolbar')
79
+
80
+ export interface ServerClient {
81
+ readonly available: boolean
82
+ readonly member: Store<Member | undefined>
83
+ fetch(plugin: string, path: string, init?: RequestInit): Promise<Response>
84
+ events(plugin: string, path: string): EventSource
85
+ }
86
+
87
+ export interface StatusProvider {
88
+ id: string
89
+ read(): unknown
90
+ }
91
+
92
+ export interface StatusRegistry {
93
+ register(provider: StatusProvider): Unsubscribe
94
+ list(): StatusProvider[]
95
+ }
96
+
97
+ export const STATUS = defineService<StatusRegistry>('presmium.status')
98
+
99
+ export interface ReplayHandler {
100
+ apply(data: Record<string, unknown>, seeking: boolean): void
101
+ clear?(): void
102
+ }
103
+
104
+ export interface Operations {
105
+ report(operation: Operation): void
106
+ subscribe(listener: (operation: Operation) => void): Unsubscribe
107
+ onReplay(type: string, handler: ReplayHandler): Unsubscribe
108
+ replay(operation: Operation, seeking?: boolean): boolean
109
+ clear(): void
110
+ readonly replaying: Store<boolean>
111
+ }
112
+
113
+ export const OPERATIONS = defineService<Operations>('presmium.operations')
114
+
115
+ /** A registered player keeps its existing clock; this lease only coordinates whether it may start. */
116
+ export interface PlaybackLease {
117
+ requestStart(): Promise<boolean>
118
+ cancel(): void
119
+ dispose(): void
120
+ }
121
+
122
+ export interface PlaybackControl {
123
+ register(pause: () => void): PlaybackLease
124
+ pause(): void
125
+ /** Embedded previews await their author's audio focus before starting. Ordinary pages need no gate. */
126
+ setGate(authorize: (signal: AbortSignal) => Promise<void>): Unsubscribe
127
+ }
128
+
129
+ export const PLAYBACK_CONTROL = defineService<PlaybackControl>('presmium.playbackControl')
130
+
131
+ /** Observes the loaded player's clock and selects stable step boundaries; author interfaces never synthesize time. */
132
+ export interface ProductionPlayback {
133
+ readonly version: 1
134
+ readonly state: Pick<Store<ProductionPlaybackState | undefined>, 'getSnapshot' | 'subscribe'>
135
+ control(command: ProductionPlaybackCommand, signal?: AbortSignal): Promise<ProductionPlaybackState>
136
+ }
137
+ export const PRODUCTION_PLAYBACK = defineService<ProductionPlayback>('presmium.productionPlayback')
138
+
139
+ /** A loaded timed-caption player owns presentation captions until its lease is released. */
140
+ export interface TimedCaptions {
141
+ readonly active: Store<boolean>
142
+ claim(): Unsubscribe
143
+ }
144
+ export const TIMED_CAPTIONS = defineService<TimedCaptions>('presmium.timedCaptions')
145
+
146
+ export interface StepClockDriver {
147
+ readonly elapsed: Store<number | undefined>
148
+ readonly recording?: boolean
149
+ }
150
+
151
+ export interface StepClock {
152
+ drive(driver: StepClockDriver): Unsubscribe
153
+ wait(work: Promise<unknown>): void
154
+ settled(): Promise<void>
155
+ }
156
+
157
+ export const STEP_CLOCK = defineService<StepClock>('presmium.stepClock')