qmlbox 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -2,6 +2,11 @@
2
2
  type ThemeFileMap = Record<string, Uint8Array>;
3
3
  type ThemeFiles = Record<string, Uint8Array | string>;
4
4
  type ThemeConfigValue = string | number | boolean;
5
+ type QmlVersion = "auto" | "6.8" | "6" | "2.15" | "2.12" | "2.0" | (string & {});
6
+ interface RenderThemeOptions {
7
+ entryFile?: string;
8
+ qmlVersion?: QmlVersion;
9
+ }
5
10
  interface SddmUser {
6
11
  name: string;
7
12
  realName?: string;
@@ -38,6 +43,8 @@ interface QmlViewerOptions {
38
43
  /** Directory containing qtloader.js, qml_engine.js and qml_engine.wasm. Defaults to ./wasm/. */
39
44
  wasmBaseUrl?: string;
40
45
  sddmConfig?: SddmMockConfig;
46
+ /** Target QML version for standard Qt imports ("auto" preserves source imports). */
47
+ qmlVersion?: QmlVersion;
41
48
  /** Positive upper bound for the viewer's device pixel ratio. Defaults to 2. */
42
49
  maxPixelRatio?: number;
43
50
  onProgress?: (percent: number) => void;
@@ -63,6 +70,9 @@ type IniFile = Record<string, IniSection>;
63
70
  declare function parseIni(source: string): IniFile;
64
71
  declare function parseThemeConfig(source: string): Record<string, string>;
65
72
 
73
+ declare const SUPPORTED_QML_VERSIONS: readonly ["auto", "6.8", "2.15", "2.12", "2.0"];
74
+ declare function transformQmlImports(source: string, version: QmlVersion): string;
75
+
66
76
  declare class QmlViewer {
67
77
  private readonly options;
68
78
  private readonly maxPixelRatio;
@@ -74,14 +84,19 @@ declare class QmlViewer {
74
84
  private observer?;
75
85
  private sddmConfig?;
76
86
  private themeConfig?;
87
+ private qmlVersion;
77
88
  private generation;
78
89
  private destroyed;
79
90
  private inViewport;
80
91
  constructor(options: QmlViewerOptions);
81
92
  init(): Promise<void>;
82
93
  private start;
83
- renderThemeFiles(input: ThemeFiles, entryFile?: string): Promise<void>;
84
- renderCode(qmlSource: string): Promise<void>;
94
+ renderThemeFiles(input: ThemeFiles, entryOrOptions?: string | RenderThemeOptions): Promise<void>;
95
+ renderCode(qmlSource: string, qmlVersion?: QmlVersion): Promise<void>;
96
+ /** Return the active default QML target version used when rendering. */
97
+ getQmlVersion(): QmlVersion;
98
+ /** Set the default QML target version for subsequent renders. */
99
+ setQmlVersion(version: QmlVersion): void;
85
100
  /** Update the mock environment used by the current and subsequent previews. */
86
101
  setSddmConfig(config: SddmMockConfig): void;
87
102
  destroy(): void;
@@ -91,4 +106,4 @@ declare class QmlViewer {
91
106
  private stop;
92
107
  }
93
108
 
94
- export { type GitHubRepoOptions, type IniFile, QmlViewer, type QmlViewerOptions, type SddmMockConfig, type SddmSession, type SddmUser, type ThemeConfigValue, type ThemeFileMap, type ThemeFiles, fromCodeString, fromFolderInput, fromGitHubRepo, fromSingleFile, fromZipFile, parseIni, parseThemeConfig };
109
+ export { type GitHubRepoOptions, type IniFile, type QmlVersion, QmlViewer, type QmlViewerOptions, type RenderThemeOptions, SUPPORTED_QML_VERSIONS, type SddmMockConfig, type SddmSession, type SddmUser, type ThemeConfigValue, type ThemeFileMap, type ThemeFiles, fromCodeString, fromFolderInput, fromGitHubRepo, fromSingleFile, fromZipFile, parseIni, parseThemeConfig, transformQmlImports };
package/dist/index.js CHANGED
@@ -173,16 +173,29 @@ async function fromGitHubRepo(url, options = {}) {
173
173
  if (!blobs.length) throw new Error(`GitHub returned no regular files${folder ? ` in "${folder}"` : ""}.`);
174
174
  const files = newFileMap();
175
175
  const downloads = /* @__PURE__ */ new Map();
176
+ const rawBase = `https://raw.githubusercontent.com/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/${encodeURIComponent(ref)}`;
176
177
  let next = 0;
177
178
  async function downloadFiles() {
178
179
  while (!signal.aborted && next < blobs.length) {
179
180
  const { path, sha } = blobs[next++];
181
+ const normalized = normalizePath(path);
180
182
  let download = downloads.get(sha);
181
183
  if (!download) {
182
- download = request(`/git/blobs/${encodeURIComponent(sha)}`, true).then((response) => response.arrayBuffer()).then((buffer) => new Uint8Array(buffer));
184
+ if (!options.token) {
185
+ const fullRepoPath = prefix ? `${prefix}${normalized}` : normalized;
186
+ const rawUrl = `${rawBase}/${fullRepoPath.split("/").map(encodeURIComponent).join("/")}`;
187
+ download = fetch(rawUrl, { signal }).then(async (response) => {
188
+ if (!response.ok) {
189
+ throw new GitHubRequestError(response.status, `GitHub returned HTTP ${response.status} for ${fullRepoPath}.`);
190
+ }
191
+ return new Uint8Array(await response.arrayBuffer());
192
+ });
193
+ } else {
194
+ download = request(`/git/blobs/${encodeURIComponent(sha)}`, true).then((response) => response.arrayBuffer()).then((buffer) => new Uint8Array(buffer));
195
+ }
183
196
  downloads.set(sha, download);
184
197
  }
185
- insertFile(files, normalizePath(path), await download);
198
+ insertFile(files, normalized, await download);
186
199
  }
187
200
  signal.throwIfAborted();
188
201
  }
@@ -195,6 +208,119 @@ async function fromGitHubRepo(url, options = {}) {
195
208
  return files;
196
209
  }
197
210
 
211
+ // src/qmlShims.ts
212
+ var FALLBACK_QML_SHIMS = {
213
+ "QtMultimedia/AudioOutput.qml": "import QtQuick\n\nQtObject {\n property real volume: 1.0\n property bool muted: false\n property var device: null\n}\n",
214
+ "QtMultimedia/MediaDevices.qml": "import QtQuick\n\nQtObject {\n readonly property var audioInputs: []\n readonly property var audioOutputs: []\n readonly property var videoInputs: []\n readonly property var defaultAudioInput: null\n readonly property var defaultAudioOutput: null\n readonly property var defaultVideoInput: null\n}\n",
215
+ "QtMultimedia/MediaPlayer.qml": 'import QtQuick\n\nQtObject {\n id: player\n\n enum Loops {\n Once = 1,\n Infinite = -1\n }\n enum PlaybackState {\n StoppedState = 0,\n PlayingState = 1,\n PausedState = 2\n }\n enum MediaStatus {\n NoMedia = 0,\n LoadingMedia = 1,\n LoadedMedia = 2,\n StalledMedia = 3,\n BufferingMedia = 4,\n BufferedMedia = 5,\n EndOfMedia = 6,\n InvalidMedia = 7\n }\n enum Error {\n NoError = 0,\n ResourceError = 1,\n FormatError = 2,\n NetworkError = 3,\n AccessDeniedError = 4\n }\n\n property url source: ""\n property var videoOutput: null\n property var audioOutput: null\n property bool autoPlay: false\n property real playbackRate: 1.0\n property int loops: 1\n property bool muted: false\n property real volume: 1.0\n property int playbackState: 0\n readonly property bool playing: playbackState === 1\n property int mediaStatus: 0\n property int position: 0\n property int duration: 0\n property bool hasVideo: false\n property bool hasAudio: false\n property int error: 0\n property string errorString: ""\n\n onSourceChanged: {\n syncVideoOutput()\n if (autoPlay && source.toString() !== "")\n play()\n }\n\n onVideoOutputChanged: syncVideoOutput()\n\n function syncVideoOutput() {\n if (!videoOutput)\n return\n if ("source" in videoOutput)\n videoOutput.source = source\n }\n\n function play() {\n const uri = source.toString()\n if (uri === "")\n return\n syncVideoOutput()\n const isImage = /\\.(gif|png|jpe?g|webp|svg|bmp)(\\?|#|$)/i.test(uri)\n hasVideo = isImage\n mediaStatus = 2\n playbackState = isImage ? 1 : 0\n }\n\n function pause() {\n if (playbackState === 1)\n playbackState = 2\n }\n\n function stop() {\n playbackState = 0\n position = 0\n }\n\n function setPosition(pos) {\n position = pos\n }\n}\n',
216
+ "QtMultimedia/VideoOutput.qml": 'import QtQuick\n\nItem {\n id: output\n\n enum FillMode {\n Stretch = 0,\n PreserveAspectFit = 1,\n PreserveAspectCrop = 2\n }\n\n property int fillMode: Image.PreserveAspectFit\n property int orientation: 0\n property url source: ""\n property rect contentRect: Qt.rect(0, 0, width, height)\n property rect sourceRect: Qt.rect(0, 0, width, height)\n\n readonly property bool isImageSource: /\\.(gif|png|jpe?g|webp|svg|bmp)(\\?|#|$)/i.test(source.toString())\n\n AnimatedImage {\n id: fallbackImage\n anchors.fill: parent\n source: output.isImageSource ? output.source : ""\n fillMode: output.fillMode\n visible: output.isImageSource && status === AnimatedImage.Ready\n playing: visible\n clip: true\n }\n}\n',
217
+ "QtMultimedia/qmldir": "module QtMultimedia\n\nMediaPlayer 1.0 MediaPlayer.qml\nMediaPlayer 5.0 MediaPlayer.qml\nMediaPlayer 5.12 MediaPlayer.qml\nMediaPlayer 5.15 MediaPlayer.qml\nMediaPlayer 6.0 MediaPlayer.qml\nVideoOutput 1.0 VideoOutput.qml\nVideoOutput 5.0 VideoOutput.qml\nVideoOutput 5.12 VideoOutput.qml\nVideoOutput 5.15 VideoOutput.qml\nVideoOutput 6.0 VideoOutput.qml\nAudioOutput 1.0 AudioOutput.qml\nAudioOutput 6.0 AudioOutput.qml\nMediaDevices 1.0 MediaDevices.qml\nMediaDevices 6.0 MediaDevices.qml\n",
218
+ "Qt5Compat/GraphicalEffects/BrightnessContrast.qml": "import QtQuick\nimport QtQuick.Effects\n\nMultiEffect {\n property bool cached: false\n}\n",
219
+ "Qt5Compat/GraphicalEffects/ColorOverlay.qml": 'import QtQuick\nimport QtQuick.Effects\n\nMultiEffect {\n property color color: "#000000"\n property bool cached: false\n\n colorization: 1.0\n colorizationColor: color\n}\n',
220
+ "Qt5Compat/GraphicalEffects/Colorize.qml": "import QtQuick\nimport QtQuick.Effects\n\nMultiEffect {\n property real hue: 0.0\n property real saturation: 0.5\n property real lightness: 0.0\n property bool cached: false\n\n colorization: 1.0\n colorizationColor: Qt.hsla(hue, saturation, Math.max(0.0, Math.min(1.0, 0.5 + lightness * 0.5)), 1.0)\n}\n",
221
+ "Qt5Compat/GraphicalEffects/Desaturate.qml": "import QtQuick\nimport QtQuick.Effects\n\nMultiEffect {\n property real desaturation: 0.0\n property bool cached: false\n\n saturation: -Math.max(0.0, Math.min(1.0, desaturation))\n}\n",
222
+ "Qt5Compat/GraphicalEffects/DropShadow.qml": 'import QtQuick\nimport QtQuick.Effects\n\nMultiEffect {\n property color color: "#80000000"\n property real horizontalOffset: 0\n property real verticalOffset: 0\n property real radius: 0\n property int samples: 9\n property real spread: 0\n property bool fast: false\n property bool transparentBorder: true\n property bool cached: false\n\n shadowEnabled: true\n shadowColor: color\n shadowHorizontalOffset: horizontalOffset\n shadowVerticalOffset: verticalOffset\n shadowBlur: Math.min(1.0, Math.max(0.0, radius / 32.0))\n shadowScale: 1.0 + Math.max(0.0, spread) * 0.2\n autoPaddingEnabled: transparentBorder\n}\n',
223
+ "Qt5Compat/GraphicalEffects/FastBlur.qml": "import QtQuick\nimport QtQuick.Effects\n\nMultiEffect {\n property real radius: 0\n property bool transparentBorder: false\n property bool cached: false\n\n blurEnabled: radius > 0\n blurMax: 64\n blur: Math.min(1.0, Math.max(0.0, radius / 64.0))\n autoPaddingEnabled: transparentBorder\n}\n",
224
+ "Qt5Compat/GraphicalEffects/GaussianBlur.qml": "import QtQuick\nimport QtQuick.Effects\n\nMultiEffect {\n property real radius: 0\n property int samples: 9\n property real deviation: 0\n property bool transparentBorder: false\n property bool cached: false\n\n blurEnabled: radius > 0\n blurMax: 64\n blur: Math.min(1.0, Math.max(0.0, radius / 64.0))\n autoPaddingEnabled: transparentBorder\n}\n",
225
+ "Qt5Compat/GraphicalEffects/Glow.qml": 'import QtQuick\nimport QtQuick.Effects\n\nMultiEffect {\n property color color: "#ffffff"\n property real radius: 0\n property int samples: 9\n property real spread: 0\n property bool fast: false\n property bool transparentBorder: true\n property bool cached: false\n\n shadowEnabled: true\n shadowColor: color\n shadowHorizontalOffset: 0\n shadowVerticalOffset: 0\n shadowBlur: Math.min(1.0, Math.max(0.0, radius / 32.0))\n shadowScale: 1.0 + Math.max(0.0, spread) * 0.2\n autoPaddingEnabled: transparentBorder\n}\n',
226
+ "Qt5Compat/GraphicalEffects/HueSaturation.qml": "import QtQuick\nimport QtQuick.Effects\n\nMultiEffect {\n property real hue: 0.0\n property bool cached: false\n}\n",
227
+ "Qt5Compat/GraphicalEffects/LinearGradient.qml": 'import QtQuick\n\nItem {\n id: root\n property point start: Qt.point(0, 0)\n property point end: Qt.point(0, height)\n property var source: null\n property bool cached: false\n default property list<GradientStop> stops\n\n Canvas {\n anchors.fill: parent\n onPaint: {\n const ctx = getContext("2d")\n ctx.clearRect(0, 0, width, height)\n const g = ctx.createLinearGradient(root.start.x, root.start.y, root.end.x, root.end.y)\n for (let i = 0; i < root.stops.length; i++) {\n const s = root.stops[i]\n g.addColorStop(Math.max(0, Math.min(1, s.position)), s.color.toString())\n }\n ctx.fillStyle = g\n ctx.fillRect(0, 0, width, height)\n }\n onWidthChanged: requestPaint()\n onHeightChanged: requestPaint()\n }\n}\n',
228
+ "Qt5Compat/GraphicalEffects/OpacityMask.qml": "import QtQuick\nimport QtQuick.Effects\n\nMultiEffect {\n property bool invert: false\n property bool cached: false\n\n maskEnabled: true\n maskInverted: invert\n}\n",
229
+ "Qt5Compat/GraphicalEffects/RadialGradient.qml": 'import QtQuick\n\nItem {\n id: root\n property real horizontalOffset: 0\n property real verticalOffset: 0\n property real horizontalRadius: width / 2\n property real verticalRadius: height / 2\n property real angle: 0\n property var source: null\n property bool cached: false\n default property list<GradientStop> stops\n\n Canvas {\n anchors.fill: parent\n onPaint: {\n const ctx = getContext("2d")\n ctx.clearRect(0, 0, width, height)\n const cx = width / 2 + root.horizontalOffset\n const cy = height / 2 + root.verticalOffset\n const r = Math.max(1, Math.max(root.horizontalRadius, root.verticalRadius))\n const g = ctx.createRadialGradient(cx, cy, 0, cx, cy, r)\n for (let i = 0; i < root.stops.length; i++) {\n const s = root.stops[i]\n g.addColorStop(Math.max(0, Math.min(1, s.position)), s.color.toString())\n }\n ctx.fillStyle = g\n ctx.fillRect(0, 0, width, height)\n }\n onWidthChanged: requestPaint()\n onHeightChanged: requestPaint()\n }\n}\n',
230
+ "Qt5Compat/GraphicalEffects/RectangularGlow.qml": "import QtQuick\n\nRectangle {\n property real glowRadius: 0\n property real spread: 0\n property real cornerRadius: 0\n property bool cached: false\n\n radius: cornerRadius + glowRadius * 0.5\n opacity: 0.45\n}\n",
231
+ "Qt5Compat/GraphicalEffects/ThresholdMask.qml": "import QtQuick\nimport QtQuick.Effects\n\nMultiEffect {\n property real threshold: 0.5\n property real spread: 0.0\n property bool cached: false\n\n maskEnabled: true\n maskThresholdMin: Math.max(0.0, threshold - spread)\n maskSpreadAtMin: Math.max(0.0, spread)\n}\n",
232
+ "Qt5Compat/GraphicalEffects/qmldir": "module Qt5Compat.GraphicalEffects\n\nBrightnessContrast 1.0 BrightnessContrast.qml\nBrightnessContrast 1.15 BrightnessContrast.qml\nBrightnessContrast 6.0 BrightnessContrast.qml\nColorize 1.0 Colorize.qml\nColorize 1.15 Colorize.qml\nColorize 6.0 Colorize.qml\nColorOverlay 1.0 ColorOverlay.qml\nColorOverlay 1.15 ColorOverlay.qml\nColorOverlay 6.0 ColorOverlay.qml\nDesaturate 1.0 Desaturate.qml\nDesaturate 1.15 Desaturate.qml\nDesaturate 6.0 Desaturate.qml\nDropShadow 1.0 DropShadow.qml\nDropShadow 1.15 DropShadow.qml\nDropShadow 6.0 DropShadow.qml\nFastBlur 1.0 FastBlur.qml\nFastBlur 1.15 FastBlur.qml\nFastBlur 6.0 FastBlur.qml\nGaussianBlur 1.0 GaussianBlur.qml\nGaussianBlur 1.15 GaussianBlur.qml\nGaussianBlur 6.0 GaussianBlur.qml\nGlow 1.0 Glow.qml\nGlow 1.15 Glow.qml\nGlow 6.0 Glow.qml\nHueSaturation 1.0 HueSaturation.qml\nHueSaturation 1.15 HueSaturation.qml\nHueSaturation 6.0 HueSaturation.qml\nLinearGradient 1.0 LinearGradient.qml\nLinearGradient 1.15 LinearGradient.qml\nLinearGradient 6.0 LinearGradient.qml\nOpacityMask 1.0 OpacityMask.qml\nOpacityMask 1.15 OpacityMask.qml\nOpacityMask 6.0 OpacityMask.qml\nRadialGradient 1.0 RadialGradient.qml\nRadialGradient 1.15 RadialGradient.qml\nRadialGradient 6.0 RadialGradient.qml\nRectangularGlow 1.0 RectangularGlow.qml\nRectangularGlow 1.15 RectangularGlow.qml\nRectangularGlow 6.0 RectangularGlow.qml\nThresholdMask 1.0 ThresholdMask.qml\nThresholdMask 1.15 ThresholdMask.qml\nThresholdMask 6.0 ThresholdMask.qml\n",
233
+ "QtGraphicalEffects/qmldir": "module QtGraphicalEffects\n\nBrightnessContrast 1.0 ../Qt5Compat/GraphicalEffects/BrightnessContrast.qml\nBrightnessContrast 1.15 ../Qt5Compat/GraphicalEffects/BrightnessContrast.qml\nColorize 1.0 ../Qt5Compat/GraphicalEffects/Colorize.qml\nColorize 1.15 ../Qt5Compat/GraphicalEffects/Colorize.qml\nColorOverlay 1.0 ../Qt5Compat/GraphicalEffects/ColorOverlay.qml\nColorOverlay 1.15 ../Qt5Compat/GraphicalEffects/ColorOverlay.qml\nDesaturate 1.0 ../Qt5Compat/GraphicalEffects/Desaturate.qml\nDesaturate 1.15 ../Qt5Compat/GraphicalEffects/Desaturate.qml\nDropShadow 1.0 ../Qt5Compat/GraphicalEffects/DropShadow.qml\nDropShadow 1.15 ../Qt5Compat/GraphicalEffects/DropShadow.qml\nFastBlur 1.0 ../Qt5Compat/GraphicalEffects/FastBlur.qml\nFastBlur 1.15 ../Qt5Compat/GraphicalEffects/FastBlur.qml\nGaussianBlur 1.0 ../Qt5Compat/GraphicalEffects/GaussianBlur.qml\nGaussianBlur 1.15 ../Qt5Compat/GraphicalEffects/GaussianBlur.qml\nGlow 1.0 ../Qt5Compat/GraphicalEffects/Glow.qml\nGlow 1.15 ../Qt5Compat/GraphicalEffects/Glow.qml\nHueSaturation 1.0 ../Qt5Compat/GraphicalEffects/HueSaturation.qml\nHueSaturation 1.15 ../Qt5Compat/GraphicalEffects/HueSaturation.qml\nLinearGradient 1.0 ../Qt5Compat/GraphicalEffects/LinearGradient.qml\nLinearGradient 1.15 ../Qt5Compat/GraphicalEffects/LinearGradient.qml\nOpacityMask 1.0 ../Qt5Compat/GraphicalEffects/OpacityMask.qml\nOpacityMask 1.15 ../Qt5Compat/GraphicalEffects/OpacityMask.qml\nRadialGradient 1.0 ../Qt5Compat/GraphicalEffects/RadialGradient.qml\nRadialGradient 1.15 ../Qt5Compat/GraphicalEffects/RadialGradient.qml\nRectangularGlow 1.0 ../Qt5Compat/GraphicalEffects/RectangularGlow.qml\nRectangularGlow 1.15 ../Qt5Compat/GraphicalEffects/RectangularGlow.qml\nThresholdMask 1.0 ../Qt5Compat/GraphicalEffects/ThresholdMask.qml\nThresholdMask 1.15 ../Qt5Compat/GraphicalEffects/ThresholdMask.qml\n",
234
+ "QtQuick/VirtualKeyboard/InputPanel.qml": 'import QtQuick\nimport QtQuick.Controls\nimport QtQuick.Layouts\n\nItem {\n id: panel\n property bool active: false\n property bool externalLanguageSwitchEnabled: false\n signal externalLanguageSwitchRequested(var localeList, int currentIndex)\n\n implicitWidth: 640\n implicitHeight: 210\n visible: active\n\n readonly property var rows: [\n ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "\u232B"],\n ["q", "w", "e", "r", "t", "y", "u", "i", "o", "p"],\n ["a", "s", "d", "f", "g", "h", "j", "k", "l", "\u21B5"],\n ["\u21E7", "z", "x", "c", "v", "b", "n", "m", "Space"]\n ]\n property bool shifted: false\n\n function dispatchKey(label) {\n if (label === "\u21E7") {\n shifted = !shifted\n return\n }\n if (label === "\u232B") {\n const target = panel.Window.activeFocusItem\n if (target && typeof target.text === "string" && typeof target.cursorPosition === "number") {\n const pos = target.cursorPosition\n if (pos > 0) {\n target.text = target.text.slice(0, pos - 1) + target.text.slice(pos)\n target.cursorPosition = pos - 1\n }\n }\n return\n }\n if (label === "\u21B5") {\n const target = panel.Window.activeFocusItem\n if (target && typeof target.accepted === "function")\n target.accepted()\n return\n }\n const ch = label === "Space" ? " " : (shifted ? label.toUpperCase() : label)\n const target = panel.Window.activeFocusItem\n if (target && typeof target.text === "string" && typeof target.cursorPosition === "number") {\n const pos = target.cursorPosition\n target.text = target.text.slice(0, pos) + ch + target.text.slice(pos)\n target.cursorPosition = pos + ch.length\n }\n }\n\n Rectangle {\n anchors.fill: parent\n radius: 10\n color: "#e6181d25"\n border.color: "#384454"\n border.width: 1\n\n ColumnLayout {\n anchors.fill: parent\n anchors.margins: 10\n spacing: 6\n\n Repeater {\n model: panel.rows\n RowLayout {\n Layout.fillWidth: true\n Layout.fillHeight: true\n spacing: 6\n\n Repeater {\n model: modelData\n Button {\n Layout.fillWidth: true\n Layout.fillHeight: true\n Layout.preferredWidth: modelData === "Space" ? 160 : 40\n text: (modelData.length === 1 && panel.shifted) ? modelData.toUpperCase() : modelData\n focusPolicy: Qt.NoFocus\n onClicked: panel.dispatchKey(modelData)\n }\n }\n }\n }\n }\n }\n}\n',
235
+ "QtQuick/VirtualKeyboard/qmldir": "module QtQuick.VirtualKeyboard\n\nInputPanel 2.0 InputPanel.qml\nInputPanel 2.12 InputPanel.qml\nInputPanel 2.15 InputPanel.qml\nInputPanel 6.0 InputPanel.qml\n"
236
+ };
237
+
238
+ // src/qmlVersion.ts
239
+ var SUPPORTED_QML_VERSIONS = ["auto", "6.8", "2.15", "2.12", "2.0"];
240
+ var QT_QUICK_2_MODULES = /* @__PURE__ */ new Set([
241
+ "QtQuick",
242
+ "QtQuick.Window",
243
+ "QtQuick.Controls",
244
+ "QtQuick.Controls.Basic",
245
+ "QtQuick.VirtualKeyboard",
246
+ "QtQml",
247
+ "QtQml.Models",
248
+ "QtQml.WorkerScript"
249
+ ]);
250
+ var QT_LAYOUT_MODULES = /* @__PURE__ */ new Set([
251
+ "QtQuick.Layouts",
252
+ "QtQuick.Shapes"
253
+ ]);
254
+ var QT6_ONLY_OR_UNVERSIONED_MODULES = /* @__PURE__ */ new Set([
255
+ "QtQuick.Effects"
256
+ ]);
257
+ var GRAPHICAL_EFFECT_MODULES = /* @__PURE__ */ new Set([
258
+ "QtGraphicalEffects",
259
+ "Qt5Compat.GraphicalEffects"
260
+ ]);
261
+ var MULTIMEDIA_MODULES = /* @__PURE__ */ new Set([
262
+ "QtMultimedia"
263
+ ]);
264
+ var IMPORT_LINE = /^(\s*import\s+)([A-Za-z_][\w.]*)(?:\s+(\d+(?:\.\d+)?))?(\s+as\s+[A-Za-z_]\w*)?(\s*;?\s*(?:\/\/.*)?)$/;
265
+ function parseTargetVersion(version) {
266
+ const trimmed = version.trim();
267
+ if (!trimmed || trimmed.toLowerCase() === "auto") return { mode: "auto" };
268
+ if (trimmed === "6" || /^6\.\d+$/.test(trimmed)) return { mode: "qt6" };
269
+ if (trimmed === "5" || /^5\.\d+$/.test(trimmed)) {
270
+ const minor = trimmed === "5" ? 15 : Number(trimmed.split(".")[1]);
271
+ const clamped = Math.max(0, Math.min(15, Number.isFinite(minor) ? minor : 15));
272
+ return { mode: "qtquick2", version: `2.${clamped}`, minor: clamped };
273
+ }
274
+ const qtQuickMatch = /^2\.(\d+)$/.exec(trimmed);
275
+ if (qtQuickMatch) {
276
+ const minor = Number(qtQuickMatch[1]);
277
+ return { mode: "qtquick2", version: trimmed, minor };
278
+ }
279
+ throw new RangeError(`Unsupported QML version "${version}". Use "auto", "6.8", "2.15", "2.12", or "2.0".`);
280
+ }
281
+ function normalizeQmlVersion(version) {
282
+ if (!version) return "auto";
283
+ const parsed = parseTargetVersion(version);
284
+ if (parsed.mode === "auto") return "auto";
285
+ if (parsed.mode === "qt6") return version.trim() === "6" ? "6" : version.trim();
286
+ return parsed.version;
287
+ }
288
+ function transformQmlImports(source, version) {
289
+ const target = parseTargetVersion(version);
290
+ if (target.mode === "auto") return source;
291
+ return source.split(/\r?\n/).map((line) => {
292
+ const match = IMPORT_LINE.exec(line);
293
+ if (!match) return line;
294
+ const [, prefix, moduleName, , alias = "", suffix = ""] = match;
295
+ if (!prefix || !moduleName) return line;
296
+ if (target.mode === "qt6") {
297
+ if (GRAPHICAL_EFFECT_MODULES.has(moduleName)) {
298
+ return `${prefix}Qt5Compat.GraphicalEffects${alias}${suffix}`;
299
+ }
300
+ if (QT_QUICK_2_MODULES.has(moduleName) || QT_LAYOUT_MODULES.has(moduleName) || QT6_ONLY_OR_UNVERSIONED_MODULES.has(moduleName) || MULTIMEDIA_MODULES.has(moduleName)) {
301
+ return `${prefix}${moduleName}${alias}${suffix}`;
302
+ }
303
+ return line;
304
+ }
305
+ if (QT_QUICK_2_MODULES.has(moduleName)) {
306
+ return `${prefix}${moduleName} ${target.version}${alias}${suffix}`;
307
+ }
308
+ if (QT_LAYOUT_MODULES.has(moduleName)) {
309
+ const layoutMinor = Math.min(target.minor, 15);
310
+ return `${prefix}${moduleName} 1.${layoutMinor}${alias}${suffix}`;
311
+ }
312
+ if (GRAPHICAL_EFFECT_MODULES.has(moduleName)) {
313
+ const effectMinor = target.minor >= 15 ? "1.15" : "1.0";
314
+ return `${prefix}${moduleName} ${effectMinor}${alias}${suffix}`;
315
+ }
316
+ if (MULTIMEDIA_MODULES.has(moduleName)) {
317
+ const mediaVersion = target.minor >= 15 ? "5.15" : target.minor >= 12 ? "5.12" : "5.0";
318
+ return `${prefix}${moduleName} ${mediaVersion}${alias}${suffix}`;
319
+ }
320
+ return line;
321
+ }).join("\n");
322
+ }
323
+
198
324
  // src/sddmParser.ts
199
325
  var decoder = new TextDecoder();
200
326
  function parseIni(source) {
@@ -277,7 +403,8 @@ function resolveTheme(files, entryFile) {
277
403
  throw new Error(`QML entry file "${entry}" was not found.`);
278
404
  }
279
405
  const root = metadataPath ? metadataRoot : directory(entry);
280
- const configPath = root + normalizePath(metadata.configFile || "theme.conf");
406
+ const declaredConfigPath = root + normalizePath(metadata.configFile || "theme.conf");
407
+ const configPath = Object.hasOwn(files, declaredConfigPath) ? declaredConfigPath : Object.hasOwn(files, `${root}theme.conf`) ? `${root}theme.conf` : paths.filter((path) => path.startsWith(root) && /\.conf$/i.test(path)).sort()[0] ?? declaredConfigPath;
281
408
  const config = Object.assign(
282
409
  parseThemeConfig(readText(files, configPath)),
283
410
  parseThemeConfig(readText(files, `${configPath}.user`))
@@ -401,6 +528,8 @@ async function loadWasmRuntime(frame, baseUrl, maxPixelRatio, signal, progress,
401
528
  }
402
529
 
403
530
  // src/index.ts
531
+ var decoder2 = new TextDecoder();
532
+ var encoder2 = new TextEncoder();
404
533
  var workspace = "/workspace";
405
534
  var defaults = {
406
535
  hostName: "qml-preview",
@@ -441,6 +570,7 @@ var QmlViewer = class {
441
570
  this.options = options;
442
571
  this.document = options.container.ownerDocument;
443
572
  this.sddmConfig = options.sddmConfig;
573
+ this.qmlVersion = normalizeQmlVersion(options.qmlVersion);
444
574
  this.maxPixelRatio = options.maxPixelRatio ?? 2;
445
575
  if (!Number.isFinite(this.maxPixelRatio) || this.maxPixelRatio <= 0) {
446
576
  throw new RangeError("maxPixelRatio must be a positive finite number.");
@@ -456,6 +586,7 @@ var QmlViewer = class {
456
586
  observer;
457
587
  sddmConfig;
458
588
  themeConfig;
589
+ qmlVersion;
459
590
  generation = 0;
460
591
  destroyed = false;
461
592
  inViewport = true;
@@ -505,12 +636,15 @@ var QmlViewer = class {
505
636
  throw error;
506
637
  }
507
638
  }
508
- async renderThemeFiles(input, entryFile) {
639
+ async renderThemeFiles(input, entryOrOptions) {
640
+ const options = typeof entryOrOptions === "string" ? { entryFile: entryOrOptions } : entryOrOptions ?? {};
641
+ let targetVersion;
509
642
  let prepared;
510
643
  let theme;
511
644
  try {
645
+ targetVersion = normalizeQmlVersion(options.qmlVersion ?? this.qmlVersion);
512
646
  prepared = prepareFiles(input);
513
- theme = resolveTheme(prepared.files, entryFile);
647
+ theme = resolveTheme(prepared.files, options.entryFile);
514
648
  } catch (error2) {
515
649
  this.reportError(messageOf(error2));
516
650
  throw error2;
@@ -524,7 +658,24 @@ var QmlViewer = class {
524
658
  if (!runtime.clearWorkspace()) throw new Error("Could not clear the Qt workspace.");
525
659
  runtime.FS.mkdirTree(root);
526
660
  for (const dir of prepared.directories) runtime.FS.mkdirTree(`${root}/${dir}`);
527
- for (const [path, data] of Object.entries(prepared.files)) runtime.FS.writeFile(`${root}/${path}`, data);
661
+ for (const [path, data] of Object.entries(prepared.files)) {
662
+ const content = targetVersion !== "auto" && /\.qml$/i.test(path) ? encoder2.encode(transformQmlImports(typeof data === "string" ? data : decoder2.decode(data), targetVersion)) : data;
663
+ runtime.FS.writeFile(`${root}/${path}`, content);
664
+ }
665
+ const importRoot = theme.root ? `${root}/${theme.root.slice(0, -1)}` : root;
666
+ const shimDirs = /* @__PURE__ */ new Set();
667
+ for (const [shimPath, shimSource] of Object.entries(FALLBACK_QML_SHIMS)) {
668
+ if (Object.hasOwn(prepared.files, `${theme.root}${shimPath}`)) continue;
669
+ const slash = shimPath.lastIndexOf("/");
670
+ if (slash > 0) {
671
+ const dir = `${importRoot}/${shimPath.slice(0, slash)}`;
672
+ if (!shimDirs.has(dir)) {
673
+ runtime.FS.mkdirTree(dir);
674
+ shimDirs.add(dir);
675
+ }
676
+ }
677
+ runtime.FS.writeFile(`${importRoot}/${shimPath}`, shimSource);
678
+ }
528
679
  runtime.updateSddmConfig(config);
529
680
  this.themeConfig = theme.config;
530
681
  } catch (error2) {
@@ -536,8 +687,17 @@ var QmlViewer = class {
536
687
  const error = runtime.loadMainQml(`${root}/${theme.entryFile}`, importDirectory);
537
688
  if (error) throw new Error(error);
538
689
  }
539
- renderCode(qmlSource) {
540
- return this.renderThemeFiles(fromCodeString(qmlSource), "Main.qml");
690
+ renderCode(qmlSource, qmlVersion) {
691
+ return this.renderThemeFiles(fromCodeString(qmlSource), { entryFile: "Main.qml", qmlVersion });
692
+ }
693
+ /** Return the active default QML target version used when rendering. */
694
+ getQmlVersion() {
695
+ return this.qmlVersion;
696
+ }
697
+ /** Set the default QML target version for subsequent renders. */
698
+ setQmlVersion(version) {
699
+ if (this.destroyed) throw new Error("This QmlViewer has been destroyed.");
700
+ this.qmlVersion = normalizeQmlVersion(version);
541
701
  }
542
702
  /** Update the mock environment used by the current and subsequent previews. */
543
703
  setSddmConfig(config) {
@@ -586,11 +746,13 @@ var QmlViewer = class {
586
746
  };
587
747
  export {
588
748
  QmlViewer,
749
+ SUPPORTED_QML_VERSIONS,
589
750
  fromCodeString,
590
751
  fromFolderInput,
591
752
  fromGitHubRepo,
592
753
  fromSingleFile,
593
754
  fromZipFile,
594
755
  parseIni,
595
- parseThemeConfig
756
+ parseThemeConfig,
757
+ transformQmlImports
596
758
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "qmlbox",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "Render interactive Qt Quick QML and SDDM themes in a browser with Qt for WebAssembly",
5
5
  "license": "GPL-3.0-only",
6
6
  "keywords": [
@@ -42,7 +42,7 @@
42
42
  "wasm"
43
43
  ],
44
44
  "scripts": {
45
- "build": "tsup src/index.ts --format esm,cjs --dts --clean",
45
+ "build": "node scripts/sync-shims.mjs && tsup src/index.ts --format esm,cjs --dts --clean",
46
46
  "typecheck": "tsc --noEmit",
47
47
  "dev": "vite --open /example/",
48
48
  "prepack": "npm run build && node scripts/check-wasm.mjs",