File size: 6,205 Bytes
9bd422a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
/**
 * ShareableURL - Manages URL hash state for model sharing
 * Encodes/decodes model ID in URL hash so users can share direct links
 * to specific models from models.json.
 *
 * Format: #model=<modelId>  (e.g. #model=ppe)
 *
 * Requirements: 25.1, 25.2, 25.3, 25.4, 25.5
 */

class ShareableURL {
  constructor() {
    /** @type {Array<{id: string}>|null} Cached model list for validation */
    this._modelList = null;

    /** @type {Function|null} Unsubscribe from EventBus */
    this._unsubModelSelected = null;

    /** @type {Function|null} Unsubscribe from hashchange */
    this._boundHashChange = null;
  }

  // ─── Public API ───────────────────────────────────────────────────────────

  /**
   * Initialise the component. Call once after the model list is available.
   * @param {Array<{id: string}>} modelList - The models from models.json
   */
  init(modelList) {
    this._modelList = Array.isArray(modelList) ? modelList : [];

    // Listen for model:selected events to update the hash (Req 25.1)
    if (window.EventBus) {
      this._unsubModelSelected = window.EventBus.on(
        CONFIG.EVENTS.MODEL_SELECTED,
        (model) => this._onModelSelected(model)
      );
    }

    // Listen for hashchange so the browser back/forward buttons work
    this._boundHashChange = () => this._onHashChange();
    window.addEventListener('hashchange', this._boundHashChange);
  }

  /**
   * Read the current URL hash. If it contains a valid model ID, return
   * the matching model object so the caller can auto-select it.
   * If the ID is invalid, show an error and return null. (Req 25.2, 25.4)
   *
   * @returns {{ model: object|null, error: string|null }}
   */
  readHash() {
    const modelId = this._parseHash();

    if (!modelId) {
      return { model: null, error: null };
    }

    const model = this._findModelById(modelId);

    if (!model) {
      const errorMsg = `Model "${modelId}" not found. The shared link may be outdated or invalid.`;
      console.warn('[ShareableURL]', errorMsg);
      // Clear the invalid hash
      this._clearHash();
      return { model: null, error: errorMsg };
    }

    return { model, error: null };
  }

  /**
   * Set the URL hash to point to the given model ID. (Req 25.1)
   * Only applies to models from models.json (Req 25.5).
   * @param {string} modelId
   */
  setModel(modelId) {
    if (!modelId || !this._isListModel(modelId)) {
      return;
    }
    window.history.replaceState(null, '', '#model=' + encodeURIComponent(modelId));
  }

  /**
   * Read the model ID from the current URL hash.
   * @returns {string|null}
   */
  getModel() {
    return this._parseHash();
  }

  /**
   * Copy the current page URL (including hash) to the clipboard. (Req 25.3)
   * @returns {Promise<boolean>} true if copy succeeded
   */
  async copyToClipboard() {
    try {
      await navigator.clipboard.writeText(window.location.href);
      return true;
    } catch (err) {
      // Fallback for older browsers / insecure contexts
      return this._fallbackCopy(window.location.href);
    }
  }

  /**
   * Clean up event listeners.
   */
  destroy() {
    if (this._unsubModelSelected) {
      this._unsubModelSelected();
      this._unsubModelSelected = null;
    }
    if (this._boundHashChange) {
      window.removeEventListener('hashchange', this._boundHashChange);
      this._boundHashChange = null;
    }
  }

  // ─── Private ──────────────────────────────────────────────────────────────

  /**
   * Parse the URL hash and return the model ID, or null.
   * @returns {string|null}
   */
  _parseHash() {
    const hash = window.location.hash; // e.g. "#model=ppe"
    if (!hash || !hash.startsWith('#model=')) {
      return null;
    }
    const raw = hash.substring('#model='.length);
    const decoded = decodeURIComponent(raw).trim();
    return decoded || null;
  }

  /**
   * Clear the URL hash without triggering a page reload.
   */
  _clearHash() {
    window.history.replaceState(null, '', window.location.pathname + window.location.search);
  }

  /**
   * Find a model in the cached list by its id.
   * @param {string} modelId
   * @returns {object|null}
   */
  _findModelById(modelId) {
    if (!this._modelList) return null;
    return this._modelList.find((m) => m.id === modelId) || null;
  }

  /**
   * Check whether a model ID belongs to the models.json list (Req 25.5).
   * @param {string} modelId
   * @returns {boolean}
   */
  _isListModel(modelId) {
    return this._findModelById(modelId) !== null;
  }

  /**
   * Handle model:selected events from the EventBus.
   * Only update the hash for models that come from models.json (Req 25.5).
   * @param {object} model
   */
  _onModelSelected(model) {
    if (!model || !model.id) return;
    // Only set hash for list models, not uploaded files
    if (this._isListModel(model.id)) {
      this.setModel(model.id);
    }
  }

  /**
   * Handle browser hashchange (back/forward navigation).
   */
  _onHashChange() {
    const { model, error } = this.readHash();

    if (error && window.EventBus) {
      window.EventBus.emit(CONFIG.EVENTS.ERROR_OCCURRED, {
        message: error,
        type: 'warning'
      });
      return;
    }

    if (model && window.EventBus) {
      window.EventBus.emit(CONFIG.EVENTS.MODEL_SELECTED, model);
    }
  }

  /**
   * Fallback clipboard copy for environments without navigator.clipboard.
   * @param {string} text
   * @returns {boolean}
   */
  _fallbackCopy(text) {
    try {
      const textarea = document.createElement('textarea');
      textarea.value = text;
      textarea.style.position = 'fixed';
      textarea.style.opacity = '0';
      document.body.appendChild(textarea);
      textarea.select();
      const ok = document.execCommand('copy');
      document.body.removeChild(textarea);
      return ok;
    } catch (_) {
      return false;
    }
  }
}

// Export as global for browser usage
window.ShareableURL = ShareableURL;