feat(docs): add Zotero citation integration (#332)
This commit is contained in:
@@ -120,6 +120,7 @@ import {
|
||||
} from './docx-encryption'
|
||||
import { isExternallyModified, type DiskFileState } from './external-change'
|
||||
import { initDocsAutoUpdater } from './updater'
|
||||
import { registerZoteroIpc, teardownZoteroIpc } from './zotero-ipc'
|
||||
|
||||
/**
|
||||
* Docs main-process logic as an embeddable module: no top-level side effects.
|
||||
@@ -2446,6 +2447,7 @@ async function diskChangedExternally(wcId: number, filePath: string): Promise<bo
|
||||
* workaround), so the orphan must lose write access and stop its timers — otherwise
|
||||
* its 30s recovery loop resurrects content the user already discarded. */
|
||||
export function teardownDocsRenderer(contents: WebContents): void {
|
||||
teardownZoteroIpc(contents)
|
||||
tornDownWcIds.add(contents.id)
|
||||
// Sweep recovery copies for this renderer's documents: every non-crash close
|
||||
// either saved (docs:save already cleared it) or explicitly discarded, so a
|
||||
@@ -3195,6 +3197,7 @@ export function registerProjectIpc(): void {
|
||||
|
||||
/** document/attachment/window IPC (everything except the AI proxy above) */
|
||||
export function registerDocsIpc(): void {
|
||||
registerZoteroIpc()
|
||||
// Node fetch (undici) direct connections get reset under VPN/tun setups; retry over Chromium's stack
|
||||
setRescueFetch((url, init) => net.fetch(url, init))
|
||||
setAiUserAgent(`GenOffice/${app.getVersion()}`)
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { ipcMain, type WebContents } from 'electron'
|
||||
import type { ZoteroCommandResult, ZoteroRendererResponse } from '../shared/ipc'
|
||||
import { ZoteroWireClient, type ZoteroWireRequest } from './zotero-wire'
|
||||
|
||||
const clients = new Map<number, ZoteroWireClient>()
|
||||
const pending = new Map<
|
||||
string,
|
||||
{ webContentsId: number; resolve: (value: unknown) => void; reject: (error: Error) => void }
|
||||
>()
|
||||
let registered = false
|
||||
|
||||
function requestRenderer(contents: WebContents, request: ZoteroWireRequest): Promise<unknown> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const requestId = randomUUID()
|
||||
const timer = setTimeout(() => {
|
||||
pending.delete(requestId)
|
||||
reject(new Error(`Timed out handling ${request.command}`))
|
||||
}, 120_000)
|
||||
pending.set(requestId, {
|
||||
webContentsId: contents.id,
|
||||
resolve: (value) => {
|
||||
clearTimeout(timer)
|
||||
resolve(value)
|
||||
},
|
||||
reject: (error) => {
|
||||
clearTimeout(timer)
|
||||
reject(error)
|
||||
},
|
||||
})
|
||||
contents.send('zotero:request', { requestId, ...request })
|
||||
})
|
||||
}
|
||||
|
||||
export function registerZoteroIpc(): void {
|
||||
if (registered) return
|
||||
registered = true
|
||||
|
||||
ipcMain.handle('zotero:command', async (event, command: string): Promise<ZoteroCommandResult> => {
|
||||
if (!/^(addEditCitation|addEditBibliography|refresh|setDocPrefs|removeCodes)$/.test(command)) {
|
||||
return { ok: false, errorCode: 'unsupported-command', error: 'Unsupported Zotero command' }
|
||||
}
|
||||
let client = clients.get(event.sender.id)
|
||||
if (!client) {
|
||||
client = new ZoteroWireClient()
|
||||
clients.set(event.sender.id, client)
|
||||
}
|
||||
try {
|
||||
await client.run(command, (request) => requestRenderer(event.sender, request))
|
||||
return { ok: true }
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error)
|
||||
return {
|
||||
ok: false,
|
||||
errorCode: /ECONNREFUSED/.test(message) ? 'connection-refused' : 'operation-failed',
|
||||
error: message,
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
ipcMain.on('zotero:response', (event, response: ZoteroRendererResponse) => {
|
||||
if (!response || typeof response.requestId !== 'string') return
|
||||
const waiter = pending.get(response.requestId)
|
||||
if (!waiter || waiter.webContentsId !== event.sender.id) return
|
||||
pending.delete(response.requestId)
|
||||
if (response.ok) waiter.resolve(response.result)
|
||||
else waiter.reject(new Error(response.error || 'Zotero document operation failed'))
|
||||
})
|
||||
}
|
||||
|
||||
export function teardownZoteroIpc(contents: WebContents): void {
|
||||
clients.get(contents.id)?.close()
|
||||
clients.delete(contents.id)
|
||||
for (const [requestId, waiter] of pending) {
|
||||
if (waiter.webContentsId !== contents.id) continue
|
||||
pending.delete(requestId)
|
||||
waiter.reject(new Error('The document was closed'))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
import { createConnection, type Socket } from 'node:net'
|
||||
|
||||
export const ZOTERO_INTEGRATION_HOST = '127.0.0.1'
|
||||
export const ZOTERO_INTEGRATION_PORT = 23116
|
||||
const MAX_PAYLOAD_BYTES = 16 * 1024 * 1024
|
||||
|
||||
export interface ZoteroWireFrame {
|
||||
transactionId: number
|
||||
payload: string
|
||||
}
|
||||
|
||||
export interface ZoteroWireRequest {
|
||||
command: string
|
||||
args: unknown[]
|
||||
}
|
||||
|
||||
export function encodeZoteroFrame(transactionId: number, payload: string): Buffer {
|
||||
const body = Buffer.from(payload, 'utf8')
|
||||
const frame = Buffer.allocUnsafe(8 + body.length)
|
||||
frame.writeUInt32BE(transactionId >>> 0, 0)
|
||||
frame.writeUInt32BE(body.length, 4)
|
||||
body.copy(frame, 8)
|
||||
return frame
|
||||
}
|
||||
|
||||
export class ZoteroFrameDecoder {
|
||||
private buffered = Buffer.alloc(0)
|
||||
|
||||
push(chunk: Uint8Array): ZoteroWireFrame[] {
|
||||
this.buffered = Buffer.concat([this.buffered, Buffer.from(chunk)])
|
||||
const frames: ZoteroWireFrame[] = []
|
||||
while (this.buffered.length >= 8) {
|
||||
const transactionId = this.buffered.readUInt32BE(0)
|
||||
const length = this.buffered.readUInt32BE(4)
|
||||
if (length > MAX_PAYLOAD_BYTES) throw new Error('Zotero integration payload is too large')
|
||||
if (this.buffered.length < 8 + length) break
|
||||
frames.push({
|
||||
transactionId,
|
||||
payload: this.buffered.subarray(8, 8 + length).toString('utf8'),
|
||||
})
|
||||
this.buffered = this.buffered.subarray(8 + length)
|
||||
}
|
||||
return frames
|
||||
}
|
||||
}
|
||||
|
||||
function parseRequest(payload: string): ZoteroWireRequest {
|
||||
const value: unknown = JSON.parse(payload)
|
||||
if (!Array.isArray(value) || typeof value[0] !== 'string' || !Array.isArray(value[1])) {
|
||||
throw new Error('Invalid Zotero integration request')
|
||||
}
|
||||
return { command: value[0], args: value[1] }
|
||||
}
|
||||
|
||||
function errorPayload(error: unknown): string {
|
||||
return `ERR:${error instanceof Error ? error.message : String(error)}`
|
||||
}
|
||||
|
||||
export class ZoteroWireClient {
|
||||
private socket: Socket | null = null
|
||||
private active = false
|
||||
|
||||
get isActive(): boolean {
|
||||
return this.active
|
||||
}
|
||||
|
||||
async run(
|
||||
command: string,
|
||||
handleRequest: (request: ZoteroWireRequest) => Promise<unknown>,
|
||||
): Promise<void> {
|
||||
if (this.active) throw new Error('A Zotero operation is already running')
|
||||
this.active = true
|
||||
const decoder = new ZoteroFrameDecoder()
|
||||
|
||||
try {
|
||||
const socket = await new Promise<Socket>((resolve, reject) => {
|
||||
const candidate = createConnection({
|
||||
host: ZOTERO_INTEGRATION_HOST,
|
||||
port: ZOTERO_INTEGRATION_PORT,
|
||||
})
|
||||
const onError = (error: Error) => reject(error)
|
||||
candidate.once('error', onError)
|
||||
candidate.once('connect', () => {
|
||||
candidate.off('error', onError)
|
||||
resolve(candidate)
|
||||
})
|
||||
})
|
||||
this.socket = socket
|
||||
socket.on('data', (chunk) => {
|
||||
let frames: ZoteroWireFrame[]
|
||||
try {
|
||||
frames = decoder.push(chunk)
|
||||
} catch (error) {
|
||||
socket.destroy(error instanceof Error ? error : new Error(String(error)))
|
||||
return
|
||||
}
|
||||
for (const frame of frames) void this.respondToFrame(socket, frame, handleRequest)
|
||||
})
|
||||
socket.once('close', () => {
|
||||
if (this.socket === socket) this.socket = null
|
||||
this.active = false
|
||||
})
|
||||
socket.once('error', () => {
|
||||
// Post-connect errors terminate the socket; request failures are returned as ERR frames.
|
||||
})
|
||||
socket.write(encodeZoteroFrame(0, JSON.stringify({ command, templateVersion: 1 })))
|
||||
} catch (error) {
|
||||
this.active = false
|
||||
this.socket = null
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.socket?.destroy()
|
||||
this.socket = null
|
||||
this.active = false
|
||||
}
|
||||
|
||||
private async respondToFrame(
|
||||
socket: Socket,
|
||||
frame: ZoteroWireFrame,
|
||||
handleRequest: (request: ZoteroWireRequest) => Promise<unknown>,
|
||||
): Promise<void> {
|
||||
if (frame.transactionId === 0) return
|
||||
let payload: string
|
||||
let command = ''
|
||||
try {
|
||||
const request = parseRequest(frame.payload)
|
||||
command = request.command
|
||||
payload = JSON.stringify(await handleRequest(request))
|
||||
} catch (error) {
|
||||
payload = errorPayload(error)
|
||||
}
|
||||
if (!socket.destroyed) socket.write(encodeZoteroFrame(frame.transactionId, payload))
|
||||
if (command === 'Document_complete') socket.end()
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import type {
|
||||
MenuCommand,
|
||||
AutoSaveDefault,
|
||||
UiTheme,
|
||||
ZoteroRendererRequest,
|
||||
} from '../shared/ipc'
|
||||
import type { ProjectApi } from '@genoffice/project-store'
|
||||
import { installDropOpenBridge } from '@genoffice/electron-utils/drop-open'
|
||||
@@ -47,6 +48,13 @@ const api: DesktopApi = {
|
||||
ipcRenderer.on('app:chrome-pressed', listener)
|
||||
return () => ipcRenderer.removeListener('app:chrome-pressed', listener)
|
||||
},
|
||||
zoteroCommand: (command) => ipcRenderer.invoke('zotero:command', command),
|
||||
onZoteroRequest: (handler) => {
|
||||
const listener = (_event: IpcRendererEvent, request: ZoteroRendererRequest) => handler(request)
|
||||
ipcRenderer.on('zotero:request', listener)
|
||||
return () => ipcRenderer.removeListener('zotero:request', listener)
|
||||
},
|
||||
respondToZotero: (response) => ipcRenderer.send('zotero:response', response),
|
||||
openDocx: () => ipcRenderer.invoke('docs:open'),
|
||||
openDocxPath: (path: string) => ipcRenderer.invoke('docs:open-path', path),
|
||||
openDocxDecrypt: (path: string, password: string) =>
|
||||
|
||||
@@ -40,6 +40,7 @@ import {
|
||||
} from '@genoffice/docx-engine'
|
||||
import type { AiDocContent, AiSettings, OpenDocxResult } from '../shared/ipc'
|
||||
import { AI_PROVIDERS } from '../shared/ipc'
|
||||
import { ZoteroDocumentController } from './zotero/controller'
|
||||
import { AiPanel, AI_REVISION_AUTHOR } from './ai/AiPanel'
|
||||
import type { AiCommentsAccess, AiHeaderFooterAccess } from './ai/tools'
|
||||
import { applyHfText, hfEditText } from './editor/hf-text'
|
||||
@@ -745,6 +746,13 @@ export function App() {
|
||||
const [notesDirty, setNotesDirty] = useState(false)
|
||||
const [sources, setSources] = useState<SourceInfo[]>([])
|
||||
const [sourcesDirty, setSourcesDirty] = useState(false)
|
||||
const [zoteroDocumentData, setZoteroDocumentDataState] = useState('')
|
||||
const [zoteroDocumentDataDirty, setZoteroDocumentDataDirty] = useState(false)
|
||||
const zoteroDocumentDataRef = useRef('')
|
||||
const setZoteroDocumentData = useCallback((value: string) => {
|
||||
zoteroDocumentDataRef.current = value
|
||||
setZoteroDocumentDataState(value)
|
||||
}, [])
|
||||
const [themeFonts, setThemeFonts] = useState<ThemeFonts | null>(null)
|
||||
const [themeFontsDirty, setThemeFontsDirty] = useState(false)
|
||||
const [themeColors, setThemeColors] = useState<ThemeColors | null>(null)
|
||||
@@ -838,6 +846,7 @@ export function App() {
|
||||
const saveIncompleteRef = useRef(false)
|
||||
|
||||
const editorRef = useRef<Editor | null>(null)
|
||||
const zoteroControllerRef = useRef<ZoteroDocumentController | null>(null)
|
||||
const editor = useEditor({
|
||||
extensions: editorExtensions,
|
||||
content: { type: 'doc', content: [{ type: 'docParagraph' }] },
|
||||
@@ -1410,6 +1419,10 @@ export function App() {
|
||||
sourcesDirty,
|
||||
setSources,
|
||||
setSourcesDirty,
|
||||
zoteroDocumentData,
|
||||
zoteroDocumentDataDirty,
|
||||
setZoteroDocumentData,
|
||||
setZoteroDocumentDataDirty,
|
||||
themeFonts,
|
||||
themeFontsDirty,
|
||||
themeColors,
|
||||
@@ -1776,8 +1789,38 @@ export function App() {
|
||||
// editorRef: lets the handlePaste closure (the useEditor config exists before the instance) reach the instance
|
||||
useEffect(() => {
|
||||
editorRef.current = editor
|
||||
zoteroControllerRef.current = null
|
||||
}, [editor])
|
||||
|
||||
useEffect(
|
||||
() =>
|
||||
window.desktop.onZoteroRequest(async (request) => {
|
||||
try {
|
||||
const activeEditor = editorRef.current
|
||||
if (!activeEditor) throw new Error('No active GenOffice document')
|
||||
const controller =
|
||||
zoteroControllerRef.current ??
|
||||
new ZoteroDocumentController(activeEditor, {
|
||||
get: () => zoteroDocumentDataRef.current,
|
||||
set: (value) => {
|
||||
setZoteroDocumentData(value)
|
||||
setZoteroDocumentDataDirty(true)
|
||||
},
|
||||
})
|
||||
zoteroControllerRef.current = controller
|
||||
const result = await controller.handle(request)
|
||||
window.desktop.respondToZotero({ requestId: request.requestId, ok: true, result })
|
||||
} catch (error) {
|
||||
window.desktop.respondToZotero({
|
||||
requestId: request.requestId,
|
||||
ok: false,
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
})
|
||||
}
|
||||
}),
|
||||
[setZoteroDocumentData],
|
||||
)
|
||||
|
||||
/** Pasted list items lacking a numId (schema default null; saving would lose list semantics):
|
||||
* reuse the numId of an existing same-kind instance, otherwise fall back to creating a definition */
|
||||
useEffect(() => {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useState } from 'react'
|
||||
import type { Editor } from '@tiptap/core'
|
||||
import type { ZoteroCommand } from '../../shared/ipc'
|
||||
import {
|
||||
bibliographyLine,
|
||||
citationText,
|
||||
@@ -358,6 +359,31 @@ export function ReferencesTab({
|
||||
const { t } = useI18n()
|
||||
const [captionOpen, setCaptionOpen] = useState(false)
|
||||
const [sourceOpen, setSourceOpen] = useState(false)
|
||||
const [zoteroBusy, setZoteroBusy] = useState<ZoteroCommand | null>(null)
|
||||
|
||||
const runZotero = async (command: ZoteroCommand) => {
|
||||
if (zoteroBusy) return
|
||||
setZoteroBusy(command)
|
||||
setDropdown(() => null)
|
||||
try {
|
||||
const result = await window.desktop.zoteroCommand(command)
|
||||
if (!result.ok) {
|
||||
console.error('Zotero integration failed', result.error)
|
||||
window.alert(
|
||||
t(
|
||||
result.errorCode === 'connection-refused'
|
||||
? 'zoteroConnectionError'
|
||||
: 'zoteroOperationError',
|
||||
),
|
||||
)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Zotero integration failed', error)
|
||||
window.alert(t('zoteroOperationError'))
|
||||
} finally {
|
||||
setZoteroBusy(null)
|
||||
}
|
||||
}
|
||||
|
||||
const insertToc = () => {
|
||||
const entries = collectTocEntriesWithPages(editor, headingPages)
|
||||
@@ -456,6 +482,71 @@ export function ReferencesTab({
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="ribbon-group">
|
||||
<div className="ribbon-group-items">
|
||||
<button
|
||||
className="rb-big"
|
||||
disabled={!hasDoc || zoteroBusy !== null}
|
||||
data-tip={t('zoteroCitationTip')}
|
||||
onClick={() => void runZotero('addEditCitation')}
|
||||
>
|
||||
<span className="rb-big-icon">
|
||||
<IconCitation size={BIG} />
|
||||
</span>
|
||||
<span>{t('zoteroCitation')}</span>
|
||||
</button>
|
||||
<button
|
||||
className="rb-big"
|
||||
disabled={!hasDoc || zoteroBusy !== null}
|
||||
data-tip={t('zoteroBibliographyTip')}
|
||||
onClick={() => void runZotero('addEditBibliography')}
|
||||
>
|
||||
<span className="rb-big-icon">
|
||||
<IconBook size={BIG} />
|
||||
</span>
|
||||
<span>{t('zoteroBibliography')}</span>
|
||||
</button>
|
||||
<button
|
||||
className="rb-big"
|
||||
disabled={!hasDoc || zoteroBusy !== null}
|
||||
data-tip={t('zoteroRefreshTip')}
|
||||
onClick={() => void runZotero('refresh')}
|
||||
>
|
||||
<span className="rb-big-icon">
|
||||
<IconRefresh size={BIG} />
|
||||
</span>
|
||||
<span>{t('zoteroRefresh')}</span>
|
||||
</button>
|
||||
<div className="rb-split-wrap">
|
||||
<button
|
||||
className="rb-big"
|
||||
disabled={!hasDoc || zoteroBusy !== null}
|
||||
data-tip={t('zoteroDocumentSettingsTip')}
|
||||
onClick={() => toggleDropdown(setDropdown, 'zotero-settings')}
|
||||
>
|
||||
<span className="rb-big-icon">
|
||||
<IconCitation size={BIG} />
|
||||
<IconCaret />
|
||||
</span>
|
||||
<span>{t('zoteroDocumentSettings')}</span>
|
||||
</button>
|
||||
{dropdown === 'zotero-settings' && (
|
||||
<div data-rb-panel="" className="layout-menu">
|
||||
<button onClick={() => void runZotero('setDocPrefs')}>
|
||||
{t('zoteroDocumentPreferences')}
|
||||
</button>
|
||||
<button onClick={() => void runZotero('removeCodes')}>
|
||||
{t('zoteroRemoveCodes')}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="ribbon-group-label">{t('zoteroGroup')}</div>
|
||||
</div>
|
||||
|
||||
<div className="ribbon-sep" />
|
||||
|
||||
<div className="ribbon-group">
|
||||
<div className="ribbon-group-items">
|
||||
<button
|
||||
|
||||
@@ -23,6 +23,7 @@ export interface DocDirtyState {
|
||||
inksDirty: boolean
|
||||
notesDirty: boolean
|
||||
sourcesDirty: boolean
|
||||
zoteroDocumentDataDirty: boolean
|
||||
themeFontsDirty: boolean
|
||||
themeColorsDirty: boolean
|
||||
commentsDirty: boolean
|
||||
@@ -52,6 +53,7 @@ export function isDocDirty(s: DocDirtyState): boolean {
|
||||
s.inksDirty ||
|
||||
s.notesDirty ||
|
||||
s.sourcesDirty ||
|
||||
s.zoteroDocumentDataDirty ||
|
||||
s.themeFontsDirty ||
|
||||
s.themeColorsDirty ||
|
||||
s.commentsDirty ||
|
||||
|
||||
@@ -1266,6 +1266,8 @@ function markLeadRule(nodes: PmNode[]): void {
|
||||
if (nodes.slice(1).some((n) => !isRuleNode(n))) first.attrs = { ...first.attrs, leadRule: true }
|
||||
}
|
||||
|
||||
let nextZoteroFieldId = 1
|
||||
|
||||
function runMarks(run: Run): PmMark[] {
|
||||
const marks: PmMark[] = []
|
||||
if (run.bold) marks.push({ type: 'bold' })
|
||||
@@ -1278,11 +1280,27 @@ function runMarks(run: Run): PmMark[] {
|
||||
attrs: { href: run.link.href, rId: run.link.rId ?? null, tooltip: run.link.tooltip ?? null },
|
||||
})
|
||||
if (run.refField !== undefined) marks.push({ type: 'refField', attrs: { name: run.refField } })
|
||||
if (run.instrField !== undefined)
|
||||
if (run.instrField !== undefined) {
|
||||
const isZotero = /^\s*(?:ADDIN\s+)?(?:ZOTERO_|CSL_)/i.test(run.instrField)
|
||||
let fieldId: number | null = null
|
||||
if (isZotero) {
|
||||
if (Number.isSafeInteger(run.zoteroFieldId) && Number(run.zoteroFieldId) > 0) {
|
||||
fieldId = Number(run.zoteroFieldId)
|
||||
nextZoteroFieldId = Math.max(nextZoteroFieldId, fieldId + 1)
|
||||
} else {
|
||||
fieldId = nextZoteroFieldId++
|
||||
}
|
||||
}
|
||||
marks.push({
|
||||
type: 'instrField',
|
||||
attrs: { instr: run.instrField, beginXml: run.fldBeginXml ?? null },
|
||||
attrs: {
|
||||
instr: run.instrField,
|
||||
beginXml: run.fldBeginXml ?? null,
|
||||
fieldId,
|
||||
fieldPart: run.zoteroFieldPart ?? null,
|
||||
},
|
||||
})
|
||||
}
|
||||
if (run.commentIds?.length)
|
||||
marks.push({ type: 'comment', attrs: { ids: run.commentIds.join(' ') } })
|
||||
if (run.ins) {
|
||||
@@ -2607,6 +2625,19 @@ function runFromMarks(text: string, marks: PmMark[]): Run {
|
||||
} else if (mark.type === 'instrField') {
|
||||
run.instrField = String(mark.attrs?.instr ?? '')
|
||||
if (mark.attrs?.beginXml) run.fldBeginXml = String(mark.attrs.beginXml)
|
||||
if (/^\s*(?:ADDIN\s+)?(?:ZOTERO_|CSL_)/i.test(run.instrField)) {
|
||||
const fieldId = Number(mark.attrs?.fieldId)
|
||||
if (Number.isSafeInteger(fieldId) && fieldId > 0) run.zoteroFieldId = fieldId
|
||||
const fieldPart = mark.attrs?.fieldPart
|
||||
if (
|
||||
fieldPart === 'single' ||
|
||||
fieldPart === 'begin' ||
|
||||
fieldPart === 'inside' ||
|
||||
fieldPart === 'end'
|
||||
) {
|
||||
run.zoteroFieldPart = fieldPart
|
||||
}
|
||||
}
|
||||
} else if (mark.type === 'comment') {
|
||||
const ids = String(mark.attrs?.ids ?? '')
|
||||
.split(' ')
|
||||
|
||||
@@ -338,18 +338,28 @@ export const InstrFieldMark = Mark.create({
|
||||
inclusive: false,
|
||||
addAttributes() {
|
||||
// beginXml: preserved w:fldChar begin run (form-field ffData) for verbatim write-back
|
||||
return { instr: { default: '' }, beginXml: { default: null } }
|
||||
// fieldId/fieldPart are runtime-only and keep cross-paragraph Zotero fields addressable.
|
||||
return {
|
||||
instr: { default: '' },
|
||||
beginXml: { default: null },
|
||||
fieldId: { default: null, rendered: false },
|
||||
fieldPart: { default: null, rendered: false },
|
||||
}
|
||||
},
|
||||
parseHTML() {
|
||||
return [{ tag: 'span[data-instr-field]' }]
|
||||
},
|
||||
renderHTML({ mark }) {
|
||||
const instruction = String(mark.attrs.instr)
|
||||
const zoteroClass = /^\s*(?:ADDIN\s+)?(?:ZOTERO_|CSL_)/i.test(instruction)
|
||||
? ' zotero-ref-field'
|
||||
: ''
|
||||
return [
|
||||
'span',
|
||||
{
|
||||
'data-instr-field': String(mark.attrs.instr),
|
||||
class: 'doc-ref-field',
|
||||
title: t('editorFieldHint', { instr: String(mark.attrs.instr) }),
|
||||
'data-instr-field': instruction,
|
||||
class: `doc-ref-field${zoteroClass}`,
|
||||
title: t('editorFieldHint', { instr: instruction }),
|
||||
},
|
||||
0,
|
||||
]
|
||||
|
||||
@@ -177,6 +177,10 @@ export interface FileActionContext {
|
||||
sourcesDirty: boolean
|
||||
setSources: (value: SourceInfo[]) => void
|
||||
setSourcesDirty: (dirty: boolean) => void
|
||||
zoteroDocumentData: string
|
||||
zoteroDocumentDataDirty: boolean
|
||||
setZoteroDocumentData: (value: string) => void
|
||||
setZoteroDocumentDataDirty: (dirty: boolean) => void
|
||||
themeFonts: ThemeFonts | null
|
||||
themeFontsDirty: boolean
|
||||
themeColors: ThemeColors | null
|
||||
@@ -396,6 +400,8 @@ export async function loadFile(
|
||||
ctx.setNotesDirty(false)
|
||||
ctx.setSources(parsed.sources)
|
||||
ctx.setSourcesDirty(false)
|
||||
ctx.setZoteroDocumentData(parsed.zoteroDocumentData)
|
||||
ctx.setZoteroDocumentDataDirty(false)
|
||||
ctx.setThemeFonts(parsed.themeFonts ?? null)
|
||||
ctx.setThemeFontsDirty(false)
|
||||
ctx.setThemeColors(parsed.themeColors ?? null)
|
||||
@@ -486,6 +492,8 @@ export async function newFile(ctx: FileActionContext): Promise<boolean | undefin
|
||||
ctx.setNotesDirty(false)
|
||||
ctx.setSources([])
|
||||
ctx.setSourcesDirty(false)
|
||||
ctx.setZoteroDocumentData(parsed.zoteroDocumentData)
|
||||
ctx.setZoteroDocumentDataDirty(false)
|
||||
ctx.setThemeFonts(parsed.themeFonts ?? null)
|
||||
ctx.setThemeFontsDirty(false)
|
||||
ctx.setThemeColors(parsed.themeColors ?? null)
|
||||
@@ -665,6 +673,7 @@ export async function buildDocBytes(ctx: FileActionContext): Promise<Uint8Array
|
||||
footnotes: ctx.notesDirty ? ctx.footnotes : undefined,
|
||||
endnotes: ctx.notesDirty ? ctx.endnotes : undefined,
|
||||
sources: ctx.sourcesDirty ? ctx.sources : undefined,
|
||||
zoteroDocumentData: ctx.zoteroDocumentDataDirty ? ctx.zoteroDocumentData : undefined,
|
||||
themeFonts: ctx.themeFontsDirty && ctx.themeFonts ? ctx.themeFonts : undefined,
|
||||
themeColors: ctx.themeColorsDirty && ctx.themeColors ? ctx.themeColors : undefined,
|
||||
})
|
||||
@@ -994,6 +1003,8 @@ async function saveOnce(
|
||||
ctx.setNotesDirty(false)
|
||||
ctx.setSources(reparsed.sources)
|
||||
ctx.setSourcesDirty(false)
|
||||
ctx.setZoteroDocumentData(reparsed.zoteroDocumentData)
|
||||
ctx.setZoteroDocumentDataDirty(false)
|
||||
ctx.setThemeFonts(reparsed.themeFonts ?? null)
|
||||
ctx.setThemeFontsDirty(false)
|
||||
ctx.setThemeColors(reparsed.themeColors ?? null)
|
||||
|
||||
@@ -0,0 +1,317 @@
|
||||
import { defineStrings } from '@genoffice/i18n'
|
||||
|
||||
/** Strings for the Zotero integration in the References tab. */
|
||||
export const zoteroStrings = defineStrings({
|
||||
zh: {
|
||||
zoteroCitation: 'Zotero 引文',
|
||||
zoteroCitationTip: '使用 Zotero 添加引文;光标在现有引文中时可编辑',
|
||||
zoteroBibliography: 'Zotero 文献表',
|
||||
zoteroBibliographyTip: '使用 Zotero 添加或编辑参考文献表',
|
||||
zoteroRefresh: '刷新',
|
||||
zoteroRefreshTip: '刷新全部 Zotero 引文和参考文献表',
|
||||
zoteroDocumentSettings: '文档设置',
|
||||
zoteroDocumentSettingsTip: 'Zotero 文档设置',
|
||||
zoteroDocumentPreferences: '文档首选项',
|
||||
zoteroRemoveCodes: '移除域代码',
|
||||
zoteroConnectionError: '无法连接 Zotero。请先启动 Zotero,并保持桌面程序运行。',
|
||||
zoteroOperationError: 'Zotero 操作失败。',
|
||||
zoteroGroup: 'Zotero',
|
||||
},
|
||||
en: {
|
||||
zoteroCitation: 'Zotero Citation',
|
||||
zoteroCitationTip: 'Add a citation with Zotero; place the cursor in a citation to edit it',
|
||||
zoteroBibliography: 'Zotero Bibliography',
|
||||
zoteroBibliographyTip: 'Add or edit the bibliography with Zotero',
|
||||
zoteroRefresh: 'Refresh',
|
||||
zoteroRefreshTip: 'Refresh all Zotero citations and bibliographies',
|
||||
zoteroDocumentSettings: 'Document Settings',
|
||||
zoteroDocumentSettingsTip: 'Zotero document settings',
|
||||
zoteroDocumentPreferences: 'Document Preferences',
|
||||
zoteroRemoveCodes: 'Remove Field Codes',
|
||||
zoteroConnectionError: 'Unable to connect to Zotero. Start Zotero and keep it running.',
|
||||
zoteroOperationError: 'The Zotero operation failed.',
|
||||
zoteroGroup: 'Zotero',
|
||||
},
|
||||
ja: {
|
||||
zoteroCitation: 'Zotero 引用',
|
||||
zoteroCitationTip: 'Zotero で引用を追加します。既存の引用内にカーソルを置くと編集できます',
|
||||
zoteroBibliography: 'Zotero 文献目録',
|
||||
zoteroBibliographyTip: 'Zotero で文献目録を追加または編集します',
|
||||
zoteroRefresh: '更新',
|
||||
zoteroRefreshTip: 'すべての Zotero 引用と文献目録を更新します',
|
||||
zoteroDocumentSettings: '文書設定',
|
||||
zoteroDocumentSettingsTip: 'Zotero 文書設定',
|
||||
zoteroDocumentPreferences: '文書の環境設定',
|
||||
zoteroRemoveCodes: 'フィールドコードを削除',
|
||||
zoteroConnectionError: 'Zotero に接続できません。Zotero を起動したままにしてください。',
|
||||
zoteroOperationError: 'Zotero の操作に失敗しました。',
|
||||
zoteroGroup: 'Zotero',
|
||||
},
|
||||
ko: {
|
||||
zoteroCitation: 'Zotero 인용',
|
||||
zoteroCitationTip: 'Zotero로 인용을 추가합니다. 기존 인용 안에 커서를 두면 편집할 수 있습니다',
|
||||
zoteroBibliography: 'Zotero 참고 문헌',
|
||||
zoteroBibliographyTip: 'Zotero로 참고 문헌을 추가하거나 편집합니다',
|
||||
zoteroRefresh: '새로 고침',
|
||||
zoteroRefreshTip: '모든 Zotero 인용과 참고 문헌을 새로 고칩니다',
|
||||
zoteroDocumentSettings: '문서 설정',
|
||||
zoteroDocumentSettingsTip: 'Zotero 문서 설정',
|
||||
zoteroDocumentPreferences: '문서 환경설정',
|
||||
zoteroRemoveCodes: '필드 코드 제거',
|
||||
zoteroConnectionError: 'Zotero에 연결할 수 없습니다. Zotero를 실행한 상태로 유지하세요.',
|
||||
zoteroOperationError: 'Zotero 작업에 실패했습니다.',
|
||||
zoteroGroup: 'Zotero',
|
||||
},
|
||||
fr: {
|
||||
zoteroCitation: 'Citation Zotero',
|
||||
zoteroCitationTip:
|
||||
'Ajouter une citation avec Zotero ; placer le curseur dedans pour la modifier',
|
||||
zoteroBibliography: 'Bibliographie Zotero',
|
||||
zoteroBibliographyTip: 'Ajouter ou modifier la bibliographie avec Zotero',
|
||||
zoteroRefresh: 'Actualiser',
|
||||
zoteroRefreshTip: 'Actualiser toutes les citations et bibliographies Zotero',
|
||||
zoteroDocumentSettings: 'Paramètres du document',
|
||||
zoteroDocumentSettingsTip: 'Paramètres du document Zotero',
|
||||
zoteroDocumentPreferences: 'Préférences du document',
|
||||
zoteroRemoveCodes: 'Supprimer les codes de champ',
|
||||
zoteroConnectionError:
|
||||
'Impossible de se connecter à Zotero. Démarrez Zotero et laissez-le ouvert.',
|
||||
zoteroOperationError: "L'opération Zotero a échoué.",
|
||||
zoteroGroup: 'Zotero',
|
||||
},
|
||||
de: {
|
||||
zoteroCitation: 'Zotero-Zitat',
|
||||
zoteroCitationTip: 'Zitat mit Zotero einfügen; zum Bearbeiten den Cursor in ein Zitat setzen',
|
||||
zoteroBibliography: 'Zotero-Literaturverzeichnis',
|
||||
zoteroBibliographyTip: 'Literaturverzeichnis mit Zotero einfügen oder bearbeiten',
|
||||
zoteroRefresh: 'Aktualisieren',
|
||||
zoteroRefreshTip: 'Alle Zotero-Zitate und Literaturverzeichnisse aktualisieren',
|
||||
zoteroDocumentSettings: 'Dokumenteinstellungen',
|
||||
zoteroDocumentSettingsTip: 'Zotero-Dokumenteinstellungen',
|
||||
zoteroDocumentPreferences: 'Dokumenteinstellungen',
|
||||
zoteroRemoveCodes: 'Feldcodes entfernen',
|
||||
zoteroConnectionError:
|
||||
'Verbindung mit Zotero nicht möglich. Starten Sie Zotero und lassen Sie es geöffnet.',
|
||||
zoteroOperationError: 'Der Zotero-Vorgang ist fehlgeschlagen.',
|
||||
zoteroGroup: 'Zotero',
|
||||
},
|
||||
es: {
|
||||
zoteroCitation: 'Cita de Zotero',
|
||||
zoteroCitationTip: 'Añadir una cita con Zotero; coloque el cursor en una cita para editarla',
|
||||
zoteroBibliography: 'Bibliografía de Zotero',
|
||||
zoteroBibliographyTip: 'Añadir o editar la bibliografía con Zotero',
|
||||
zoteroRefresh: 'Actualizar',
|
||||
zoteroRefreshTip: 'Actualizar todas las citas y bibliografías de Zotero',
|
||||
zoteroDocumentSettings: 'Configuración del documento',
|
||||
zoteroDocumentSettingsTip: 'Configuración del documento de Zotero',
|
||||
zoteroDocumentPreferences: 'Preferencias del documento',
|
||||
zoteroRemoveCodes: 'Eliminar códigos de campo',
|
||||
zoteroConnectionError: 'No se puede conectar con Zotero. Inicie Zotero y manténgalo abierto.',
|
||||
zoteroOperationError: 'La operación de Zotero ha fallado.',
|
||||
zoteroGroup: 'Zotero',
|
||||
},
|
||||
th: {
|
||||
zoteroCitation: 'การอ้างอิง Zotero',
|
||||
zoteroCitationTip: 'เพิ่มการอ้างอิงด้วย Zotero วางเคอร์เซอร์ในการอ้างอิงเพื่อแก้ไข',
|
||||
zoteroBibliography: 'บรรณานุกรม Zotero',
|
||||
zoteroBibliographyTip: 'เพิ่มหรือแก้ไขบรรณานุกรมด้วย Zotero',
|
||||
zoteroRefresh: 'รีเฟรช',
|
||||
zoteroRefreshTip: 'รีเฟรชการอ้างอิงและบรรณานุกรม Zotero ทั้งหมด',
|
||||
zoteroDocumentSettings: 'การตั้งค่าเอกสาร',
|
||||
zoteroDocumentSettingsTip: 'การตั้งค่าเอกสาร Zotero',
|
||||
zoteroDocumentPreferences: 'การกำหนดลักษณะเอกสาร',
|
||||
zoteroRemoveCodes: 'ลบรหัสเขตข้อมูล',
|
||||
zoteroConnectionError: 'ไม่สามารถเชื่อมต่อกับ Zotero ได้ โปรดเปิด Zotero ทิ้งไว้',
|
||||
zoteroOperationError: 'การดำเนินการ Zotero ล้มเหลว',
|
||||
zoteroGroup: 'Zotero',
|
||||
},
|
||||
id: {
|
||||
zoteroCitation: 'Kutipan Zotero',
|
||||
zoteroCitationTip:
|
||||
'Tambahkan kutipan dengan Zotero; letakkan kursor di kutipan untuk mengeditnya',
|
||||
zoteroBibliography: 'Bibliografi Zotero',
|
||||
zoteroBibliographyTip: 'Tambahkan atau edit bibliografi dengan Zotero',
|
||||
zoteroRefresh: 'Segarkan',
|
||||
zoteroRefreshTip: 'Segarkan semua kutipan dan bibliografi Zotero',
|
||||
zoteroDocumentSettings: 'Pengaturan Dokumen',
|
||||
zoteroDocumentSettingsTip: 'Pengaturan dokumen Zotero',
|
||||
zoteroDocumentPreferences: 'Preferensi Dokumen',
|
||||
zoteroRemoveCodes: 'Hapus Kode Bidang',
|
||||
zoteroConnectionError:
|
||||
'Tidak dapat terhubung ke Zotero. Jalankan Zotero dan biarkan tetap terbuka.',
|
||||
zoteroOperationError: 'Operasi Zotero gagal.',
|
||||
zoteroGroup: 'Zotero',
|
||||
},
|
||||
ru: {
|
||||
zoteroCitation: 'Цитата Zotero',
|
||||
zoteroCitationTip: 'Добавить цитату через Zotero; для изменения поместите курсор внутрь цитаты',
|
||||
zoteroBibliography: 'Библиография Zotero',
|
||||
zoteroBibliographyTip: 'Добавить или изменить библиографию через Zotero',
|
||||
zoteroRefresh: 'Обновить',
|
||||
zoteroRefreshTip: 'Обновить все цитаты и библиографии Zotero',
|
||||
zoteroDocumentSettings: 'Параметры документа',
|
||||
zoteroDocumentSettingsTip: 'Параметры документа Zotero',
|
||||
zoteroDocumentPreferences: 'Настройки документа',
|
||||
zoteroRemoveCodes: 'Удалить коды полей',
|
||||
zoteroConnectionError:
|
||||
'Не удалось подключиться к Zotero. Запустите Zotero и оставьте его открытым.',
|
||||
zoteroOperationError: 'Операция Zotero завершилась с ошибкой.',
|
||||
zoteroGroup: 'Zotero',
|
||||
},
|
||||
ar: {
|
||||
zoteroCitation: 'اقتباس Zotero',
|
||||
zoteroCitationTip: 'أضف اقتباسًا باستخدام Zotero؛ ضع المؤشر داخل اقتباس لتعديله',
|
||||
zoteroBibliography: 'مراجع Zotero',
|
||||
zoteroBibliographyTip: 'أضف قائمة المراجع أو عدّلها باستخدام Zotero',
|
||||
zoteroRefresh: 'تحديث',
|
||||
zoteroRefreshTip: 'تحديث جميع اقتباسات ومراجع Zotero',
|
||||
zoteroDocumentSettings: 'إعدادات المستند',
|
||||
zoteroDocumentSettingsTip: 'إعدادات مستند Zotero',
|
||||
zoteroDocumentPreferences: 'تفضيلات المستند',
|
||||
zoteroRemoveCodes: 'إزالة رموز الحقول',
|
||||
zoteroConnectionError: 'تعذر الاتصال بـ Zotero. شغّل Zotero واتركه مفتوحًا.',
|
||||
zoteroOperationError: 'فشلت عملية Zotero.',
|
||||
zoteroGroup: 'Zotero',
|
||||
},
|
||||
pt: {
|
||||
zoteroCitation: 'Citação do Zotero',
|
||||
zoteroCitationTip: 'Adicione uma citação com o Zotero; posicione o cursor nela para editar',
|
||||
zoteroBibliography: 'Bibliografia do Zotero',
|
||||
zoteroBibliographyTip: 'Adicione ou edite a bibliografia com o Zotero',
|
||||
zoteroRefresh: 'Atualizar',
|
||||
zoteroRefreshTip: 'Atualizar todas as citações e bibliografias do Zotero',
|
||||
zoteroDocumentSettings: 'Configurações do documento',
|
||||
zoteroDocumentSettingsTip: 'Configurações do documento do Zotero',
|
||||
zoteroDocumentPreferences: 'Preferências do documento',
|
||||
zoteroRemoveCodes: 'Remover códigos de campo',
|
||||
zoteroConnectionError:
|
||||
'Não foi possível conectar ao Zotero. Inicie o Zotero e mantenha-o aberto.',
|
||||
zoteroOperationError: 'A operação do Zotero falhou.',
|
||||
zoteroGroup: 'Zotero',
|
||||
},
|
||||
it: {
|
||||
zoteroCitation: 'Citazione Zotero',
|
||||
zoteroCitationTip:
|
||||
'Aggiungi una citazione con Zotero; posiziona il cursore in una citazione per modificarla',
|
||||
zoteroBibliography: 'Bibliografia Zotero',
|
||||
zoteroBibliographyTip: 'Aggiungi o modifica la bibliografia con Zotero',
|
||||
zoteroRefresh: 'Aggiorna',
|
||||
zoteroRefreshTip: 'Aggiorna tutte le citazioni e bibliografie Zotero',
|
||||
zoteroDocumentSettings: 'Impostazioni documento',
|
||||
zoteroDocumentSettingsTip: 'Impostazioni del documento Zotero',
|
||||
zoteroDocumentPreferences: 'Preferenze documento',
|
||||
zoteroRemoveCodes: 'Rimuovi codici di campo',
|
||||
zoteroConnectionError: 'Impossibile connettersi a Zotero. Avvia Zotero e lascialo aperto.',
|
||||
zoteroOperationError: "L'operazione Zotero non è riuscita.",
|
||||
zoteroGroup: 'Zotero',
|
||||
},
|
||||
pl: {
|
||||
zoteroCitation: 'Cytowanie Zotero',
|
||||
zoteroCitationTip: 'Dodaj cytowanie przez Zotero; umieść kursor w cytowaniu, aby je edytować',
|
||||
zoteroBibliography: 'Bibliografia Zotero',
|
||||
zoteroBibliographyTip: 'Dodaj lub edytuj bibliografię przez Zotero',
|
||||
zoteroRefresh: 'Odśwież',
|
||||
zoteroRefreshTip: 'Odśwież wszystkie cytowania i bibliografie Zotero',
|
||||
zoteroDocumentSettings: 'Ustawienia dokumentu',
|
||||
zoteroDocumentSettingsTip: 'Ustawienia dokumentu Zotero',
|
||||
zoteroDocumentPreferences: 'Preferencje dokumentu',
|
||||
zoteroRemoveCodes: 'Usuń kody pól',
|
||||
zoteroConnectionError: 'Nie można połączyć się z Zotero. Uruchom Zotero i pozostaw je otwarte.',
|
||||
zoteroOperationError: 'Operacja Zotero nie powiodła się.',
|
||||
zoteroGroup: 'Zotero',
|
||||
},
|
||||
cs: {
|
||||
zoteroCitation: 'Citace Zotero',
|
||||
zoteroCitationTip: 'Přidat citaci pomocí Zotera; pro úpravu umístěte kurzor do citace',
|
||||
zoteroBibliography: 'Bibliografie Zotero',
|
||||
zoteroBibliographyTip: 'Přidat nebo upravit bibliografii pomocí Zotera',
|
||||
zoteroRefresh: 'Aktualizovat',
|
||||
zoteroRefreshTip: 'Aktualizovat všechny citace a bibliografie Zotero',
|
||||
zoteroDocumentSettings: 'Nastavení dokumentu',
|
||||
zoteroDocumentSettingsTip: 'Nastavení dokumentu Zotero',
|
||||
zoteroDocumentPreferences: 'Předvolby dokumentu',
|
||||
zoteroRemoveCodes: 'Odebrat kódy polí',
|
||||
zoteroConnectionError: 'K Zoteru se nelze připojit. Spusťte Zotero a nechte je otevřené.',
|
||||
zoteroOperationError: 'Operace Zotero se nezdařila.',
|
||||
zoteroGroup: 'Zotero',
|
||||
},
|
||||
nl: {
|
||||
zoteroCitation: 'Zotero-citatie',
|
||||
zoteroCitationTip:
|
||||
'Voeg een citatie toe met Zotero; plaats de cursor in een citatie om die te bewerken',
|
||||
zoteroBibliography: 'Zotero-bibliografie',
|
||||
zoteroBibliographyTip: 'Voeg de bibliografie toe of bewerk deze met Zotero',
|
||||
zoteroRefresh: 'Vernieuwen',
|
||||
zoteroRefreshTip: 'Vernieuw alle Zotero-citaties en bibliografieën',
|
||||
zoteroDocumentSettings: 'Documentinstellingen',
|
||||
zoteroDocumentSettingsTip: 'Zotero-documentinstellingen',
|
||||
zoteroDocumentPreferences: 'Documentvoorkeuren',
|
||||
zoteroRemoveCodes: 'Veldcodes verwijderen',
|
||||
zoteroConnectionError:
|
||||
'Kan geen verbinding maken met Zotero. Start Zotero en laat het geopend.',
|
||||
zoteroOperationError: 'De Zotero-bewerking is mislukt.',
|
||||
zoteroGroup: 'Zotero',
|
||||
},
|
||||
ms: {
|
||||
zoteroCitation: 'Petikan Zotero',
|
||||
zoteroCitationTip:
|
||||
'Tambah petikan dengan Zotero; letakkan kursor dalam petikan untuk mengeditnya',
|
||||
zoteroBibliography: 'Bibliografi Zotero',
|
||||
zoteroBibliographyTip: 'Tambah atau edit bibliografi dengan Zotero',
|
||||
zoteroRefresh: 'Segar semula',
|
||||
zoteroRefreshTip: 'Segar semula semua petikan dan bibliografi Zotero',
|
||||
zoteroDocumentSettings: 'Tetapan Dokumen',
|
||||
zoteroDocumentSettingsTip: 'Tetapan dokumen Zotero',
|
||||
zoteroDocumentPreferences: 'Keutamaan Dokumen',
|
||||
zoteroRemoveCodes: 'Buang Kod Medan',
|
||||
zoteroConnectionError:
|
||||
'Tidak dapat menyambung ke Zotero. Mulakan Zotero dan biarkannya terbuka.',
|
||||
zoteroOperationError: 'Operasi Zotero gagal.',
|
||||
zoteroGroup: 'Zotero',
|
||||
},
|
||||
he: {
|
||||
zoteroCitation: 'ציטוט Zotero',
|
||||
zoteroCitationTip: 'הוספת ציטוט באמצעות Zotero; יש למקם את הסמן בציטוט כדי לערוך אותו',
|
||||
zoteroBibliography: 'ביבליוגרפיה של Zotero',
|
||||
zoteroBibliographyTip: 'הוספה או עריכה של הביבליוגרפיה באמצעות Zotero',
|
||||
zoteroRefresh: 'רענון',
|
||||
zoteroRefreshTip: 'רענון כל הציטוטים והביבליוגרפיות של Zotero',
|
||||
zoteroDocumentSettings: 'הגדרות מסמך',
|
||||
zoteroDocumentSettingsTip: 'הגדרות מסמך Zotero',
|
||||
zoteroDocumentPreferences: 'העדפות מסמך',
|
||||
zoteroRemoveCodes: 'הסרת קודי שדה',
|
||||
zoteroConnectionError: 'לא ניתן להתחבר ל-Zotero. יש להפעיל את Zotero ולהשאיר אותו פתוח.',
|
||||
zoteroOperationError: 'פעולת Zotero נכשלה.',
|
||||
zoteroGroup: 'Zotero',
|
||||
},
|
||||
hi: {
|
||||
zoteroCitation: 'Zotero उद्धरण',
|
||||
zoteroCitationTip: 'Zotero से उद्धरण जोड़ें; संपादित करने के लिए कर्सर को उद्धरण में रखें',
|
||||
zoteroBibliography: 'Zotero ग्रंथ सूची',
|
||||
zoteroBibliographyTip: 'Zotero से ग्रंथ सूची जोड़ें या संपादित करें',
|
||||
zoteroRefresh: 'रीफ़्रेश करें',
|
||||
zoteroRefreshTip: 'सभी Zotero उद्धरण और ग्रंथ सूचियाँ रीफ़्रेश करें',
|
||||
zoteroDocumentSettings: 'दस्तावेज़ सेटिंग',
|
||||
zoteroDocumentSettingsTip: 'Zotero दस्तावेज़ सेटिंग',
|
||||
zoteroDocumentPreferences: 'दस्तावेज़ प्राथमिकताएँ',
|
||||
zoteroRemoveCodes: 'फ़ील्ड कोड हटाएँ',
|
||||
zoteroConnectionError: 'Zotero से कनेक्ट नहीं हो सका। Zotero शुरू करें और उसे खुला रखें।',
|
||||
zoteroOperationError: 'Zotero कार्रवाई विफल रही।',
|
||||
zoteroGroup: 'Zotero',
|
||||
},
|
||||
'zh-TW': {
|
||||
zoteroCitation: 'Zotero 引文',
|
||||
zoteroCitationTip: '使用 Zotero 新增引文;游標位於現有引文中時可編輯',
|
||||
zoteroBibliography: 'Zotero 參考文獻',
|
||||
zoteroBibliographyTip: '使用 Zotero 新增或編輯參考文獻',
|
||||
zoteroRefresh: '重新整理',
|
||||
zoteroRefreshTip: '重新整理所有 Zotero 引文和參考文獻',
|
||||
zoteroDocumentSettings: '文件設定',
|
||||
zoteroDocumentSettingsTip: 'Zotero 文件設定',
|
||||
zoteroDocumentPreferences: '文件偏好設定',
|
||||
zoteroRemoveCodes: '移除欄位代碼',
|
||||
zoteroConnectionError: '無法連線至 Zotero。請先啟動 Zotero,並保持桌面程式執行。',
|
||||
zoteroOperationError: 'Zotero 操作失敗。',
|
||||
zoteroGroup: 'Zotero',
|
||||
},
|
||||
})
|
||||
@@ -3,6 +3,7 @@ import { appStrings } from './strings-app'
|
||||
import { editorStrings } from './strings-editor'
|
||||
import { ribbonStrings } from './strings-ribbon'
|
||||
import { tableStrings } from './strings-table'
|
||||
import { zoteroStrings } from './strings-zotero'
|
||||
|
||||
export const strings = {
|
||||
zh: {
|
||||
@@ -11,6 +12,7 @@ export const strings = {
|
||||
...tableStrings.zh,
|
||||
...editorStrings.zh,
|
||||
...aiStrings.zh,
|
||||
...zoteroStrings.zh,
|
||||
},
|
||||
en: {
|
||||
...appStrings.en,
|
||||
@@ -18,6 +20,7 @@ export const strings = {
|
||||
...tableStrings.en,
|
||||
...editorStrings.en,
|
||||
...aiStrings.en,
|
||||
...zoteroStrings.en,
|
||||
},
|
||||
ja: {
|
||||
...appStrings.ja,
|
||||
@@ -25,6 +28,7 @@ export const strings = {
|
||||
...tableStrings.ja,
|
||||
...editorStrings.ja,
|
||||
...aiStrings.ja,
|
||||
...zoteroStrings.ja,
|
||||
},
|
||||
ko: {
|
||||
...appStrings.ko,
|
||||
@@ -32,6 +36,7 @@ export const strings = {
|
||||
...tableStrings.ko,
|
||||
...editorStrings.ko,
|
||||
...aiStrings.ko,
|
||||
...zoteroStrings.ko,
|
||||
},
|
||||
fr: {
|
||||
...appStrings.fr,
|
||||
@@ -39,6 +44,7 @@ export const strings = {
|
||||
...tableStrings.fr,
|
||||
...editorStrings.fr,
|
||||
...aiStrings.fr,
|
||||
...zoteroStrings.fr,
|
||||
},
|
||||
de: {
|
||||
...appStrings.de,
|
||||
@@ -46,6 +52,7 @@ export const strings = {
|
||||
...tableStrings.de,
|
||||
...editorStrings.de,
|
||||
...aiStrings.de,
|
||||
...zoteroStrings.de,
|
||||
},
|
||||
es: {
|
||||
...appStrings.es,
|
||||
@@ -53,6 +60,7 @@ export const strings = {
|
||||
...tableStrings.es,
|
||||
...editorStrings.es,
|
||||
...aiStrings.es,
|
||||
...zoteroStrings.es,
|
||||
},
|
||||
th: {
|
||||
...appStrings.th,
|
||||
@@ -60,6 +68,7 @@ export const strings = {
|
||||
...tableStrings.th,
|
||||
...editorStrings.th,
|
||||
...aiStrings.th,
|
||||
...zoteroStrings.th,
|
||||
},
|
||||
id: {
|
||||
...appStrings.id,
|
||||
@@ -67,6 +76,7 @@ export const strings = {
|
||||
...tableStrings.id,
|
||||
...editorStrings.id,
|
||||
...aiStrings.id,
|
||||
...zoteroStrings.id,
|
||||
},
|
||||
ru: {
|
||||
...appStrings.ru,
|
||||
@@ -74,6 +84,7 @@ export const strings = {
|
||||
...tableStrings.ru,
|
||||
...editorStrings.ru,
|
||||
...aiStrings.ru,
|
||||
...zoteroStrings.ru,
|
||||
},
|
||||
ar: {
|
||||
...appStrings.ar,
|
||||
@@ -81,6 +92,7 @@ export const strings = {
|
||||
...tableStrings.ar,
|
||||
...editorStrings.ar,
|
||||
...aiStrings.ar,
|
||||
...zoteroStrings.ar,
|
||||
},
|
||||
pt: {
|
||||
...appStrings.pt,
|
||||
@@ -88,6 +100,7 @@ export const strings = {
|
||||
...tableStrings.pt,
|
||||
...editorStrings.pt,
|
||||
...aiStrings.pt,
|
||||
...zoteroStrings.pt,
|
||||
},
|
||||
it: {
|
||||
...appStrings.it,
|
||||
@@ -95,6 +108,7 @@ export const strings = {
|
||||
...tableStrings.it,
|
||||
...editorStrings.it,
|
||||
...aiStrings.it,
|
||||
...zoteroStrings.it,
|
||||
},
|
||||
pl: {
|
||||
...appStrings.pl,
|
||||
@@ -102,6 +116,7 @@ export const strings = {
|
||||
...tableStrings.pl,
|
||||
...editorStrings.pl,
|
||||
...aiStrings.pl,
|
||||
...zoteroStrings.pl,
|
||||
},
|
||||
cs: {
|
||||
...appStrings.cs,
|
||||
@@ -109,6 +124,7 @@ export const strings = {
|
||||
...tableStrings.cs,
|
||||
...editorStrings.cs,
|
||||
...aiStrings.cs,
|
||||
...zoteroStrings.cs,
|
||||
},
|
||||
nl: {
|
||||
...appStrings.nl,
|
||||
@@ -116,6 +132,7 @@ export const strings = {
|
||||
...tableStrings.nl,
|
||||
...editorStrings.nl,
|
||||
...aiStrings.nl,
|
||||
...zoteroStrings.nl,
|
||||
},
|
||||
ms: {
|
||||
...appStrings.ms,
|
||||
@@ -123,6 +140,7 @@ export const strings = {
|
||||
...tableStrings.ms,
|
||||
...editorStrings.ms,
|
||||
...aiStrings.ms,
|
||||
...zoteroStrings.ms,
|
||||
},
|
||||
he: {
|
||||
...appStrings.he,
|
||||
@@ -130,6 +148,7 @@ export const strings = {
|
||||
...tableStrings.he,
|
||||
...editorStrings.he,
|
||||
...aiStrings.he,
|
||||
...zoteroStrings.he,
|
||||
},
|
||||
hi: {
|
||||
...appStrings.hi,
|
||||
@@ -137,6 +156,7 @@ export const strings = {
|
||||
...tableStrings.hi,
|
||||
...editorStrings.hi,
|
||||
...aiStrings.hi,
|
||||
...zoteroStrings.hi,
|
||||
},
|
||||
'zh-TW': {
|
||||
...appStrings['zh-TW'],
|
||||
@@ -144,5 +164,6 @@ export const strings = {
|
||||
...tableStrings['zh-TW'],
|
||||
...editorStrings['zh-TW'],
|
||||
...aiStrings['zh-TW'],
|
||||
...zoteroStrings['zh-TW'],
|
||||
},
|
||||
}
|
||||
|
||||
@@ -5772,6 +5772,10 @@ body.docs-crop-active .doc-protected[data-doc-protected='image'] .doc-img-wrap {
|
||||
border-radius: 2px;
|
||||
}
|
||||
|
||||
.zotero-ref-field {
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
|
||||
.doc-ref-field:hover {
|
||||
background: var(--docs-paper-field-bg);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,387 @@
|
||||
import type { Editor } from '@tiptap/core'
|
||||
import { TextSelection } from '@tiptap/pm/state'
|
||||
import { Fragment, type Mark, type Node as PmNode } from '@tiptap/pm/model'
|
||||
import type { ZoteroRendererRequest } from '../../shared/ipc'
|
||||
import { parseZoteroRtf, zoteroRtfToText, type ZoteroRtfParagraph, type ZoteroRtfRun } from './rtf'
|
||||
|
||||
const ZOTERO_INSTR_RE = /^\s*(?:ADDIN\s+)?(?:ZOTERO_|CSL_)(?:ITEM|BIBL|TEMP)\b/i
|
||||
|
||||
interface ZoteroFieldRange {
|
||||
id: number
|
||||
from: number
|
||||
to: number
|
||||
blockFrom: number
|
||||
blockTo: number
|
||||
mark: Mark
|
||||
text: string
|
||||
segments: ZoteroFieldSegment[]
|
||||
blocks: ZoteroFieldBlock[]
|
||||
}
|
||||
|
||||
interface ZoteroFieldSegment {
|
||||
from: number
|
||||
to: number
|
||||
blockFrom: number
|
||||
mark: Mark
|
||||
text: string
|
||||
}
|
||||
|
||||
interface ZoteroFieldBlock {
|
||||
from: number
|
||||
to: number
|
||||
node: PmNode
|
||||
}
|
||||
|
||||
export interface ZoteroDocumentDataAccess {
|
||||
get(): string
|
||||
set(value: string): void
|
||||
}
|
||||
|
||||
export function zoteroCodeFromInstruction(instruction: string): string {
|
||||
return instruction
|
||||
.trim()
|
||||
.replace(/^ADDIN\s+ZOTERO_/i, '')
|
||||
.replace(/^ZOTERO_/i, '')
|
||||
.replace(/^CSL_/i, '')
|
||||
.trim()
|
||||
}
|
||||
|
||||
export function zoteroInstructionFromCode(code: string): string {
|
||||
const normalized = zoteroCodeFromInstruction(code)
|
||||
return `ADDIN ZOTERO_${normalized || 'TEMP'}`
|
||||
}
|
||||
|
||||
export class ZoteroDocumentController {
|
||||
private nextFieldId = 1
|
||||
|
||||
constructor(
|
||||
private readonly editor: Editor,
|
||||
private readonly documentData: ZoteroDocumentDataAccess,
|
||||
) {}
|
||||
|
||||
async handle(request: ZoteroRendererRequest): Promise<unknown> {
|
||||
const args = request.args
|
||||
switch (request.command) {
|
||||
case 'Application_getActiveDocument':
|
||||
return [3, 1]
|
||||
case 'Document_activate':
|
||||
this.editor.commands.focus()
|
||||
return null
|
||||
case 'Document_displayAlert':
|
||||
return this.displayAlert(String(args[1] ?? ''), Number(args[3] ?? 0))
|
||||
case 'Document_canInsertField':
|
||||
return this.editor.isEditable
|
||||
case 'Document_cursorInField': {
|
||||
const field = this.fieldAtSelection()
|
||||
return field ? this.fieldDescriptor(field) : null
|
||||
}
|
||||
case 'Document_getDocumentData':
|
||||
return this.documentData.get()
|
||||
case 'Document_setDocumentData':
|
||||
this.documentData.set(String(args[1] ?? ''))
|
||||
return null
|
||||
case 'Document_insertField':
|
||||
return this.insertField(Number(args[2] ?? 0))
|
||||
case 'Document_getFields': {
|
||||
const fields = this.fields()
|
||||
return [
|
||||
fields.map((field) => field.id),
|
||||
fields.map((field) => zoteroCodeFromInstruction(String(field.mark.attrs.instr))),
|
||||
fields.map(() => 0),
|
||||
fields.map((field, index) =>
|
||||
index + 1 < fields.length && field.to === fields[index + 1].from ? 0 : -1,
|
||||
),
|
||||
]
|
||||
}
|
||||
case 'Document_setBibliographyStyle':
|
||||
case 'Document_cleanup':
|
||||
case 'Document_complete':
|
||||
return null
|
||||
case 'Document_insertText':
|
||||
this.editor
|
||||
.chain()
|
||||
.focus()
|
||||
.insertContent(zoteroRtfToText(String(args[1] ?? '')))
|
||||
.run()
|
||||
return null
|
||||
case 'Document_convertPlaceholdersToFields':
|
||||
return [[], [], [], []]
|
||||
case 'Document_exportDocument':
|
||||
throw new Error('Zotero document transfer export is not supported yet')
|
||||
case 'Document_importDocument':
|
||||
throw new Error('Zotero document transfer import is not supported yet')
|
||||
case 'Field_getText':
|
||||
return this.requireField(args[1]).text
|
||||
case 'Field_setText':
|
||||
this.setFieldText(args[1], String(args[2] ?? ''), args[3] === true)
|
||||
return null
|
||||
case 'Field_getCode':
|
||||
return zoteroCodeFromInstruction(String(this.requireField(args[1]).mark.attrs.instr))
|
||||
case 'Field_setCode':
|
||||
this.setFieldCode(args[1], String(args[2] ?? ''))
|
||||
return null
|
||||
case 'Field_select':
|
||||
this.selectField(args[1])
|
||||
return null
|
||||
case 'Field_delete':
|
||||
this.deleteField(args[1])
|
||||
return null
|
||||
case 'Field_removeCode':
|
||||
this.removeFieldCode(args[1])
|
||||
return null
|
||||
case 'Field_convert':
|
||||
if (Number(args[3] ?? 0) !== 0) {
|
||||
throw new Error('Zotero footnote and endnote citations are not supported yet')
|
||||
}
|
||||
return null
|
||||
default:
|
||||
throw new Error(`Unsupported Zotero command: ${request.command}`)
|
||||
}
|
||||
}
|
||||
|
||||
private fields(): ZoteroFieldRange[] {
|
||||
const ranges = new Map<number, ZoteroFieldRange>()
|
||||
this.editor.state.doc.forEach((block, blockOffset) => {
|
||||
block.descendants((node, relativePos) => {
|
||||
if (!node.isText || !node.text) return
|
||||
const mark = node.marks.find(
|
||||
(candidate) =>
|
||||
candidate.type.name === 'instrField' &&
|
||||
ZOTERO_INSTR_RE.test(String(candidate.attrs.instr ?? '')),
|
||||
)
|
||||
if (!mark) return
|
||||
let id = Number(mark.attrs.fieldId)
|
||||
if (!Number.isSafeInteger(id) || id <= 0) id = this.nextFieldId++
|
||||
else this.nextFieldId = Math.max(this.nextFieldId, id + 1)
|
||||
const from = blockOffset + 1 + relativePos
|
||||
const to = from + node.nodeSize
|
||||
const segment: ZoteroFieldSegment = {
|
||||
from,
|
||||
to,
|
||||
blockFrom: blockOffset,
|
||||
mark,
|
||||
text: node.text,
|
||||
}
|
||||
const existing = ranges.get(id)
|
||||
if (existing) {
|
||||
const previous = existing.segments[existing.segments.length - 1]
|
||||
if (previous.blockFrom === blockOffset && previous.to === from) {
|
||||
previous.to = to
|
||||
previous.text += node.text
|
||||
} else {
|
||||
existing.segments.push(segment)
|
||||
}
|
||||
existing.to = to
|
||||
existing.blockTo = blockOffset + block.nodeSize
|
||||
if (!existing.blocks.some((entry) => entry.from === blockOffset)) {
|
||||
existing.blocks.push({
|
||||
from: blockOffset,
|
||||
to: blockOffset + block.nodeSize,
|
||||
node: block,
|
||||
})
|
||||
}
|
||||
} else {
|
||||
ranges.set(id, {
|
||||
id,
|
||||
from,
|
||||
to,
|
||||
blockFrom: blockOffset,
|
||||
blockTo: blockOffset + block.nodeSize,
|
||||
mark,
|
||||
text: '',
|
||||
segments: [segment],
|
||||
blocks: [{ from: blockOffset, to: blockOffset + block.nodeSize, node: block }],
|
||||
})
|
||||
}
|
||||
})
|
||||
})
|
||||
return [...ranges.values()]
|
||||
.sort((a, b) => a.from - b.from)
|
||||
.map((field) => {
|
||||
const textByBlock = field.blocks.map((block) =>
|
||||
field.segments
|
||||
.filter((segment) => segment.blockFrom === block.from)
|
||||
.map((segment) => segment.text)
|
||||
.join(''),
|
||||
)
|
||||
return { ...field, text: textByBlock.join('\n') }
|
||||
})
|
||||
}
|
||||
|
||||
private fieldAtSelection(): ZoteroFieldRange | null {
|
||||
const { from, to } = this.editor.state.selection
|
||||
return (
|
||||
this.fields().find(
|
||||
(field) =>
|
||||
field.segments.some((segment) => from >= segment.from && to <= segment.to) ||
|
||||
(field.blocks.length > 1 && from >= field.blockFrom && to <= field.blockTo),
|
||||
) ?? null
|
||||
)
|
||||
}
|
||||
|
||||
private requireField(value: unknown): ZoteroFieldRange {
|
||||
const id = Number(value)
|
||||
const field = this.fields().find((candidate) => candidate.id === id)
|
||||
if (!field) throw new Error(`Zotero field ${String(value)} no longer exists`)
|
||||
return field
|
||||
}
|
||||
|
||||
private fieldDescriptor(field: ZoteroFieldRange): [number, string, number] {
|
||||
return [field.id, zoteroCodeFromInstruction(String(field.mark.attrs.instr)), 0]
|
||||
}
|
||||
|
||||
private insertField(noteType: number): [number, string, number] {
|
||||
if (noteType !== 0) {
|
||||
throw new Error('Zotero footnote and endnote citations are not supported yet')
|
||||
}
|
||||
const { state, view } = this.editor
|
||||
const type = state.schema.marks.instrField
|
||||
if (!type) throw new Error('This document cannot store Zotero fields')
|
||||
this.fields()
|
||||
const id = this.nextFieldId++
|
||||
const mark = type.create({
|
||||
instr: 'ADDIN ZOTERO_TEMP',
|
||||
beginXml: null,
|
||||
fieldId: id,
|
||||
fieldPart: 'single',
|
||||
})
|
||||
view.dispatch(state.tr.replaceSelectionWith(state.schema.text('{Citation}', [mark]), false))
|
||||
return [id, 'TEMP', 0]
|
||||
}
|
||||
|
||||
private setFieldText(value: unknown, input: string, rich: boolean): void {
|
||||
const field = this.requireField(value)
|
||||
const paragraphs: ZoteroRtfParagraph[] = rich
|
||||
? parseZoteroRtf(input).paragraphs
|
||||
: input.split(/\r?\n/).map((text) => ({ runs: text ? [{ text }] : [] }))
|
||||
const prepared = paragraphs.map((paragraph) => ({
|
||||
...paragraph,
|
||||
runs: paragraph.runs.length > 0 ? paragraph.runs : [{ text: ' ' }],
|
||||
}))
|
||||
const totalRuns = prepared.reduce((total, paragraph) => total + paragraph.runs.length, 0)
|
||||
let runIndex = 0
|
||||
const markFor = (fieldPart: 'single' | 'begin' | 'inside' | 'end') =>
|
||||
field.mark.type.create({ ...field.mark.attrs, fieldId: field.id, fieldPart })
|
||||
const contentFor = (paragraph: (typeof prepared)[number]) =>
|
||||
paragraph.runs.map((run) => {
|
||||
const fieldPart =
|
||||
totalRuns === 1
|
||||
? 'single'
|
||||
: runIndex === 0
|
||||
? 'begin'
|
||||
: runIndex === totalRuns - 1
|
||||
? 'end'
|
||||
: 'inside'
|
||||
runIndex++
|
||||
return this.editor.state.schema.text(run.text, [markFor(fieldPart), ...this.rtfMarks(run)])
|
||||
})
|
||||
let transaction = this.editor.state.tr
|
||||
if (prepared.length === 1 && field.blocks.length === 1) {
|
||||
transaction = transaction.replaceWith(
|
||||
field.from,
|
||||
field.to,
|
||||
Fragment.fromArray(contentFor(prepared[0])),
|
||||
)
|
||||
} else {
|
||||
const nodes = prepared.map((paragraph, index) => {
|
||||
const existing = field.blocks[index]
|
||||
const template = existing ?? field.blocks[0]
|
||||
const attrs = { ...template.node.attrs }
|
||||
if (!existing && 'docxIndex' in attrs) attrs.docxIndex = null
|
||||
for (const key of [
|
||||
'indentLeft',
|
||||
'indentRight',
|
||||
'indentFirstLine',
|
||||
'spaceBefore',
|
||||
'spaceAfter',
|
||||
'align',
|
||||
] as const) {
|
||||
if (paragraph[key] !== undefined) attrs[key] = paragraph[key]
|
||||
}
|
||||
return template.node.type.create(attrs, Fragment.fromArray(contentFor(paragraph)))
|
||||
})
|
||||
transaction = transaction.replaceWith(
|
||||
field.blockFrom,
|
||||
field.blockTo,
|
||||
Fragment.fromArray(nodes),
|
||||
)
|
||||
}
|
||||
this.editor.view.dispatch(transaction)
|
||||
}
|
||||
|
||||
private rtfMarks(run: ZoteroRtfRun): Mark[] {
|
||||
const marks: Mark[] = []
|
||||
const schema = this.editor.state.schema
|
||||
if (run.bold && schema.marks.bold) marks.push(schema.marks.bold.create())
|
||||
if (run.italic && schema.marks.italic) marks.push(schema.marks.italic.create())
|
||||
if (run.underline && schema.marks.underline) marks.push(schema.marks.underline.create())
|
||||
if (run.strike && schema.marks.strike) marks.push(schema.marks.strike.create())
|
||||
if ((run.vertAlign || run.caps || run.sizeHalfPoints) && schema.marks.docTextStyle) {
|
||||
const rawRPr =
|
||||
run.caps === 'small'
|
||||
? '<w:rPr><w:smallCaps/></w:rPr>'
|
||||
: run.caps === 'all'
|
||||
? '<w:rPr><w:caps/></w:rPr>'
|
||||
: null
|
||||
marks.push(
|
||||
schema.marks.docTextStyle.create({
|
||||
vertAlign: run.vertAlign ?? null,
|
||||
caps: run.caps ?? null,
|
||||
sizeHalfPoints: run.sizeHalfPoints ?? null,
|
||||
rawRPr,
|
||||
}),
|
||||
)
|
||||
}
|
||||
return marks
|
||||
}
|
||||
|
||||
private setFieldCode(value: unknown, code: string): void {
|
||||
const field = this.requireField(value)
|
||||
const type = field.mark.type
|
||||
let transaction = this.editor.state.tr
|
||||
for (const segment of field.segments) {
|
||||
transaction = transaction.removeMark(segment.from, segment.to, type).addMark(
|
||||
segment.from,
|
||||
segment.to,
|
||||
type.create({
|
||||
...segment.mark.attrs,
|
||||
instr: zoteroInstructionFromCode(code),
|
||||
fieldId: field.id,
|
||||
}),
|
||||
)
|
||||
}
|
||||
this.editor.view.dispatch(transaction)
|
||||
}
|
||||
|
||||
private selectField(value: unknown): void {
|
||||
const field = this.requireField(value)
|
||||
this.editor.view.dispatch(
|
||||
this.editor.state.tr.setSelection(
|
||||
TextSelection.create(this.editor.state.doc, field.from, field.to),
|
||||
),
|
||||
)
|
||||
this.editor.commands.focus()
|
||||
}
|
||||
|
||||
private deleteField(value: unknown): void {
|
||||
const field = this.requireField(value)
|
||||
const from = field.blocks.length > 1 ? field.blockFrom : field.from
|
||||
const to = field.blocks.length > 1 ? field.blockTo : field.to
|
||||
this.editor.view.dispatch(this.editor.state.tr.delete(from, to))
|
||||
}
|
||||
|
||||
private removeFieldCode(value: unknown): void {
|
||||
const field = this.requireField(value)
|
||||
let transaction = this.editor.state.tr
|
||||
for (const segment of field.segments) {
|
||||
transaction = transaction.removeMark(segment.from, segment.to, field.mark.type)
|
||||
}
|
||||
this.editor.view.dispatch(transaction)
|
||||
}
|
||||
|
||||
private displayAlert(message: string, buttons: number): number {
|
||||
if (buttons > 0) return window.confirm(message) ? 1 : 0
|
||||
window.alert(message)
|
||||
return 0
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,328 @@
|
||||
const CP1252: Record<number, string> = {
|
||||
0x80: '€',
|
||||
0x82: '‚',
|
||||
0x83: 'ƒ',
|
||||
0x84: '„',
|
||||
0x85: '…',
|
||||
0x86: '†',
|
||||
0x87: '‡',
|
||||
0x88: 'ˆ',
|
||||
0x89: '‰',
|
||||
0x8a: 'Š',
|
||||
0x8b: '‹',
|
||||
0x8c: 'Œ',
|
||||
0x8e: 'Ž',
|
||||
0x91: '‘',
|
||||
0x92: '’',
|
||||
0x93: '“',
|
||||
0x94: '”',
|
||||
0x95: '•',
|
||||
0x96: '–',
|
||||
0x97: '—',
|
||||
0x98: '˜',
|
||||
0x99: '™',
|
||||
0x9a: 'š',
|
||||
0x9b: '›',
|
||||
0x9c: 'œ',
|
||||
0x9e: 'ž',
|
||||
0x9f: 'Ÿ',
|
||||
}
|
||||
|
||||
const DESTINATIONS = new Set([
|
||||
'colortbl',
|
||||
'datastore',
|
||||
'filetbl',
|
||||
'fonttbl',
|
||||
'footer',
|
||||
'footerf',
|
||||
'footerl',
|
||||
'footerr',
|
||||
'header',
|
||||
'headerf',
|
||||
'headerl',
|
||||
'headerr',
|
||||
'info',
|
||||
'listoverridetable',
|
||||
'listtable',
|
||||
'pict',
|
||||
'revtbl',
|
||||
'stylesheet',
|
||||
'themedata',
|
||||
])
|
||||
|
||||
const SYMBOLS: Record<string, string> = {
|
||||
bullet: '•',
|
||||
emdash: '—',
|
||||
endash: '–',
|
||||
lquote: '‘',
|
||||
rquote: '’',
|
||||
ldblquote: '“',
|
||||
rdblquote: '”',
|
||||
line: '\n',
|
||||
par: '\n',
|
||||
tab: '\t',
|
||||
}
|
||||
|
||||
interface RtfState {
|
||||
skip: boolean
|
||||
uc: number
|
||||
bold: boolean
|
||||
italic: boolean
|
||||
underline: boolean
|
||||
strike: boolean
|
||||
vertAlign?: 'superscript' | 'subscript'
|
||||
caps?: 'all' | 'small'
|
||||
sizeHalfPoints?: number
|
||||
indentLeft?: number
|
||||
indentRight?: number
|
||||
indentFirstLine?: number
|
||||
spaceBefore?: number
|
||||
spaceAfter?: number
|
||||
align?: 'left' | 'center' | 'right' | 'justify'
|
||||
}
|
||||
|
||||
export interface ZoteroRtfRun {
|
||||
text: string
|
||||
bold?: true
|
||||
italic?: true
|
||||
underline?: true
|
||||
strike?: true
|
||||
vertAlign?: 'superscript' | 'subscript'
|
||||
caps?: 'all' | 'small'
|
||||
sizeHalfPoints?: number
|
||||
}
|
||||
|
||||
export interface ZoteroRtfParagraph {
|
||||
runs: ZoteroRtfRun[]
|
||||
indentLeft?: number
|
||||
indentRight?: number
|
||||
indentFirstLine?: number
|
||||
spaceBefore?: number
|
||||
spaceAfter?: number
|
||||
align?: 'left' | 'center' | 'right' | 'justify'
|
||||
}
|
||||
|
||||
export interface ZoteroRtfDocument {
|
||||
paragraphs: ZoteroRtfParagraph[]
|
||||
}
|
||||
|
||||
function plainDocument(input: string): ZoteroRtfDocument {
|
||||
return {
|
||||
paragraphs: input.split(/\r?\n/).map((text) => ({ runs: text ? [{ text }] : [] })),
|
||||
}
|
||||
}
|
||||
|
||||
/** Parse the formatting subset emitted by Zotero's LibreOffice integration. */
|
||||
export function parseZoteroRtf(input: string): ZoteroRtfDocument {
|
||||
if (!/^\{\\rtf/i.test(input.trim())) return plainDocument(input)
|
||||
const initial: RtfState = {
|
||||
skip: false,
|
||||
uc: 1,
|
||||
bold: false,
|
||||
italic: false,
|
||||
underline: false,
|
||||
strike: false,
|
||||
}
|
||||
const states: RtfState[] = [initial]
|
||||
let state = states[0]
|
||||
const paragraphs: ZoteroRtfParagraph[] = []
|
||||
let paragraph: ZoteroRtfParagraph = { runs: [] }
|
||||
let skipFallback = 0
|
||||
|
||||
const syncParagraphFormat = () => {
|
||||
for (const key of [
|
||||
'indentLeft',
|
||||
'indentRight',
|
||||
'indentFirstLine',
|
||||
'spaceBefore',
|
||||
'spaceAfter',
|
||||
'align',
|
||||
] as const) {
|
||||
const value = state[key]
|
||||
if (value === undefined) delete paragraph[key]
|
||||
else Object.assign(paragraph, { [key]: value })
|
||||
}
|
||||
}
|
||||
const resetParagraph = () => {
|
||||
paragraphs.push(paragraph)
|
||||
paragraph = { runs: [] }
|
||||
syncParagraphFormat()
|
||||
}
|
||||
const append = (text: string) => {
|
||||
if (!text) return
|
||||
const run: ZoteroRtfRun = {
|
||||
text,
|
||||
...(state.bold ? { bold: true } : {}),
|
||||
...(state.italic ? { italic: true } : {}),
|
||||
...(state.underline ? { underline: true } : {}),
|
||||
...(state.strike ? { strike: true } : {}),
|
||||
...(state.vertAlign ? { vertAlign: state.vertAlign } : {}),
|
||||
...(state.caps ? { caps: state.caps } : {}),
|
||||
...(state.sizeHalfPoints ? { sizeHalfPoints: state.sizeHalfPoints } : {}),
|
||||
}
|
||||
const previous = paragraph.runs[paragraph.runs.length - 1]
|
||||
const style = ({ text: _text, ...attrs }: ZoteroRtfRun) => JSON.stringify(attrs)
|
||||
if (previous && style(previous) === style(run)) previous.text += text
|
||||
else paragraph.runs.push(run)
|
||||
}
|
||||
const appendDecoded = (text: string) => {
|
||||
if (skipFallback > 0) skipFallback--
|
||||
else append(text)
|
||||
}
|
||||
|
||||
for (let i = 0; i < input.length; i++) {
|
||||
const char = input[i]
|
||||
if (char === '{') {
|
||||
state = { ...state }
|
||||
states.push(state)
|
||||
continue
|
||||
}
|
||||
if (char === '}') {
|
||||
if (states.length > 1) states.pop()
|
||||
state = states[states.length - 1]
|
||||
continue
|
||||
}
|
||||
if (char !== '\\') {
|
||||
if (!state.skip && char !== '\r' && char !== '\n') {
|
||||
appendDecoded(char)
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
const next = input[++i]
|
||||
if (next === undefined) break
|
||||
if (next === '\\' || next === '{' || next === '}') {
|
||||
if (!state.skip) appendDecoded(next)
|
||||
continue
|
||||
}
|
||||
if (next === '\r' || next === '\n') {
|
||||
// Zotero joins citeproc bibliography entries with a backslash plus CRLF.
|
||||
if (!state.skip) resetParagraph()
|
||||
if (next === '\r' && input[i + 1] === '\n') i++
|
||||
continue
|
||||
}
|
||||
if (next === '*') {
|
||||
state.skip = true
|
||||
continue
|
||||
}
|
||||
if (next === "'") {
|
||||
const hex = input.slice(i + 1, i + 3)
|
||||
if (/^[0-9a-f]{2}$/i.test(hex)) {
|
||||
i += 2
|
||||
if (!state.skip) {
|
||||
const value = parseInt(hex, 16)
|
||||
appendDecoded(CP1252[value] ?? String.fromCharCode(value))
|
||||
}
|
||||
}
|
||||
continue
|
||||
}
|
||||
if (!/[A-Za-z]/.test(next)) {
|
||||
if (!state.skip && next === '~') append('\u00a0')
|
||||
else if (!state.skip && next === '_') append('\u2011')
|
||||
continue
|
||||
}
|
||||
|
||||
let word = next
|
||||
while (i + 1 < input.length && /[A-Za-z]/.test(input[i + 1])) word += input[++i]
|
||||
let sign = 1
|
||||
if (input[i + 1] === '-') {
|
||||
sign = -1
|
||||
i++
|
||||
}
|
||||
let digits = ''
|
||||
while (i + 1 < input.length && /\d/.test(input[i + 1])) digits += input[++i]
|
||||
const parameter = digits ? sign * Number(digits) : null
|
||||
if (input[i + 1] === ' ') i++
|
||||
|
||||
const lower = word.toLowerCase()
|
||||
if (DESTINATIONS.has(lower)) {
|
||||
state.skip = true
|
||||
continue
|
||||
}
|
||||
if (lower === 'uc' && parameter !== null) {
|
||||
state.uc = Math.max(0, parameter)
|
||||
continue
|
||||
}
|
||||
if (lower === 'u' && parameter !== null && !state.skip) {
|
||||
append(String.fromCharCode(parameter < 0 ? parameter + 65536 : parameter))
|
||||
skipFallback = state.uc
|
||||
continue
|
||||
}
|
||||
if (state.skip) continue
|
||||
if (lower === 'par' || lower === 'line') {
|
||||
resetParagraph()
|
||||
continue
|
||||
}
|
||||
if (lower === 'tab') {
|
||||
append('\t')
|
||||
continue
|
||||
}
|
||||
if (SYMBOLS[lower] !== undefined) {
|
||||
append(SYMBOLS[lower])
|
||||
continue
|
||||
}
|
||||
if (lower === 'b') state.bold = parameter !== 0
|
||||
else if (lower === 'i') state.italic = parameter !== 0
|
||||
else if (lower === 'ul') state.underline = parameter !== 0
|
||||
else if (lower === 'ulnone') state.underline = false
|
||||
else if (lower === 'strike') state.strike = parameter !== 0
|
||||
else if (lower === 'super') state.vertAlign = 'superscript'
|
||||
else if (lower === 'sub') state.vertAlign = 'subscript'
|
||||
else if (lower === 'nosupersub') state.vertAlign = undefined
|
||||
else if (lower === 'caps') state.caps = parameter === 0 ? undefined : 'all'
|
||||
else if (lower === 'scaps') state.caps = parameter === 0 ? undefined : 'small'
|
||||
else if (lower === 'fs' && parameter !== null) state.sizeHalfPoints = parameter
|
||||
else if (lower === 'plain') {
|
||||
state.bold = false
|
||||
state.italic = false
|
||||
state.underline = false
|
||||
state.strike = false
|
||||
state.vertAlign = undefined
|
||||
state.caps = undefined
|
||||
state.sizeHalfPoints = undefined
|
||||
} else if (lower === 'pard') {
|
||||
state.indentLeft = undefined
|
||||
state.indentRight = undefined
|
||||
state.indentFirstLine = undefined
|
||||
state.spaceBefore = undefined
|
||||
state.spaceAfter = undefined
|
||||
state.align = undefined
|
||||
syncParagraphFormat()
|
||||
} else if (lower === 'li' && parameter !== null) {
|
||||
state.indentLeft = parameter
|
||||
syncParagraphFormat()
|
||||
} else if (lower === 'ri' && parameter !== null) {
|
||||
state.indentRight = parameter
|
||||
syncParagraphFormat()
|
||||
} else if (lower === 'fi' && parameter !== null) {
|
||||
state.indentFirstLine = parameter
|
||||
syncParagraphFormat()
|
||||
} else if (lower === 'sb' && parameter !== null) {
|
||||
state.spaceBefore = parameter
|
||||
syncParagraphFormat()
|
||||
} else if (lower === 'sa' && parameter !== null) {
|
||||
state.spaceAfter = parameter
|
||||
syncParagraphFormat()
|
||||
} else if (lower === 'ql' || lower === 'qc' || lower === 'qr' || lower === 'qj') {
|
||||
state.align = { ql: 'left', qc: 'center', qr: 'right', qj: 'justify' }[lower] as
|
||||
'left' | 'center' | 'right' | 'justify'
|
||||
syncParagraphFormat()
|
||||
}
|
||||
}
|
||||
|
||||
paragraphs.push(paragraph)
|
||||
while (paragraphs.length > 1 && paragraphs[0].runs.length === 0) paragraphs.shift()
|
||||
while (paragraphs.length > 1 && paragraphs[paragraphs.length - 1].runs.length === 0) {
|
||||
paragraphs.pop()
|
||||
}
|
||||
return { paragraphs }
|
||||
}
|
||||
|
||||
/** Convert Zotero's LibreOffice RTF output to editable Unicode text. */
|
||||
export function zoteroRtfToText(input: string): string {
|
||||
if (!/^\{\\rtf/i.test(input.trim())) return input
|
||||
return parseZoteroRtf(input)
|
||||
.paragraphs.map((paragraph) => paragraph.runs.map((run) => run.text).join(''))
|
||||
.join('\n')
|
||||
.replace(/\n{3,}/g, '\n\n')
|
||||
}
|
||||
@@ -189,6 +189,31 @@ export interface AiDocContent {
|
||||
html: string
|
||||
}
|
||||
|
||||
export type ZoteroCommand =
|
||||
'addEditCitation' | 'addEditBibliography' | 'refresh' | 'setDocPrefs' | 'removeCodes'
|
||||
|
||||
export type ZoteroCommandErrorCode =
|
||||
'connection-refused' | 'unsupported-command' | 'operation-failed'
|
||||
|
||||
export interface ZoteroCommandResult {
|
||||
ok: boolean
|
||||
errorCode?: ZoteroCommandErrorCode
|
||||
error?: string
|
||||
}
|
||||
|
||||
export interface ZoteroRendererRequest {
|
||||
requestId: string
|
||||
command: string
|
||||
args: unknown[]
|
||||
}
|
||||
|
||||
export interface ZoteroRendererResponse {
|
||||
requestId: string
|
||||
ok: boolean
|
||||
result?: unknown
|
||||
error?: string
|
||||
}
|
||||
|
||||
export interface DesktopApi {
|
||||
/** current UI language (persisted by the shell in app-settings.json) */
|
||||
getLanguage(): Promise<'zh' | 'en' | 'ja' | 'ko' | 'fr' | 'de' | 'es' | 'th' | 'id' | 'ru' | 'ar'>
|
||||
@@ -211,6 +236,10 @@ export interface DesktopApi {
|
||||
/** press on the shell chrome (tab strip is a sibling WebContentsView whose
|
||||
* clicks produce no DOM event here) — dismiss open popovers */
|
||||
onChromePressed(handler: () => void): () => void
|
||||
/** invoke Zotero's word-processor integration and service its document callbacks */
|
||||
zoteroCommand(command: ZoteroCommand): Promise<ZoteroCommandResult>
|
||||
onZoteroRequest(handler: (request: ZoteroRendererRequest) => void): () => void
|
||||
respondToZotero(response: ZoteroRendererResponse): void
|
||||
openDocx(): Promise<OpenDocxResult>
|
||||
openDocxPath(path: string): Promise<OpenDocxResult>
|
||||
/** decrypt-and-open a password-protected docx (path from a needsPassword result) */
|
||||
|
||||
@@ -39,6 +39,32 @@ describe('inlineToRuns hard break after atomic runs', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('Zotero field conversion', () => {
|
||||
it('preserves one field id and its cross-paragraph boundaries', () => {
|
||||
const instruction = 'ADDIN ZOTERO_BIBL {} CSL_BIBLIOGRAPHY'
|
||||
const parts = ['begin', 'inside', 'end'] as const
|
||||
const inline = parts.map(
|
||||
(part, index) =>
|
||||
runsToInline([
|
||||
{
|
||||
text: `Reference ${index + 1}`,
|
||||
instrField: instruction,
|
||||
zoteroFieldId: 17,
|
||||
zoteroFieldPart: part,
|
||||
},
|
||||
])[0],
|
||||
)
|
||||
|
||||
const marks = inline.map((node) => node.marks?.find((mark) => mark.type === 'instrField'))
|
||||
expect(marks.map((mark) => mark?.attrs?.fieldId)).toEqual([17, 17, 17])
|
||||
expect(marks.map((mark) => mark?.attrs?.fieldPart)).toEqual(parts)
|
||||
|
||||
const runs = inline.map((node) => inlineToRuns([node])[0])
|
||||
expect(runs.map((run) => run.zoteroFieldId)).toEqual([17, 17, 17])
|
||||
expect(runs.map((run) => run.zoteroFieldPart)).toEqual(parts)
|
||||
})
|
||||
})
|
||||
|
||||
describe('runsToInline image runs', () => {
|
||||
it('keeps sibling w:t text on a run that also carries a drawing', () => {
|
||||
const runs = [
|
||||
|
||||
@@ -23,6 +23,7 @@ function cleanState(): DocDirtyState {
|
||||
inksDirty: false,
|
||||
notesDirty: false,
|
||||
sourcesDirty: false,
|
||||
zoteroDocumentDataDirty: false,
|
||||
themeFontsDirty: false,
|
||||
themeColorsDirty: false,
|
||||
commentsDirty: false,
|
||||
@@ -64,6 +65,7 @@ describe('isDocDirty', () => {
|
||||
['inksDirty', { inksDirty: true }],
|
||||
['notesDirty', { notesDirty: true }],
|
||||
['sourcesDirty', { sourcesDirty: true }],
|
||||
['zoteroDocumentDataDirty', { zoteroDocumentDataDirty: true }],
|
||||
['themeFontsDirty', { themeFontsDirty: true }],
|
||||
['themeColorsDirty', { themeColorsDirty: true }],
|
||||
['numberingDirty', { numberingDirty: true }],
|
||||
|
||||
@@ -54,15 +54,21 @@ describe('invisible characters survive saving', () => {
|
||||
|
||||
it('keeps the NBSP when the field result is edited in place', async () => {
|
||||
const { parsed, editor, host } = await openDoc(FIELD_PARA)
|
||||
const text = host.querySelector<HTMLElement>('.doc-field-text')!
|
||||
expect(text.textContent).toBe(FIELD_TEXT)
|
||||
text.textContent = FIELD_TEXT + '!'
|
||||
text.dispatchEvent(new Event('input', { bubbles: true }))
|
||||
const field = host.querySelector<HTMLElement>('.zotero-ref-field')!
|
||||
expect(field.textContent).toBe(FIELD_TEXT)
|
||||
const marks = editor.state.doc.nodeAt(1)?.marks ?? []
|
||||
editor.view.dispatch(
|
||||
editor.state.tr.replaceWith(
|
||||
1,
|
||||
FIELD_TEXT.length + 1,
|
||||
editor.state.schema.text(`${FIELD_TEXT}!`, marks),
|
||||
),
|
||||
)
|
||||
window.dispatchEvent(new Event('ai-docs-commit-tables'))
|
||||
const plan = pmDocToSavePlan(editor.getJSON() as PmNode, parsed.blocks)
|
||||
expect(plan.changedCount).toBe(1)
|
||||
const xml = await documentXml(await saveDocx(parsed, plan.saveBlocks))
|
||||
expect(xml).toContain(`<w:t>${FIELD_TEXT}!</w:t>`)
|
||||
expect(xml).toContain(`${FIELD_TEXT}!`)
|
||||
expect(xml).toContain('ZOTERO_ITEM')
|
||||
editor.destroy()
|
||||
host.remove()
|
||||
|
||||
@@ -0,0 +1,229 @@
|
||||
import { Editor, Mark, Node } from '@tiptap/core'
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import { ZoteroDocumentController } from '../src/renderer/zotero/controller'
|
||||
|
||||
const Doc = Node.create({ name: 'doc', topNode: true, content: 'paragraph+' })
|
||||
const Paragraph = Node.create({
|
||||
name: 'paragraph',
|
||||
group: 'block',
|
||||
content: 'inline*',
|
||||
addAttributes: () => ({
|
||||
docxIndex: { default: null },
|
||||
indentLeft: { default: null },
|
||||
indentRight: { default: null },
|
||||
indentFirstLine: { default: null },
|
||||
spaceBefore: { default: null },
|
||||
spaceAfter: { default: null },
|
||||
align: { default: null },
|
||||
}),
|
||||
parseHTML: () => [{ tag: 'p' }],
|
||||
renderHTML: () => ['p', 0],
|
||||
})
|
||||
const Text = Node.create({ name: 'text', group: 'inline' })
|
||||
const Bold = Mark.create({ name: 'bold', renderHTML: () => ['strong', 0] })
|
||||
const Italic = Mark.create({ name: 'italic', renderHTML: () => ['em', 0] })
|
||||
const Underline = Mark.create({ name: 'underline', renderHTML: () => ['u', 0] })
|
||||
const Strike = Mark.create({ name: 'strike', renderHTML: () => ['s', 0] })
|
||||
const DocTextStyle = Mark.create({
|
||||
name: 'docTextStyle',
|
||||
addAttributes: () => ({
|
||||
vertAlign: { default: null },
|
||||
caps: { default: null },
|
||||
sizeHalfPoints: { default: null },
|
||||
}),
|
||||
renderHTML: () => ['span', 0],
|
||||
})
|
||||
const InstrField = Mark.create({
|
||||
name: 'instrField',
|
||||
inclusive: false,
|
||||
addAttributes: () => ({
|
||||
instr: { default: '' },
|
||||
beginXml: { default: null },
|
||||
fieldId: { default: null, rendered: false },
|
||||
fieldPart: { default: null, rendered: false },
|
||||
}),
|
||||
renderHTML: ({ mark }) => ['span', { 'data-instr-field': mark.attrs.instr }, 0],
|
||||
})
|
||||
|
||||
let editor: Editor | null = null
|
||||
|
||||
interface TestJsonNode {
|
||||
text?: string
|
||||
attrs?: Record<string, unknown>
|
||||
marks?: Array<{ type: string; attrs?: Record<string, unknown> }>
|
||||
content?: TestJsonNode[]
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
editor?.destroy()
|
||||
editor = null
|
||||
})
|
||||
|
||||
describe('ZoteroDocumentController', () => {
|
||||
const extensions = [
|
||||
Doc,
|
||||
Paragraph,
|
||||
Text,
|
||||
Bold,
|
||||
Italic,
|
||||
Underline,
|
||||
Strike,
|
||||
DocTextStyle,
|
||||
InstrField,
|
||||
]
|
||||
|
||||
it('inserts and updates a Zotero field using the LibreOffice wire contract', async () => {
|
||||
let documentData = ''
|
||||
editor = new Editor({
|
||||
element: document.createElement('div'),
|
||||
extensions,
|
||||
content: { type: 'doc', content: [{ type: 'paragraph' }] },
|
||||
})
|
||||
const controller = new ZoteroDocumentController(editor, {
|
||||
get: () => documentData,
|
||||
set: (value) => {
|
||||
documentData = value
|
||||
},
|
||||
})
|
||||
const call = (command: string, args: unknown[]) =>
|
||||
controller.handle({ requestId: 'test', command, args })
|
||||
|
||||
expect(await call('Application_getActiveDocument', [3])).toEqual([3, 1])
|
||||
const inserted = (await call('Document_insertField', [1, 'ReferenceMark', 0])) as [
|
||||
number,
|
||||
string,
|
||||
number,
|
||||
]
|
||||
expect(inserted.slice(1)).toEqual(['TEMP', 0])
|
||||
|
||||
const code = 'ITEM CSL_CITATION {"citationID":"citation-1"}'
|
||||
await call('Field_setCode', [1, inserted[0], code])
|
||||
await call('Field_setText', [1, inserted[0], '(Smith, 2024)', false])
|
||||
expect(await call('Field_getText', [1, inserted[0]])).toBe('(Smith, 2024)')
|
||||
expect(await call('Document_getFields', [1, 'ReferenceMark'])).toEqual([
|
||||
[inserted[0]],
|
||||
[code],
|
||||
[0],
|
||||
[-1],
|
||||
])
|
||||
|
||||
await call('Document_setDocumentData', [1, '<data data-version="3"/>'])
|
||||
expect(await call('Document_getDocumentData', [1])).toBe('<data data-version="3"/>')
|
||||
await call('Field_removeCode', [1, inserted[0]])
|
||||
expect(editor.getText()).toBe('(Smith, 2024)')
|
||||
expect(await call('Document_getFields', [1, 'ReferenceMark'])).toEqual([[], [], [], []])
|
||||
})
|
||||
|
||||
it('keeps a multi-paragraph Zotero bibliography as one field', async () => {
|
||||
editor = new Editor({
|
||||
element: document.createElement('div'),
|
||||
extensions,
|
||||
content: { type: 'doc', content: [{ type: 'paragraph' }] },
|
||||
})
|
||||
const controller = new ZoteroDocumentController(editor, { get: () => '', set: () => {} })
|
||||
const call = (command: string, args: unknown[]) =>
|
||||
controller.handle({ requestId: 'test', command, args })
|
||||
const [fieldId] = (await call('Document_insertField', [1, 'ReferenceMark', 0])) as [
|
||||
number,
|
||||
string,
|
||||
number,
|
||||
]
|
||||
const code = 'BIBL {"uncited":[],"omitted":[],"custom":[]} CSL_BIBLIOGRAPHY'
|
||||
await call('Field_setCode', [1, fieldId, code])
|
||||
await call('Field_setText', [
|
||||
1,
|
||||
fieldId,
|
||||
'{\\rtf1 Alpha, A. (2024).\\par Beta, B. (2023).\\par Gamma, G. (2022).}',
|
||||
true,
|
||||
])
|
||||
|
||||
const blocks = (editor.getJSON().content ?? []) as TestJsonNode[]
|
||||
expect(editor.state.doc.content.content.map((block) => block.textContent)).toEqual([
|
||||
'Alpha, A. (2024).',
|
||||
'Beta, B. (2023).',
|
||||
'Gamma, G. (2022).',
|
||||
])
|
||||
expect(
|
||||
blocks.map(
|
||||
(block) =>
|
||||
block.content?.[0]?.marks?.find((mark) => mark.type === 'instrField')?.attrs?.fieldPart,
|
||||
),
|
||||
).toEqual(['begin', 'inside', 'end'])
|
||||
expect(await call('Field_getText', [1, fieldId])).toBe(
|
||||
'Alpha, A. (2024).\nBeta, B. (2023).\nGamma, G. (2022).',
|
||||
)
|
||||
expect(await call('Document_getFields', [1, 'ReferenceMark'])).toEqual([
|
||||
[fieldId],
|
||||
[code],
|
||||
[0],
|
||||
[-1],
|
||||
])
|
||||
|
||||
await call('Field_removeCode', [1, fieldId])
|
||||
expect(editor.state.doc.content.content.map((block) => block.textContent)).toEqual([
|
||||
'Alpha, A. (2024).',
|
||||
'Beta, B. (2023).',
|
||||
'Gamma, G. (2022).',
|
||||
])
|
||||
})
|
||||
|
||||
it('maps Zotero RTF styles and hanging indents into editable document formatting', async () => {
|
||||
editor = new Editor({
|
||||
element: document.createElement('div'),
|
||||
extensions,
|
||||
content: { type: 'doc', content: [{ type: 'paragraph' }] },
|
||||
})
|
||||
const controller = new ZoteroDocumentController(editor, { get: () => '', set: () => {} })
|
||||
const call = (command: string, args: unknown[]) =>
|
||||
controller.handle({ requestId: 'test', command, args })
|
||||
const [fieldId] = (await call('Document_insertField', [1, 'ReferenceMark', 0])) as [
|
||||
number,
|
||||
string,
|
||||
number,
|
||||
]
|
||||
await call('Field_setCode', [1, fieldId, 'BIBL {} CSL_BIBLIOGRAPHY'])
|
||||
await call('Field_setText', [
|
||||
1,
|
||||
fieldId,
|
||||
'{\\rtf1\\pard\\li720\\fi-360 Alpha {\\i Journal} {\\super 2}\\par ' +
|
||||
'\\pard\\li720\\fi-360 {\\b Beta} {\\sub n}\\par}',
|
||||
true,
|
||||
])
|
||||
|
||||
const blocks = (editor.getJSON().content ?? []) as TestJsonNode[]
|
||||
expect(blocks.map((block) => block.attrs)).toEqual([
|
||||
expect.objectContaining({ indentLeft: 720, indentFirstLine: -360 }),
|
||||
expect.objectContaining({ indentLeft: 720, indentFirstLine: -360 }),
|
||||
])
|
||||
const textNodes = blocks.flatMap((block) => block.content ?? [])
|
||||
const marksOf = (text: string) => textNodes.find((node) => node.text === text)?.marks ?? []
|
||||
expect(marksOf('Journal').map((mark) => mark.type)).toContain('italic')
|
||||
expect(marksOf('2')).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
type: 'docTextStyle',
|
||||
attrs: expect.objectContaining({ vertAlign: 'superscript' }),
|
||||
}),
|
||||
]),
|
||||
)
|
||||
expect(marksOf('Beta').map((mark) => mark.type)).toContain('bold')
|
||||
expect(marksOf('n')).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
type: 'docTextStyle',
|
||||
attrs: expect.objectContaining({ vertAlign: 'subscript' }),
|
||||
}),
|
||||
]),
|
||||
)
|
||||
|
||||
await call('Field_removeCode', [1, fieldId])
|
||||
const withoutCodes = ((editor.getJSON().content ?? []) as TestJsonNode[]).flatMap(
|
||||
(block) => block.content ?? [],
|
||||
)
|
||||
expect(
|
||||
withoutCodes
|
||||
.find((node) => node.text === 'Journal')
|
||||
?.marks?.some((mark) => mark.type === 'italic'),
|
||||
).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,54 @@
|
||||
import { Editor } from '@tiptap/core'
|
||||
import { buildBlankDocx, parseDocx, saveDocx } from '@genoffice/docx-engine'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { blocksToPmDoc, pmDocToSavePlan, type PmNode } from '../src/renderer/editor/convert'
|
||||
import { editorExtensions } from '../src/renderer/editor/extensions'
|
||||
import { ZoteroDocumentController } from '../src/renderer/zotero/controller'
|
||||
|
||||
describe('Zotero rich bibliography DOCX round-trip', () => {
|
||||
it('keeps rich runs, hanging indents, and one field across paragraphs', async () => {
|
||||
const parsed = await parseDocx(await buildBlankDocx())
|
||||
const editor = new Editor({
|
||||
element: document.createElement('div'),
|
||||
extensions: editorExtensions,
|
||||
content: blocksToPmDoc(parsed.blocks) as never,
|
||||
})
|
||||
const controller = new ZoteroDocumentController(editor, { get: () => '', set: () => {} })
|
||||
const call = (command: string, args: unknown[]) =>
|
||||
controller.handle({ requestId: 'test', command, args })
|
||||
|
||||
try {
|
||||
const [fieldId] = (await call('Document_insertField', [1, 'ReferenceMark', 0])) as [
|
||||
number,
|
||||
string,
|
||||
number,
|
||||
]
|
||||
await call('Field_setCode', [1, fieldId, 'BIBL {} CSL_BIBLIOGRAPHY'])
|
||||
await call('Field_setText', [
|
||||
1,
|
||||
fieldId,
|
||||
'{\\rtf1\\pard\\li720\\fi-360 Alpha {\\i Journal} {\\super 2} {\\scaps Press}\\\r\n' +
|
||||
'\\pard\\li720\\fi-360 Beta}',
|
||||
true,
|
||||
])
|
||||
|
||||
const plan = pmDocToSavePlan(editor.getJSON() as PmNode, parsed.blocks)
|
||||
const reopened = await parseDocx(await saveDocx(parsed, plan.saveBlocks))
|
||||
const blocks = reopened.blocks.filter((block) => !block.hidden)
|
||||
expect(blocks).toHaveLength(2)
|
||||
expect(blocks.map((block) => block.format)).toEqual([
|
||||
expect.objectContaining({ indentLeft: 720, indentFirstLine: -360 }),
|
||||
expect.objectContaining({ indentLeft: 720, indentFirstLine: -360 }),
|
||||
])
|
||||
const runs = blocks.flatMap((block) => block.runs ?? [])
|
||||
expect(runs.find((run) => run.text === 'Journal')?.italic).toBe(true)
|
||||
expect(runs.find((run) => run.text === '2')?.vertAlign).toBe('superscript')
|
||||
expect(runs.find((run) => run.text === 'Press')?.caps).toBe('small')
|
||||
expect(new Set(runs.map((run) => run.zoteroFieldId)).size).toBe(1)
|
||||
expect(runs[0].zoteroFieldPart).toBe('begin')
|
||||
expect(runs[runs.length - 1].zoteroFieldPart).toBe('end')
|
||||
} finally {
|
||||
editor.destroy()
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,98 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
zoteroCodeFromInstruction,
|
||||
zoteroInstructionFromCode,
|
||||
} from '../src/renderer/zotero/controller'
|
||||
import { parseZoteroRtf, zoteroRtfToText } from '../src/renderer/zotero/rtf'
|
||||
|
||||
describe('Zotero RTF conversion', () => {
|
||||
it('decodes Unicode, escaped punctuation, tabs, and paragraph breaks', () => {
|
||||
const rtf =
|
||||
"{\\rtf1\\ansi\\uc1{\\fonttbl{\\f0 Arial;}}Smith \\'96 Jones\\tab 2024\\par \\u20013?\\u25991?}"
|
||||
expect(zoteroRtfToText(rtf)).toBe('Smith – Jones\t2024\n中文')
|
||||
})
|
||||
|
||||
it('splits bibliography entries joined with Zotero RTF line continuations', () => {
|
||||
const rtf =
|
||||
'{\\rtf1\\ansi [1]\\tab First entry\\\r\n' +
|
||||
'[2]\\tab Second entry\\\r\n' +
|
||||
'[3]\\tab Third entry}'
|
||||
|
||||
expect(
|
||||
parseZoteroRtf(rtf).paragraphs.map((paragraph) =>
|
||||
paragraph.runs.map((run) => run.text).join(''),
|
||||
),
|
||||
).toEqual(['[1]\tFirst entry', '[2]\tSecond entry', '[3]\tThird entry'])
|
||||
})
|
||||
|
||||
it('leaves Zotero plain-text output unchanged', () => {
|
||||
expect(zoteroRtfToText('(Smith, 2024)')).toBe('(Smith, 2024)')
|
||||
})
|
||||
|
||||
it('preserves character styles and bibliography hanging indents', () => {
|
||||
const rtf =
|
||||
'{\\rtf1\\ansi\\pard\\li720\\fi-360 Alpha {\\i Journal} {\\super 2}\\par ' +
|
||||
'\\pard\\li720\\fi-360 {\\b Beta} {\\sub n}\\par}'
|
||||
|
||||
expect(parseZoteroRtf(rtf)).toEqual({
|
||||
paragraphs: [
|
||||
{
|
||||
indentLeft: 720,
|
||||
indentFirstLine: -360,
|
||||
runs: [
|
||||
{ text: 'Alpha ' },
|
||||
{ text: 'Journal', italic: true },
|
||||
{ text: ' ' },
|
||||
{ text: '2', vertAlign: 'superscript' },
|
||||
],
|
||||
},
|
||||
{
|
||||
indentLeft: 720,
|
||||
indentFirstLine: -360,
|
||||
runs: [
|
||||
{ text: 'Beta', bold: true },
|
||||
{ text: ' ' },
|
||||
{ text: 'n', vertAlign: 'subscript' },
|
||||
],
|
||||
},
|
||||
],
|
||||
})
|
||||
})
|
||||
|
||||
it('handles Zotero style resets, sizing, spacing, and alignment', () => {
|
||||
const parsed = parseZoteroRtf(
|
||||
'{\\rtf1\\pard\\qr\\ri120\\sb40\\sa80\\fs20 ' +
|
||||
'{\\ul Under} {\\strike Strike} {\\scaps Small} plain\\par}',
|
||||
)
|
||||
|
||||
expect(parsed.paragraphs[0]).toMatchObject({
|
||||
align: 'right',
|
||||
indentRight: 120,
|
||||
spaceBefore: 40,
|
||||
spaceAfter: 80,
|
||||
})
|
||||
expect(parsed.paragraphs[0].runs).toEqual([
|
||||
{ text: 'Under', underline: true, sizeHalfPoints: 20 },
|
||||
{ text: ' ', sizeHalfPoints: 20 },
|
||||
{ text: 'Strike', strike: true, sizeHalfPoints: 20 },
|
||||
{ text: ' ', sizeHalfPoints: 20 },
|
||||
{ text: 'Small', caps: 'small', sizeHalfPoints: 20 },
|
||||
{ text: ' plain', sizeHalfPoints: 20 },
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe('Zotero field code compatibility', () => {
|
||||
it('maps between the wire code and Word ADDIN field instruction', () => {
|
||||
const code = 'ITEM CSL_CITATION {"citationID":"abc"}'
|
||||
expect(zoteroInstructionFromCode(code)).toBe(`ADDIN ZOTERO_${code}`)
|
||||
expect(zoteroCodeFromInstruction(` ADDIN ZOTERO_${code} `)).toBe(code)
|
||||
})
|
||||
|
||||
it('supports older ZOTERO_ and CSL_ prefixes', () => {
|
||||
expect(zoteroCodeFromInstruction('ZOTERO_BIBL {} CSL_BIBLIOGRAPHY')).toBe(
|
||||
'BIBL {} CSL_BIBLIOGRAPHY',
|
||||
)
|
||||
expect(zoteroCodeFromInstruction('CSL_TEMP')).toBe('TEMP')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,30 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { encodeZoteroFrame, ZoteroFrameDecoder } from '../src/main/zotero-wire'
|
||||
|
||||
describe('Zotero integration wire framing', () => {
|
||||
it('encodes the transaction ID and UTF-8 byte length as big-endian uint32 values', () => {
|
||||
const frame = encodeZoteroFrame(42, '中文')
|
||||
expect(frame.readUInt32BE(0)).toBe(42)
|
||||
expect(frame.readUInt32BE(4)).toBe(6)
|
||||
expect(frame.subarray(8).toString('utf8')).toBe('中文')
|
||||
})
|
||||
|
||||
it('decodes a frame split across arbitrary TCP chunks', () => {
|
||||
const frame = encodeZoteroFrame(7, '["Document_complete",[1]]')
|
||||
const decoder = new ZoteroFrameDecoder()
|
||||
expect(decoder.push(frame.subarray(0, 3))).toEqual([])
|
||||
expect(decoder.push(frame.subarray(3, 11))).toEqual([])
|
||||
expect(decoder.push(frame.subarray(11))).toEqual([
|
||||
{ transactionId: 7, payload: '["Document_complete",[1]]' },
|
||||
])
|
||||
})
|
||||
|
||||
it('decodes multiple frames delivered in one TCP chunk', () => {
|
||||
const decoder = new ZoteroFrameDecoder()
|
||||
const chunk = Buffer.concat([encodeZoteroFrame(1, 'one'), encodeZoteroFrame(2, 'two')])
|
||||
expect(decoder.push(chunk)).toEqual([
|
||||
{ transactionId: 1, payload: 'one' },
|
||||
{ transactionId: 2, payload: 'two' },
|
||||
])
|
||||
})
|
||||
})
|
||||
@@ -2401,6 +2401,22 @@ function runFragmentXml(run: Run, insideLink: boolean): string {
|
||||
`<w:r><w:instrText xml:space="preserve"> ${escapeXmlText(run.instrField)} </w:instrText></w:r>` +
|
||||
'<w:r><w:fldChar w:fldCharType="separate"/></w:r>'
|
||||
const endXml = '<w:r><w:fldChar w:fldCharType="end"/></w:r>'
|
||||
if (run.zoteroFieldPart && run.zoteroFieldPart !== 'single') {
|
||||
const cachedXml = generateRunXml(
|
||||
{
|
||||
...run,
|
||||
instrField: undefined,
|
||||
zoteroFieldId: undefined,
|
||||
zoteroFieldPart: undefined,
|
||||
},
|
||||
insideLink,
|
||||
)
|
||||
if (run.zoteroFieldPart === 'begin') {
|
||||
return '<w:r><w:fldChar w:fldCharType="begin"/></w:r>' + instrXml + cachedXml
|
||||
}
|
||||
if (run.zoteroFieldPart === 'end') return cachedXml + endXml
|
||||
return cachedXml
|
||||
}
|
||||
if (run.fldBeginXml) {
|
||||
// Adjacent identical checkboxes merge into one text node in the editor
|
||||
// (equal marks), so each ☐/☒ glyph in the run is one field sharing the
|
||||
|
||||
@@ -100,6 +100,7 @@ export {
|
||||
stripInkRuns,
|
||||
} from './ink'
|
||||
export { bibliographyLine, citationText, parseSourcesXml } from './sources'
|
||||
export { parseZoteroDocumentDataXml, patchZoteroDocumentDataXml } from './zotero-doc-props'
|
||||
export { readThemeColors, readThemeFonts } from './theme'
|
||||
export { hashProtectionPassword, verifyProtectionPassword } from './protection'
|
||||
export { decodeSymbolChar, decodeSymbolText, isSymbolFont, toSymbolPua } from './symbol-fonts'
|
||||
|
||||
@@ -345,6 +345,9 @@ export function ptabDisplayStops(pNode: XNode): import('./types').TabStop[] {
|
||||
export const SIMPLE_INLINE_FIELD_RE =
|
||||
/^\s*(DATE|TIME|CREATEDATE|SAVEDATE|NUMPAGES|FILENAME|AUTHOR|PAGE)\b/
|
||||
|
||||
/** Zotero Word fields. Their cached result is the visible citation/bibliography text. */
|
||||
export const ZOTERO_INLINE_FIELD_RE = /^\s*(?:ADDIN\s+)?(?:ZOTERO_|CSL_)(?:ITEM|BIBL|TEMP)\b/i
|
||||
|
||||
/** HYPERLINK "url" (optional \o "tip"): the only field form folded into an editable link run;
|
||||
* any other switch (\l bookmark, \t frame...) keeps the protected-passthrough path */
|
||||
export function convertibleHyperlink(instr: string): { href: string; tooltip?: string } | null {
|
||||
@@ -379,6 +382,7 @@ export function onlyXeFields(xml: string): boolean {
|
||||
return (
|
||||
/^\s*XE[\s"]/.test(text) ||
|
||||
/^\s*REF\s/.test(text) ||
|
||||
ZOTERO_INLINE_FIELD_RE.test(text) ||
|
||||
SIMPLE_INLINE_FIELD_RE.test(text) ||
|
||||
convertibleHyperlink(text) !== null
|
||||
)
|
||||
|
||||
@@ -10,6 +10,7 @@ import { NOTE_PART_PATH, parseNotesXml } from './notes'
|
||||
import { scanBody, type BodyElement } from './scan'
|
||||
import { sectionSettingsFromXml, xmlFlagOn } from './section'
|
||||
import { findSourcesPart, parseSourcesXml } from './sources'
|
||||
import { readZoteroDocumentData } from './zotero-doc-props'
|
||||
import { decodeSymbolChar, decodeSymbolText } from './symbol-fonts'
|
||||
import { computeListMarkerInfos, type ListItemRef } from './list-markers'
|
||||
import { FONT_TABLE_PART_PATH, parseFontTable, readEmbeddedFonts } from './font-table'
|
||||
@@ -115,6 +116,7 @@ import {
|
||||
IMAGE_RUN_CHILDREN,
|
||||
JC_ALIGN,
|
||||
SIMPLE_INLINE_FIELD_RE,
|
||||
ZOTERO_INLINE_FIELD_RE,
|
||||
activeCharIndents,
|
||||
autoSpaceOf,
|
||||
bookmarkNamesOf,
|
||||
@@ -292,6 +294,7 @@ export async function parseDocx(bytes: Uint8Array): Promise<ParsedDoc & { extras
|
||||
const footnotes = await parseNotesPart(zip, 'footnote')
|
||||
const endnotes = await parseNotesPart(zip, 'endnote')
|
||||
const sources = await parseSources(zip)
|
||||
const zoteroDocumentData = await readZoteroDocumentData(zip)
|
||||
const fontTableFile = zip.file(FONT_TABLE_PART_PATH)
|
||||
const fontTable = fontTableFile ? parseFontTable(await fontTableFile.async('string')) : []
|
||||
const embeddedFonts = await readEmbeddedFonts(zip, fontTable)
|
||||
@@ -327,6 +330,7 @@ export async function parseDocx(bytes: Uint8Array): Promise<ParsedDoc & { extras
|
||||
}
|
||||
const elements: BodyElement[] = []
|
||||
const blocks: Block[] = []
|
||||
const zoteroFieldParagraphs = crossParagraphZoteroFields(scan.elements, documentXml)
|
||||
const chartParts: Record<string, string> = {}
|
||||
const buildCtx: BuildContext = {
|
||||
zip,
|
||||
@@ -345,6 +349,8 @@ export async function parseDocx(bytes: Uint8Array): Promise<ParsedDoc & { extras
|
||||
docDefaults,
|
||||
defaultParaStyle: [...styles.values()].find((s) => s.type === 'paragraph' && s.isDefault),
|
||||
xmlSpacePreserve: partXmlSpacePreserve(documentXml, 'w:document'),
|
||||
nextZoteroFieldId:
|
||||
Math.max(0, ...[...zoteroFieldParagraphs.values()].map((field) => field.id)) + 1,
|
||||
// explicit breaks in any attribute order, plus Word's rendered-page hint
|
||||
// (catches natural pages in single-section docs); a false positive only
|
||||
// turns page-pinning off, which is the conservative direction
|
||||
@@ -390,7 +396,7 @@ export async function parseDocx(bytes: Uint8Array): Promise<ParsedDoc & { extras
|
||||
}
|
||||
const i = elements.length
|
||||
elements.push(el)
|
||||
const block = await buildBlock(el, i, xml, buildCtx)
|
||||
const block = await buildBlock(el, i, xml, buildCtx, zoteroFieldParagraphs.get(el.start))
|
||||
blocks.push(block)
|
||||
buildCtx.floatTableAhead = floatTableColumnSpan(block, sectionAt(el.start))
|
||||
}
|
||||
@@ -466,6 +472,7 @@ export async function parseDocx(bytes: Uint8Array): Promise<ParsedDoc & { extras
|
||||
|
||||
return {
|
||||
blocks,
|
||||
zoteroDocumentData,
|
||||
comments,
|
||||
protection,
|
||||
writeProtection,
|
||||
@@ -547,6 +554,8 @@ interface BuildContext {
|
||||
/** part root declares xml:space="preserve" (inherited XML scope; PDF converters
|
||||
* rely on it instead of per-w:t attributes) */
|
||||
xmlSpacePreserve?: boolean
|
||||
/** Per-document identity source for editable Zotero fields. */
|
||||
nextZoteroFieldId?: number
|
||||
}
|
||||
|
||||
/** numbering reference of a paragraph: direct w:numPr, falling back to the pStyle's
|
||||
@@ -600,6 +609,7 @@ async function buildBlock(
|
||||
index: number,
|
||||
xml: string,
|
||||
ctx: BuildContext,
|
||||
zoteroField?: ZoteroFieldParagraph,
|
||||
): Promise<Block> {
|
||||
const base = { id: `b${index}`, docxIndex: index, originalXml: xml }
|
||||
|
||||
@@ -767,7 +777,7 @@ async function buildBlock(
|
||||
return { ...base, type: 'image', label: 'Image', imageDataUrl: image, ...imageMeta(detect) }
|
||||
}
|
||||
}
|
||||
if (hasFields) {
|
||||
if (hasFields && !zoteroField) {
|
||||
// Legacy field-form OLE ({ EMBED ... } / { LINK ... } around a w:object):
|
||||
// take the OLE display path so the packaged preview picture and its
|
||||
// declared size survive instead of a bare "Field (EMBED)" chip.
|
||||
@@ -1273,7 +1283,66 @@ async function buildBlock(
|
||||
}
|
||||
}
|
||||
|
||||
return buildTextParagraph(base, xml, ctx, false, el.start)
|
||||
return buildTextParagraph(base, xml, ctx, false, el.start, zoteroField)
|
||||
}
|
||||
|
||||
type ZoteroFieldPart = NonNullable<Run['zoteroFieldPart']>
|
||||
|
||||
interface ZoteroFieldParagraph {
|
||||
id: number
|
||||
instruction: string
|
||||
part: ZoteroFieldPart
|
||||
}
|
||||
|
||||
/** Find complex Zotero fields whose cached result crosses top-level paragraphs. */
|
||||
function crossParagraphZoteroFields(
|
||||
bodyElements: BodyElement[],
|
||||
documentXml: string,
|
||||
): Map<number, ZoteroFieldParagraph> {
|
||||
const result = new Map<number, ZoteroFieldParagraph>()
|
||||
let nextId = 1
|
||||
let active: { depth: number; instruction: string; paragraphStarts: number[] } | undefined
|
||||
const tokenRe = /<w:fldChar\b[^>]*>|<w:instrText\b[^>]*>[\s\S]*?<\/w:instrText>/g
|
||||
|
||||
for (const el of bodyElements) {
|
||||
if (el.name !== 'w:p') {
|
||||
active = undefined
|
||||
continue
|
||||
}
|
||||
const xml = documentXml.slice(el.start, el.end)
|
||||
if (active) active.paragraphStarts.push(el.start)
|
||||
|
||||
for (const match of xml.matchAll(tokenRe)) {
|
||||
const token = match[0]
|
||||
if (token.startsWith('<w:instrText')) {
|
||||
if (active?.depth === 1) {
|
||||
active.instruction += decodeEntities(token.replace(/<[^>]+>/g, ''))
|
||||
}
|
||||
continue
|
||||
}
|
||||
const fieldType = /\bw:fldCharType\s*=\s*["'](begin|separate|end)["']/.exec(token)?.[1]
|
||||
if (fieldType === 'begin') {
|
||||
if (active) active.depth++
|
||||
else active = { depth: 1, instruction: '', paragraphStarts: [el.start] }
|
||||
} else if (fieldType === 'end' && active) {
|
||||
active.depth--
|
||||
if (active.depth === 0) {
|
||||
const paragraphs = [...new Set(active.paragraphStarts)]
|
||||
const instruction = active.instruction.trim()
|
||||
if (paragraphs.length > 1 && ZOTERO_INLINE_FIELD_RE.test(instruction)) {
|
||||
const id = nextId++
|
||||
paragraphs.forEach((start, index) => {
|
||||
const part: ZoteroFieldPart =
|
||||
index === 0 ? 'begin' : index === paragraphs.length - 1 ? 'end' : 'inside'
|
||||
result.set(start, { id, instruction, part })
|
||||
})
|
||||
}
|
||||
active = undefined
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1461,6 +1530,7 @@ function buildTextParagraph(
|
||||
ctx: BuildContext,
|
||||
withImages = false,
|
||||
docOffset?: number,
|
||||
zoteroField?: ZoteroFieldParagraph,
|
||||
): Block {
|
||||
let parsed: XNode[]
|
||||
try {
|
||||
@@ -1517,6 +1587,7 @@ function buildTextParagraph(
|
||||
ommlFragmentsOf(mathXml),
|
||||
rubyFragmentsOf(mathXml),
|
||||
withImages,
|
||||
zoteroField,
|
||||
)
|
||||
if (runs.length === 0) {
|
||||
const emptySz = emptyParaSizeHalfPoints(pNode, pPr)
|
||||
@@ -2993,6 +3064,7 @@ function extractRuns(
|
||||
mathFragments: string[] = [],
|
||||
rubyFragments: string[] = [],
|
||||
withImages = false,
|
||||
zoteroField?: ZoteroFieldParagraph,
|
||||
): Run[] {
|
||||
const runs: Run[] = []
|
||||
let mathIndex = 0
|
||||
@@ -3026,9 +3098,9 @@ function extractRuns(
|
||||
const activeComments = new Set<string>()
|
||||
type RevCtx = { ins?: RevisionInfo; del?: RevisionInfo }
|
||||
// inline field state: XE folds into Run.xeTerm, REF (cross-reference) into Run.refField
|
||||
let fieldDepth = 0
|
||||
let fieldInstr = ''
|
||||
let fieldSeparated = false
|
||||
let fieldDepth = zoteroField && zoteroField.part !== 'begin' ? 1 : 0
|
||||
let fieldInstr = zoteroField?.instruction ?? ''
|
||||
let fieldSeparated = zoteroField !== undefined && zoteroField.part !== 'begin'
|
||||
let fieldCached = ''
|
||||
let fieldCachedRuns: Run[] = []
|
||||
let fieldBeginRun: XNode | null = null
|
||||
@@ -3048,6 +3120,27 @@ function extractRuns(
|
||||
if (rev?.del) run.del = rev.del
|
||||
runs.push(run)
|
||||
}
|
||||
const pushZoteroCachedRuns = (part: ZoteroFieldPart, rev?: RevCtx) => {
|
||||
const cachedRuns = fieldCachedRuns.length > 0 ? fieldCachedRuns : [{ text: fieldCached || ' ' }]
|
||||
const id = zoteroField?.id ?? ctx.nextZoteroFieldId ?? 1
|
||||
if (!zoteroField) ctx.nextZoteroFieldId = id + 1
|
||||
cachedRuns.forEach((cached, index) => {
|
||||
let runPart: ZoteroFieldPart = part
|
||||
if (part === 'single' && cachedRuns.length > 1) {
|
||||
runPart = index === 0 ? 'begin' : index === cachedRuns.length - 1 ? 'end' : 'inside'
|
||||
} else if (part === 'begin' && index > 0) runPart = 'inside'
|
||||
else if (part === 'end' && index < cachedRuns.length - 1) runPart = 'inside'
|
||||
pushRun(
|
||||
{
|
||||
...cached,
|
||||
instrField: (zoteroField?.instruction ?? fieldInstr).trim(),
|
||||
zoteroFieldId: id,
|
||||
zoteroFieldPart: runPart,
|
||||
},
|
||||
rev,
|
||||
)
|
||||
})
|
||||
}
|
||||
const handleRun = (node: XNode, link: Run['link'] | undefined, rev?: RevCtx) => {
|
||||
const fldChar = findChild(node, 'w:fldChar')
|
||||
if (fldChar) {
|
||||
@@ -3112,6 +3205,9 @@ function extractRuns(
|
||||
rev,
|
||||
)
|
||||
}
|
||||
} else if (ZOTERO_INLINE_FIELD_RE.test(fieldInstr)) {
|
||||
if (zoteroField) pushZoteroCachedRuns(zoteroField.part, rev)
|
||||
else pushZoteroCachedRuns('single', rev)
|
||||
} else if (SIMPLE_INLINE_FIELD_RE.test(fieldInstr)) {
|
||||
pushRun({ text: fieldCached || ' ', instrField: fieldInstr.trim() }, rev)
|
||||
} else if (fieldCachedRuns.length > 0) {
|
||||
@@ -3263,6 +3359,9 @@ function extractRuns(
|
||||
}
|
||||
}
|
||||
walk(childrenOf(pNode))
|
||||
if (zoteroField && fieldDepth > 0 && zoteroField.part !== 'end') {
|
||||
pushZoteroCachedRuns(zoteroField.part)
|
||||
}
|
||||
return mergeRuns(runs)
|
||||
}
|
||||
|
||||
|
||||
@@ -60,6 +60,12 @@ import { PAGE_MARK, TOTAL_PAGES_MARK } from './types'
|
||||
import { patchParagraphTexts } from './text-patch'
|
||||
import { WATERMARK_NS, watermarkParagraphXml } from './watermark'
|
||||
import { escapeXmlAttr, escapeXmlText } from './xml-utils'
|
||||
import {
|
||||
CUSTOM_PROPERTIES_CONTENT_TYPE,
|
||||
CUSTOM_PROPERTIES_PATH,
|
||||
CUSTOM_PROPERTIES_REL_TYPE,
|
||||
patchZoteroDocumentDataXml,
|
||||
} from './zotero-doc-props'
|
||||
|
||||
export type ParsedDocFull = ParsedDoc & { extras: ParseExtras }
|
||||
|
||||
@@ -90,6 +96,8 @@ export type SaveBlock = (
|
||||
export interface SaveOptions {
|
||||
/** save timestamp (ISO), written to docProps/core.xml dcterms:modified; default = now */
|
||||
savedAt?: string
|
||||
/** Zotero document preferences; written as Word-compatible 255-character custom-property chunks */
|
||||
zoteroDocumentData?: string
|
||||
/** rewrite page size / margins in the trailing w:sectPr */
|
||||
section?: SectionSettings
|
||||
/** last-section start type (w:type); rewrites the trailing sectPr when inserting a continuous section break; undefined = keep */
|
||||
@@ -396,6 +404,7 @@ export async function saveDocx(
|
||||
fb.revision === undefined,
|
||||
) &&
|
||||
options.section === undefined &&
|
||||
options.zoteroDocumentData === undefined &&
|
||||
options.sectionStartType === undefined &&
|
||||
options.pgNumType === undefined &&
|
||||
options.pageColor === undefined &&
|
||||
@@ -429,6 +438,33 @@ export async function saveDocx(
|
||||
assertZipWithinLimits(zip)
|
||||
const docPath = (await resolveMainDocumentPath(zip)) ?? 'word/document.xml'
|
||||
|
||||
const customPropertiesEntry = zip.file(CUSTOM_PROPERTIES_PATH)
|
||||
const shouldWriteZoteroData =
|
||||
options.zoteroDocumentData !== undefined &&
|
||||
(options.zoteroDocumentData !== '' || customPropertiesEntry !== null)
|
||||
const customPropertiesXml = shouldWriteZoteroData
|
||||
? patchZoteroDocumentDataXml(
|
||||
customPropertiesEntry ? await customPropertiesEntry.async('string') : null,
|
||||
options.zoteroDocumentData!,
|
||||
)
|
||||
: null
|
||||
const customPropertiesIsNew = customPropertiesXml !== null && customPropertiesEntry === null
|
||||
const rootRelsPath = '_rels/.rels'
|
||||
let rootRelsXml: string | null = null
|
||||
if (customPropertiesIsNew) {
|
||||
const rootRelsEntry = zip.file(rootRelsPath)
|
||||
if (rootRelsEntry) {
|
||||
rootRelsXml = await rootRelsEntry.async('string')
|
||||
if (!rootRelsXml.includes(CUSTOM_PROPERTIES_REL_TYPE)) {
|
||||
const rId = `rId${maxRelId(rootRelsXml) + 1}`
|
||||
rootRelsXml = rootRelsXml.replace(
|
||||
'</Relationships>',
|
||||
`<Relationship Id="${rId}" Type="${CUSTOM_PROPERTIES_REL_TYPE}" Target="${CUSTOM_PROPERTIES_PATH}"/></Relationships>`,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Relationship allocation for newly created hyperlinks and images.
|
||||
const relsPath = docPath.replace(/([^/]+)$/, '_rels/$1.rels')
|
||||
const relsFile = zip.file(relsPath)
|
||||
@@ -1120,7 +1156,8 @@ export async function saveDocx(
|
||||
numberingIsNew ||
|
||||
notesParts.some((p) => p.isNew) ||
|
||||
sourcesPart?.isNew ||
|
||||
themePart?.isNew
|
||||
themePart?.isNew ||
|
||||
customPropertiesIsNew
|
||||
if (hasNewParts) {
|
||||
const file = zip.file(contentTypesPath)
|
||||
if (file) {
|
||||
@@ -1184,6 +1221,9 @@ export async function saveDocx(
|
||||
)
|
||||
}
|
||||
if (themePart?.isNew) addOverride(`/${THEME_PART_PATH}`, THEME_CONTENT_TYPE)
|
||||
if (customPropertiesIsNew) {
|
||||
addOverride(`/${CUSTOM_PROPERTIES_PATH}`, CUSTOM_PROPERTIES_CONTENT_TYPE)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1207,6 +1247,8 @@ export async function saveDocx(
|
||||
out.file(name, relsXml, { date: entry.date })
|
||||
} else if (name === contentTypesPath && contentTypesXml !== null) {
|
||||
out.file(name, contentTypesXml, { date: entry.date })
|
||||
} else if (name === rootRelsPath && rootRelsXml !== null) {
|
||||
out.file(name, rootRelsXml, { date: entry.date })
|
||||
} else if (name === settingsPath && settingsXml !== null) {
|
||||
out.file(name, settingsXml, { date: entry.date })
|
||||
} else if (name === commentsPath && commentsXml !== null) {
|
||||
@@ -1223,6 +1265,8 @@ export async function saveDocx(
|
||||
out.file(name, sourcesPart.xml, { date: entry.date })
|
||||
} else if (themePart && name === THEME_PART_PATH) {
|
||||
out.file(name, themePart.xml, { date: entry.date })
|
||||
} else if (name === CUSTOM_PROPERTIES_PATH && customPropertiesXml !== null) {
|
||||
out.file(name, customPropertiesXml, { date: entry.date })
|
||||
} else if (name === CORE_PROPS_PATH && coreXmlOut !== null) {
|
||||
out.file(name, coreXmlOut, { date: entry.date })
|
||||
} else if (options.partXml && options.partXml[name] !== undefined) {
|
||||
@@ -1284,6 +1328,9 @@ export async function saveDocx(
|
||||
if (themePart?.isNew) {
|
||||
out.file(THEME_PART_PATH, themePart.xml)
|
||||
}
|
||||
if (customPropertiesIsNew && customPropertiesXml !== null) {
|
||||
out.file(CUSTOM_PROPERTIES_PATH, customPropertiesXml)
|
||||
}
|
||||
await cleanupDocxOwnedResources(out, docPath)
|
||||
if (scrubPersonalInfo) await scrubPersonalMetadata(out)
|
||||
return out.generateAsync({
|
||||
|
||||
@@ -108,6 +108,10 @@ export interface Run {
|
||||
refInstr?: string
|
||||
/** Generic inline field (DATE/TIME/NUMPAGES/FILENAME etc.): full instruction text; run text is the cached result */
|
||||
instrField?: string
|
||||
/** Logical Zotero field shared by all cached-result runs, including runs in adjacent paragraphs. */
|
||||
zoteroFieldId?: number
|
||||
/** Position of this run inside a Zotero field that may span several paragraphs. */
|
||||
zoteroFieldPart?: 'single' | 'begin' | 'inside' | 'end'
|
||||
/** Original field-begin run XML (w:fldChar + w:ffData), written back verbatim so form-field
|
||||
* definitions survive; when set, the run text is a synthesized glyph (☐/☒), not a cached result */
|
||||
fldBeginXml?: string
|
||||
@@ -1841,6 +1845,8 @@ export interface ThemeColors {
|
||||
|
||||
export interface ParsedDoc {
|
||||
blocks: Block[]
|
||||
/** Zotero document preferences stored in Word custom properties */
|
||||
zoteroDocumentData: string
|
||||
/** comments from word/comments.xml, in file order */
|
||||
comments: CommentInfo[]
|
||||
/** footnotes from word/footnotes.xml (separators excluded), file order */
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
import JSZip from 'jszip'
|
||||
import { escapeXmlAttr, escapeXmlText } from './xml-utils'
|
||||
|
||||
export const CUSTOM_PROPERTIES_PATH = 'docProps/custom.xml'
|
||||
export const CUSTOM_PROPERTIES_REL_TYPE =
|
||||
'http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties'
|
||||
export const CUSTOM_PROPERTIES_CONTENT_TYPE =
|
||||
'application/vnd.openxmlformats-officedocument.custom-properties+xml'
|
||||
|
||||
const ZOTERO_PREF_NAME = /^ZOTERO_PREF(?:_(\d+))?$/
|
||||
const PROPERTY_RE =
|
||||
/<(?:[A-Za-z_][\w.-]*:)?property\b[^>]*>[\s\S]*?<\/(?:[A-Za-z_][\w.-]*:)?property\s*>/g
|
||||
|
||||
function decodeXmlText(value: string): string {
|
||||
return value
|
||||
.replace(/&#x([0-9a-f]+);/gi, (_match, hex) => String.fromCodePoint(parseInt(hex, 16)))
|
||||
.replace(/&#(\d+);/g, (_match, decimal) => String.fromCodePoint(parseInt(decimal, 10)))
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, "'")
|
||||
.replace(/&/g, '&')
|
||||
}
|
||||
|
||||
function attrValue(xml: string, name: string): string | null {
|
||||
const match = new RegExp(`\\b${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)')`).exec(xml)
|
||||
return match ? decodeXmlText(match[1] ?? match[2] ?? '') : null
|
||||
}
|
||||
|
||||
function propertyText(xml: string): string {
|
||||
const match =
|
||||
/<(?:[A-Za-z_][\w.-]*:)?lpwstr\b[^>]*>([\s\S]*?)<\/(?:[A-Za-z_][\w.-]*:)?lpwstr\s*>/.exec(xml)
|
||||
return decodeXmlText(match?.[1] ?? '')
|
||||
}
|
||||
|
||||
export function parseZoteroDocumentDataXml(xml: string): string {
|
||||
const chunks: Array<{ index: number; value: string }> = []
|
||||
let legacy = ''
|
||||
for (const property of xml.match(PROPERTY_RE) ?? []) {
|
||||
const name = attrValue(property, 'name')
|
||||
const match = name ? ZOTERO_PREF_NAME.exec(name) : null
|
||||
if (!match) continue
|
||||
const value = propertyText(property)
|
||||
if (match[1]) chunks.push({ index: Number(match[1]), value })
|
||||
else legacy = value
|
||||
}
|
||||
if (chunks.length === 0) return legacy
|
||||
return chunks
|
||||
.sort((a, b) => a.index - b.index)
|
||||
.map((chunk) => chunk.value)
|
||||
.join('')
|
||||
}
|
||||
|
||||
export async function readZoteroDocumentData(zip: JSZip): Promise<string> {
|
||||
const file = zip.file(CUSTOM_PROPERTIES_PATH)
|
||||
return file ? parseZoteroDocumentDataXml(await file.async('string')) : ''
|
||||
}
|
||||
|
||||
export function patchZoteroDocumentDataXml(xml: string | null, data: string): string {
|
||||
const original =
|
||||
xml ??
|
||||
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n' +
|
||||
'<Properties xmlns="http://schemas.openxmlformats.org/officeDocument/2006/custom-properties" ' +
|
||||
'xmlns:vt="http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes"></Properties>'
|
||||
let maxPid = 1
|
||||
for (const property of original.match(PROPERTY_RE) ?? []) {
|
||||
const pid = Number(attrValue(property, 'pid'))
|
||||
if (Number.isSafeInteger(pid)) maxPid = Math.max(maxPid, pid)
|
||||
}
|
||||
const withoutOld = original.replace(PROPERTY_RE, (property) => {
|
||||
const name = attrValue(property, 'name')
|
||||
return name && ZOTERO_PREF_NAME.test(name) ? '' : property
|
||||
})
|
||||
const chunks: string[] = []
|
||||
for (let offset = 0; offset < data.length; offset += 255)
|
||||
chunks.push(data.slice(offset, offset + 255))
|
||||
const properties = chunks
|
||||
.map((value, index) => {
|
||||
const name = `ZOTERO_PREF_${index + 1}`
|
||||
return (
|
||||
`<property fmtid="{D5CDD505-2E9C-101B-9397-08002B2CF9AE}" pid="${++maxPid}"` +
|
||||
` name="${escapeXmlAttr(name)}"><vt:lpwstr>${escapeXmlText(value)}</vt:lpwstr></property>`
|
||||
)
|
||||
})
|
||||
.join('')
|
||||
return withoutOld.replace(/<\/(?:[A-Za-z_][\w.-]*:)?Properties\s*>/, `${properties}$&`)
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { generateParagraphXml, generateTocFieldXml, parseDocx } from '../src/index'
|
||||
import type { GenerateContext } from '../src/index'
|
||||
import { generateParagraphXml, generateTocFieldXml, parseDocx, saveDocx } from '../src/index'
|
||||
import type { GenerateContext, GeneratedBlock } from '../src/index'
|
||||
import { buildDocx } from './helpers/build-docx'
|
||||
|
||||
// TOC entry paragraph as Word writes it: TOC field begin + hyperlink entry
|
||||
@@ -44,6 +44,28 @@ const PAGE_FIELD_PARAGRAPH =
|
||||
'<w:r><w:t>- 8 -</w:t></w:r>' +
|
||||
'<w:r><w:fldChar w:fldCharType="end"/></w:r></w:p>'
|
||||
|
||||
const ZOTERO_CITATION_INSTR =
|
||||
'ADDIN ZOTERO_ITEM CSL_CITATION {"citationID":"citation-1","citationItems":[{"id":1}]}'
|
||||
const ZOTERO_CITATION_PARAGRAPH =
|
||||
'<w:p><w:r><w:t>Evidence </w:t></w:r>' +
|
||||
'<w:r><w:fldChar w:fldCharType="begin"/></w:r>' +
|
||||
`<w:r><w:instrText xml:space="preserve"> ${ZOTERO_CITATION_INSTR} </w:instrText></w:r>` +
|
||||
'<w:r><w:fldChar w:fldCharType="separate"/></w:r>' +
|
||||
'<w:r><w:t>(Smith, 2024)</w:t></w:r>' +
|
||||
'<w:r><w:fldChar w:fldCharType="end"/></w:r>' +
|
||||
'<w:r><w:t>.</w:t></w:r></w:p>'
|
||||
|
||||
const ZOTERO_BIBLIOGRAPHY_INSTR =
|
||||
'ADDIN ZOTERO_BIBL {"uncited":[],"omitted":[],"custom":[]} CSL_BIBLIOGRAPHY'
|
||||
const ZOTERO_BIBLIOGRAPHY_PARAGRAPHS =
|
||||
'<w:p><w:r><w:fldChar w:fldCharType="begin"/></w:r>' +
|
||||
`<w:r><w:instrText xml:space="preserve"> ${ZOTERO_BIBLIOGRAPHY_INSTR} </w:instrText></w:r>` +
|
||||
'<w:r><w:fldChar w:fldCharType="separate"/></w:r>' +
|
||||
'<w:r><w:rPr><w:i/></w:rPr><w:t>Alpha, A. (2024). First study.</w:t></w:r></w:p>' +
|
||||
'<w:p><w:r><w:t>Beta, B. (2023). Second study.</w:t></w:r></w:p>' +
|
||||
'<w:p><w:r><w:t>Gamma, G. (2022). Third study.</w:t></w:r>' +
|
||||
'<w:r><w:fldChar w:fldCharType="end"/></w:r></w:p>'
|
||||
|
||||
describe('field paragraph display model', () => {
|
||||
it('TOC entry becomes a tocLine with title, page number and level', async () => {
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: TOC_ENTRY_PARAGRAPH }))
|
||||
@@ -141,6 +163,101 @@ describe('field paragraph display model', () => {
|
||||
expect(doc.blocks[0].runs?.[0]).toMatchObject({ text: '- 8 -', instrField: 'PAGE' })
|
||||
})
|
||||
|
||||
it('Zotero citation fields remain editable and round-trip as Word ADDIN fields', async () => {
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: ZOTERO_CITATION_PARAGRAPH }))
|
||||
expect(doc.blocks[0].type).toBe('paragraph')
|
||||
expect(doc.blocks[0].runs).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ text: '(Smith, 2024)', instrField: ZOTERO_CITATION_INSTR }),
|
||||
]),
|
||||
)
|
||||
|
||||
const block = doc.blocks[0]
|
||||
const saved = await saveDocx(doc, [{ kind: 'generated', block: block as GeneratedBlock }])
|
||||
const reparsed = await parseDocx(saved)
|
||||
expect(reparsed.blocks[0].runs).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ text: '(Smith, 2024)', instrField: ZOTERO_CITATION_INSTR }),
|
||||
]),
|
||||
)
|
||||
})
|
||||
|
||||
it('keeps styled runs inside one single-paragraph Zotero field', async () => {
|
||||
const xml = ZOTERO_CITATION_PARAGRAPH.replace(
|
||||
'<w:r><w:t>(Smith, 2024)</w:t></w:r>',
|
||||
'<w:r><w:t xml:space="preserve">(Smith, </w:t></w:r>' +
|
||||
'<w:r><w:rPr><w:i/></w:rPr><w:t>2024)</w:t></w:r>',
|
||||
)
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: xml }))
|
||||
const fieldRuns = doc.blocks[0].runs?.filter((run) => run.instrField) ?? []
|
||||
expect(fieldRuns.map((run) => run.zoteroFieldPart)).toEqual(['begin', 'end'])
|
||||
expect(fieldRuns[1].italic).toBe(true)
|
||||
|
||||
const saved = await saveDocx(doc, [
|
||||
{ kind: 'generated', block: doc.blocks[0] as GeneratedBlock },
|
||||
])
|
||||
const reparsed = await parseDocx(saved)
|
||||
const reparsedRuns = reparsed.blocks[0].runs?.filter((run) => run.instrField) ?? []
|
||||
expect(reparsedRuns.map((run) => run.text).join('')).toBe('(Smith, 2024)')
|
||||
expect(new Set(reparsedRuns.map((run) => run.zoteroFieldId)).size).toBe(1)
|
||||
})
|
||||
|
||||
it('keeps a Zotero bibliography spanning multiple paragraphs as one editable field', async () => {
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: ZOTERO_BIBLIOGRAPHY_PARAGRAPHS }))
|
||||
const blocks = doc.blocks.filter((block) => !block.hidden)
|
||||
|
||||
expect(blocks).toHaveLength(3)
|
||||
expect(blocks.map((block) => block.type)).toEqual(['paragraph', 'paragraph', 'paragraph'])
|
||||
expect(blocks.map((block) => block.runs?.map((run) => run.text).join(''))).toEqual([
|
||||
'Alpha, A. (2024). First study.',
|
||||
'Beta, B. (2023). Second study.',
|
||||
'Gamma, G. (2022). Third study.',
|
||||
])
|
||||
const fieldRuns = blocks.flatMap((block) => block.runs ?? [])
|
||||
expect(new Set(fieldRuns.map((run) => run.zoteroFieldId)).size).toBe(1)
|
||||
expect(fieldRuns.map((run) => run.zoteroFieldPart)).toEqual(['begin', 'inside', 'end'])
|
||||
expect(fieldRuns.every((run) => run.instrField === ZOTERO_BIBLIOGRAPHY_INSTR)).toBe(true)
|
||||
expect(fieldRuns[0].italic).toBe(true)
|
||||
|
||||
const generated = blocks.map((block) => ({
|
||||
kind: 'generated' as const,
|
||||
block: {
|
||||
type: 'paragraph' as const,
|
||||
styleId: block.styleId,
|
||||
format: block.format,
|
||||
rawPPr: block.rawPPr,
|
||||
runs: block.runs ?? [],
|
||||
},
|
||||
}))
|
||||
const saved = await saveDocx(doc, generated)
|
||||
const reparsed = await parseDocx(saved)
|
||||
const reparsedBlocks = reparsed.blocks.filter((block) => !block.hidden)
|
||||
expect(reparsedBlocks.map((block) => block.runs?.map((run) => run.text).join(''))).toEqual([
|
||||
'Alpha, A. (2024). First study.',
|
||||
'Beta, B. (2023). Second study.',
|
||||
'Gamma, G. (2022). Third study.',
|
||||
])
|
||||
const reparsedRuns = reparsedBlocks.flatMap((block) => block.runs ?? [])
|
||||
expect(new Set(reparsedRuns.map((run) => run.zoteroFieldId)).size).toBe(1)
|
||||
expect(reparsedRuns.map((run) => run.zoteroFieldPart)).toEqual(['begin', 'inside', 'end'])
|
||||
})
|
||||
|
||||
it('does not merge an inline citation with a cross-paragraph bibliography', async () => {
|
||||
const doc = await parseDocx(
|
||||
await buildDocx({ bodyXml: ZOTERO_CITATION_PARAGRAPH + ZOTERO_BIBLIOGRAPHY_PARAGRAPHS }),
|
||||
)
|
||||
const blocks = doc.blocks.filter((block) => !block.hidden)
|
||||
const citationId = blocks[0].runs?.find((run) => run.instrField)?.zoteroFieldId
|
||||
const bibliographyIds = blocks
|
||||
.slice(1)
|
||||
.flatMap((block) => block.runs ?? [])
|
||||
.map((run) => run.zoteroFieldId)
|
||||
|
||||
expect(citationId).toBeDefined()
|
||||
expect(new Set(bibliographyIds).size).toBe(1)
|
||||
expect(bibliographyIds[0]).not.toBe(citationId)
|
||||
})
|
||||
|
||||
it('a resultless INCLUDEPICTURE text field keeps spaces and run metrics (public issue #118)', async () => {
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: INCLUDEPICTURE_PARAGRAPH }))
|
||||
const block = doc.blocks[0]
|
||||
@@ -555,7 +672,7 @@ describe('mixed-size text fields (manual drop cap)', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('citation text fields (ADDIN ZOTERO_ITEM in a justified body paragraph)', () => {
|
||||
describe('editable citation fields (ADDIN ZOTERO_ITEM in a justified body paragraph)', () => {
|
||||
const CITATION_PARAGRAPH =
|
||||
'<w:p><w:pPr><w:jc w:val="both"/></w:pPr>' +
|
||||
'<w:r><w:t xml:space="preserve">Published in </w:t></w:r>' +
|
||||
@@ -571,25 +688,30 @@ describe('citation text fields (ADDIN ZOTERO_ITEM in a justified body paragraph)
|
||||
it('keeps the result runs formatted and the paragraph justified', async () => {
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: CITATION_PARAGRAPH }))
|
||||
const block = doc.blocks[0]
|
||||
expect(block.type).toBe('passthrough')
|
||||
const field = block.fieldDisplay!
|
||||
expect(field.kind).toBe('text')
|
||||
expect(field.align).toBe('justify')
|
||||
expect(field.left).toBe('Published in European Radiology, this study (21).')
|
||||
expect(field.runs).toEqual([
|
||||
{ text: 'Published in ' },
|
||||
{ text: 'European Radiology', italic: true },
|
||||
{ text: ', this study ' },
|
||||
{ text: '(21)', italic: true },
|
||||
{ text: '.' },
|
||||
expect(block.type).toBe('paragraph')
|
||||
expect(block.format?.align).toBe('justify')
|
||||
expect(block.runs).toEqual([
|
||||
expect.objectContaining({ text: 'Published in ' }),
|
||||
expect.objectContaining({ text: 'European Radiology', italic: true }),
|
||||
expect.objectContaining({ text: ', this study ' }),
|
||||
expect.objectContaining({
|
||||
text: '(21)',
|
||||
italic: true,
|
||||
instrField: 'ADDIN ZOTERO_ITEM CSL_CITATION {"citationID":"x"}',
|
||||
}),
|
||||
expect.objectContaining({ text: '. ' }),
|
||||
])
|
||||
})
|
||||
|
||||
it('falls back to the plain string when tabs keep the runs from reproducing it', async () => {
|
||||
it('keeps tabs inside the editable field result', async () => {
|
||||
const xml = CITATION_PARAGRAPH.replace('<w:t>(21)</w:t>', '<w:tab/><w:t>(21)</w:t>')
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: xml }))
|
||||
const field = doc.blocks[0].fieldDisplay!
|
||||
expect(field.runs).toBeUndefined()
|
||||
expect(field.left).toBe('Published in European Radiology, this study (21).')
|
||||
const fieldRun = doc.blocks[0].runs?.find((run) => run.instrField)
|
||||
expect(fieldRun).toMatchObject({
|
||||
text: '\t(21)',
|
||||
italic: true,
|
||||
instrField: 'ADDIN ZOTERO_ITEM CSL_CITATION {"citationID":"x"}',
|
||||
zoteroFieldPart: 'single',
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
import JSZip from 'jszip'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { parseDocx, saveDocx } from '../src/index'
|
||||
import { buildDocx } from './helpers/build-docx'
|
||||
|
||||
describe('Zotero document properties', () => {
|
||||
it('creates Word-compatible chunked preferences and reads them back', async () => {
|
||||
const source = await buildDocx({ bodyXml: '<w:p><w:r><w:t>Text</w:t></w:r></w:p>' })
|
||||
const parsed = await parseDocx(source)
|
||||
const data = JSON.stringify({
|
||||
style: 'http://www.zotero.org/styles/apa',
|
||||
value: 'x'.repeat(600),
|
||||
})
|
||||
const saved = await saveDocx(
|
||||
parsed,
|
||||
parsed.blocks
|
||||
.filter((block) => !block.hidden)
|
||||
.map((block) => ({ kind: 'original' as const, docxIndex: block.docxIndex! })),
|
||||
{ zoteroDocumentData: data },
|
||||
)
|
||||
|
||||
const reparsed = await parseDocx(saved)
|
||||
expect(reparsed.zoteroDocumentData).toBe(data)
|
||||
|
||||
const zip = await JSZip.loadAsync(saved)
|
||||
const custom = await zip.file('docProps/custom.xml')!.async('string')
|
||||
expect(custom).toContain('name="ZOTERO_PREF_1"')
|
||||
expect(custom).toContain('name="ZOTERO_PREF_3"')
|
||||
expect(await zip.file('_rels/.rels')!.async('string')).toContain(
|
||||
'relationships/custom-properties',
|
||||
)
|
||||
expect(await zip.file('[Content_Types].xml')!.async('string')).toContain(
|
||||
'officedocument.custom-properties+xml',
|
||||
)
|
||||
})
|
||||
|
||||
it('replaces only Zotero properties and preserves unrelated custom properties', async () => {
|
||||
const customXml =
|
||||
'<?xml version="1.0" encoding="UTF-8"?>' +
|
||||
'<Properties xmlns="http://schemas.openxmlformats.org/officeDocument/2006/custom-properties" ' +
|
||||
'xmlns:vt="http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes">' +
|
||||
'<property fmtid="x" pid="2" name="Owner"><vt:lpwstr>A&B</vt:lpwstr></property>' +
|
||||
'<property fmtid="x" pid="3" name="ZOTERO_PREF_1"><vt:lpwstr>old</vt:lpwstr></property>' +
|
||||
'</Properties>'
|
||||
const source = await buildDocx({
|
||||
bodyXml: '<w:p><w:r><w:t>Text</w:t></w:r></w:p>',
|
||||
extraParts: [
|
||||
{
|
||||
path: 'docProps/custom.xml',
|
||||
xml: customXml,
|
||||
contentType: 'application/vnd.openxmlformats-officedocument.custom-properties+xml',
|
||||
},
|
||||
],
|
||||
})
|
||||
const parsed = await parseDocx(source)
|
||||
expect(parsed.zoteroDocumentData).toBe('old')
|
||||
const saved = await saveDocx(
|
||||
parsed,
|
||||
parsed.blocks
|
||||
.filter((block) => !block.hidden)
|
||||
.map((block) => ({ kind: 'original' as const, docxIndex: block.docxIndex! })),
|
||||
{ zoteroDocumentData: 'new' },
|
||||
)
|
||||
const custom = await (await JSZip.loadAsync(saved)).file('docProps/custom.xml')!.async('string')
|
||||
expect(custom).toContain('name="Owner"')
|
||||
expect(custom).toContain('A&B')
|
||||
expect(custom).toContain('name="ZOTERO_PREF_1"')
|
||||
expect(custom).toContain('>new<')
|
||||
expect(custom).not.toContain('>old<')
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user