Spaces:
Paused
Paused
File size: 6,502 Bytes
88bdcff f3ebc82 88bdcff |
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 |
"""localStorage integration for Gradio via JavaScript injection.
Provides JavaScript code that syncs session state with browser localStorage.
"""
# localStorage keys
STORAGE_KEY_SESSION = "fdam_current_session"
STORAGE_KEY_HISTORY = "fdam_assessment_history"
STORAGE_KEY_IMAGES = "fdam_image_refs" # References only, not actual bytes
# JavaScript code for localStorage operations
LOCALSTORAGE_JS = """
<script>
(function() {
// FDAM localStorage utilities
window.fdamStorage = {
KEYS: {
SESSION: 'fdam_current_session',
HISTORY: 'fdam_assessment_history',
IMAGE_REFS: 'fdam_image_refs'
},
// Save current session
saveSession: function(sessionJson) {
try {
localStorage.setItem(this.KEYS.SESSION, sessionJson);
console.log('[FDAM] Session saved to localStorage');
return true;
} catch (e) {
console.error('[FDAM] Failed to save session:', e);
return false;
}
},
// Load current session
loadSession: function() {
try {
const data = localStorage.getItem(this.KEYS.SESSION);
if (data) {
console.log('[FDAM] Session loaded from localStorage');
return data;
}
} catch (e) {
console.error('[FDAM] Failed to load session:', e);
}
return null;
},
// Save assessment history
saveHistory: function(historyJson) {
try {
localStorage.setItem(this.KEYS.HISTORY, historyJson);
console.log('[FDAM] History saved to localStorage');
return true;
} catch (e) {
console.error('[FDAM] Failed to save history:', e);
return false;
}
},
// Load assessment history
loadHistory: function() {
try {
const data = localStorage.getItem(this.KEYS.HISTORY);
if (data) {
console.log('[FDAM] History loaded from localStorage');
return data;
}
} catch (e) {
console.error('[FDAM] Failed to load history:', e);
}
return null;
},
// Clear all FDAM data
clearAll: function() {
try {
localStorage.removeItem(this.KEYS.SESSION);
localStorage.removeItem(this.KEYS.HISTORY);
localStorage.removeItem(this.KEYS.IMAGE_REFS);
console.log('[FDAM] All localStorage data cleared');
return true;
} catch (e) {
console.error('[FDAM] Failed to clear storage:', e);
return false;
}
},
// Get storage usage info
getStorageInfo: function() {
try {
let total = 0;
for (let key in localStorage) {
if (key.startsWith('fdam_')) {
total += localStorage.getItem(key).length;
}
}
return {
used_bytes: total,
used_kb: (total / 1024).toFixed(2),
limit_kb: 5120 // ~5MB typical limit
};
} catch (e) {
return { error: e.message };
}
}
};
// Expose to global scope for Gradio callbacks
window.saveSession = window.fdamStorage.saveSession.bind(window.fdamStorage);
window.loadSession = window.fdamStorage.loadSession.bind(window.fdamStorage);
window.saveHistory = window.fdamStorage.saveHistory.bind(window.fdamStorage);
window.loadHistory = window.fdamStorage.loadHistory.bind(window.fdamStorage);
console.log('[FDAM] localStorage utilities loaded');
})();
</script>
"""
# JavaScript functions for Gradio event handlers
JS_SAVE_SESSION = """
async (sessionJson) => {
if (window.fdamStorage) {
window.fdamStorage.saveSession(sessionJson);
}
return sessionJson;
}
"""
JS_LOAD_SESSION = """
async () => {
if (window.fdamStorage) {
return window.fdamStorage.loadSession() || '{}';
}
return '{}';
}
"""
JS_SAVE_HISTORY = """
async (historyJson) => {
if (window.fdamStorage) {
window.fdamStorage.saveHistory(historyJson);
}
return historyJson;
}
"""
JS_LOAD_HISTORY = """
async () => {
if (window.fdamStorage) {
return window.fdamStorage.loadHistory() || '{"assessments":[],"current_session_id":null}';
}
return '{"assessments":[],"current_session_id":null}';
}
"""
# JavaScript to auto-load session on page load
JS_AUTO_LOAD = """
async () => {
// Small delay to ensure Gradio is fully loaded
await new Promise(resolve => setTimeout(resolve, 500));
if (window.fdamStorage) {
const session = window.fdamStorage.loadSession();
const history = window.fdamStorage.loadHistory();
return [session || '{}', history || '{"assessments":[],"current_session_id":null}'];
}
return ['{}', '{"assessments":[],"current_session_id":null}'];
}
"""
def get_head_html(additional_scripts: str = "") -> str:
"""Get HTML to inject into Gradio head for localStorage support.
Args:
additional_scripts: Optional additional HTML/JS to include.
Returns:
Combined HTML string for head injection.
"""
return LOCALSTORAGE_JS + additional_scripts
def create_save_trigger_js(field_updates: dict[str, str]) -> str:
"""Create JavaScript that triggers save after field updates.
Args:
field_updates: Mapping of field name to value expression
Returns:
JavaScript code string
"""
updates = ", ".join(f'"{k}": {v}' for k, v in field_updates.items())
return f"""
async (currentSession, ...values) => {{
try {{
const session = JSON.parse(currentSession || '{{}}');
const updates = {{ {updates} }};
Object.assign(session, updates);
session.updated_at = new Date().toISOString();
const newSession = JSON.stringify(session);
if (window.fdamStorage) {{
window.fdamStorage.saveSession(newSession);
}}
return newSession;
}} catch (e) {{
console.error('[FDAM] Save trigger error:', e);
return currentSession;
}}
}}
"""
|